Sunday, March 1, 2015

What is the Equivalent of C#'s DateTime.Now in Java?

How do I get the current date in Java?
In C# it is DateTime.Now



Just construct a new Date object without any arguments; this will assign the current date and time to the new object.

import java.util.Date;

Date d = new Date();

In the words of the Javadocs for the zero-argument constructor:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

NOTE: Make sure you're using java.util.Date and not java.sql.Date
java.sql.Date doesn't have a zero-arg constructor, and it has somewhat different semantics

Also note that GregorianCalendar and many similar objects work the same way.
So whatever type of date/calendar object you are working with, the zero-argument constructor usually initializes the object to the current date/time.

The Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings.

Please consider new Java8 APIs - LocalDateTime.now() and ZonedDateTime.now()
More info can be found at http://stackoverflow.com/questions/2010284/equivalent-of-cs-datetime-now-in-java?rq=1
and
http://stackoverflow.com/questions/5175728/how-to-get-the-current-date-time-in-java/26225884#26225884

Tuesday, February 24, 2015

GoDaddy $1 Domain names - Coupon Codes


cjccoup149
.COM Domain name $1.49
valid until April 30, 2015

cjccoup99
.COM Domain name $0.99
valid until April 30, 2015

cjceb99
.COM Domain name $0.99
valid until February 28, 2015

What is the difference of .jar file vs .war file in Java?

These files are simply zipped files using the java jar tool. These files are created for different purposes. Here is the description of these files:

.jar files: The .jar files contain libraries, resources and accessories files like property files.
.war files: The war file contains the web application that can be deployed on any servlet/jsp container. The .war file contains jsp, html, javascript and other files necessary for the development of web applications.


More info is at the links:
http://stackoverflow.com/questions/5871053/java-war-vs-jar-what-is-the-difference
http://www.java-tips.org/java-ee-tips/enterprise-java-beans/difference-between-ear-jar-and-war.html

Confirmation Message Box in ASP.NET using VB.NET



Public Sub CreateConfirmationAlert(ByRef page As System.Web.UI.Page, ByVal message As String, ByVal key As String)

        Dim script As String = "<script language=JavaScript>var bReturn; bReturn = confirm('" &    message & "');</script>"

If (Not page.ClientScript.IsStartupScriptRegistered(key)) Then
            page.ClientScript.RegisterStartupScript(HttpContext.Current.CurrentHandler.GetType(),       key, script)
       End If

    End Sub

Connection Pooling in Entity Framework

Question:
I've recently started to use the Entity Framework in my .NET application and am curious about a few things relating to pooling.

Connection pooling as I know is managed by the ADO.NET data provider, in my case that of MS SQL server. Does this apply when you instantiate a new entities context (ObjectContext), i.e. the parameterless new MyDatabaseModelEntities()?

What are the advantages and disadvantages of a) creating a global entities context for the application (i.e. one static instance) or b) creating and exposing an entities context for each given operation/method, with a using block.

Any other recommendations, best practices, or common approaches for certain scenarios that I should know about?



Answer:
Connection pooling is handled as in any other ADO.NET application. Entity connection still uses traditional database connection with traditional connection string. I believe you can turn off connnection pooling in connection string if you don't want to use it. (read more about SQL Server Connection Pooling (ADO.NET))
Never ever use global context. ObjectContext internally implements several patterns including Identity Map and Unit of Work. Impact of using global context is different per application type.
For web applications use single context per request. For web services use single context per call. In WinForms or WPF application use single context per form or per presenter. There can be some special requirements which will not allow to use this approach but in most situation this is enough.
If you want to know what impact has single object context for WPF / WinForm application check this article. It is about NHibernate Session but the idea is same.

When you use EF it by default loads each entity only once per context. The first query creates entity instace and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.

Any changes made to the entity are not persisted until you call SaveChanges on the context. You can do changes in multiple entities and store them at once. This is called Unit of Work pattern. You can't selectively say which modified attached entity you want to save.

Combine these two patterns and you will see some interesting effects. You have only one instance of entity for the whole application. Any changes to the entity affect the whole application even if changes are not yet persisted (commited). In the most times this is not what you want. Suppose that you have an edit form in WPF application. You are working with the entity and you decice to cancel complex editation (changing values, adding related entities, removing other related entities, etc.). But the entity is already modified in shared context. What will you do? Hint: I don't know about any CancelChanges or UndoChanges on ObjectContext.

I think we don't have to discuss server scenario. Simply sharing single entity among multiple HTTP requests or Web service calls makes your application useless. Any request can just trigger SaveChanges and save partial data from another request because you are sharing single unit of work among all of them. This will also have another problem - context and any manipulation with entities in the context or a database connection used by the context is not thread safe.

Even for a readonly application a global context is not a good choice because you probably want fresh data each time you query the application.

More info at: http://stackoverflow.com/questions/3653009/entity-framework-and-connection-pooling
and https://msdn.microsoft.com/en-us/library/8xx3tyca.aspx

namevine - Instantly Find A Domain Name

Create A Consistent Online Presence

Instantly Find A Domain Name With Matching Social Media Profiles

Null Object Pattern in C#

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

For example, a function may retrieve a list of files in a folder and perform some action on each. In the case of an empty folder, one response may be to throw an exception or return a null reference rather than a list. Thus, the code which expects a list must verify that it in fact has one before continuing, which can complicate the design.

By returning a null object (i.e. an empty list) instead, there is no need to verify that the return value is in fact a list. The calling function may simply iterate the list as normal, effectively doing nothing. It is, however, still possible to check whether the return value is a null object (e.g. an empty list) and react differently if desired.

The null object pattern can also be used to act as a stub for testing, if a certain feature such as a database is not available for testing.



C# is a language in which the Null Object pattern can be properly implemented. This example shows animal objects that display sounds and a NullAnimal instance used in place of the C# null keyword. The Null Object provides consistent behaviour and prevents a runtime Null Reference Exception that would occur if the C# null keyword were used instead.

using System;

static class Program
{
    static void Main()
    {
        IAnimal dog = new Dog();
        dog.MakeSound(); // outputs "Woof!"

        /* Instead of using C# null, use a NullAnimal instance.
         * This example is simplistic but conveys the idea that if a NullAnimal instance is used then the program
         * will never experience a .NET System.NullReferenceException at runtime, unlike if C# null was used.
         */
        IAnimal unknown = new NullAnimal();  //<< replaces: IAnimal unknown = null;
        unknown.MakeSound(); // outputs nothing, but does not throw a runtime exception      
    }
}

// Animal interface is the key to compatibility for Animal implementations below.
interface IAnimal
{
    void MakeSound();
}

// Dog is a real animal.
class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("Woof!");
    }
}

// The Null Case: this NullAnimal class should be instantiated and used in place of C# null keyword.
class NullAnimal : IAnimal
{
    public void MakeSound()
    {
        // Purposefully provides no behaviour.
    }
}
More information about Null Object Pattern can be found on http://en.wikipedia.org/wiki/Null_Object_pattern#C.23
and also on http://www.cs.oberlin.edu/~jwalker/nullObjPattern/

Monday, February 23, 2015

What is Software Design Pattern?

Patterns originated as an architectural concept by Christopher Alexander (1977/79). In 1987, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming and presented their results at the OOPSLA conference that year. In the following years, Beck, Cunningham and others followed up on this work.


Design patterns gained popularity in computer science after the book Design Patterns: Elements of Reusable Object-Oriented Software was published in 1994 by the so-called "Gang of Four" (Gamma et al.), which is frequently abbreviated as "GoF". That same year, the first Pattern Languages of Programming Conference was held and the following year, the Portland Pattern Repository was set up for documentation of design patterns.

For more info, visit the links below:
http://en.wikipedia.org/wiki/Software_design_pattern
http://en.wikipedia.org/wiki/Design_Patterns
http://en.wikipedia.org/wiki/Gang_of_Four_(disambiguation)