Saturday, February 26, 2011

how to get total number of working days in a month?

WITH c AS
     (SELECT     TRUNC (sysdate, 'MM') + ROWNUM - 1 n,rownum
       FROM DUAL
      CONNECT BY ROWNUM <= (TRUNC (sysdate) - TRUNC (sysdate, 'MM'))+1)
SELECT sum(decode(to_char(n,'D'),7,0,6,0,1)) weekdays
  FROM c




How to get total no. of weeks in a month in oracle?

WITH c AS
     (SELECT     TRUNC (sysdate, 'MM') + ROWNUM - 1 n,rownum
       FROM DUAL
      CONNECT BY ROWNUM <= (TRUNC (sysdate) - TRUNC (sysdate, 'MM'))+1)
SELECT sum(decode(to_char(n,'D'),7,1,0)) weekdays
  FROM c


OUTPUT:
                  WeekDays
                         4








Monday, February 21, 2011

Configuration setting for using code with different language

<system.web>
    <compilation>
        <codeSubDirectories>
            <add directoryName="VB"/>
            <add directoryName="CSHARP"/>
        </codeSubDirectories>
    </compilation>
</system.web>

Configuration setting for using different version of an assembly

<configurations>
<runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
</configurations>

Friday, February 11, 2011

Delete Duplicate Rows in Microsoft SQL Server



Microsoft SQL Server tables should never contain duplicate rows, nor non-unique primary keys. For brevity, we will sometimes refer to primary keys as "key" or "PK" in this article, but this will always denote "primary key." Duplicate PKs are a violation of entity integrity, and should be disallowed in a relational system. SQL Server has various mechanisms for enforcing entity integrity, including indexes, UNIQUE constraints, PRIMARY KEY constraints, and triggers.

Despite this, under unusual circumstances duplicate primary keys may occur, and if so they must be eliminated. One way they can occur is if duplicate PKs exist in non-relational data outside SQL Server, and the data is imported while PK uniqueness is not being enforced. Another way they can occur is through a database design error, such as not enforcing entity integrity on each table.

Often duplicate PKs are noticed when you attempt to create a unique index, which will abort if duplicate keys are found. This message is:
Msg 1505, Level 16, State 1 Create unique index aborted on duplicate key.
If you are using SQL Server 2000 or SQL Server 2005, you may receive the following error message:
Msg 1505, Level 16, State 1 CREATE UNIQUE INDEX terminated because a duplicate key was found for object name '%.*ls' and index name '%.*ls'. The duplicate key value is %ls.
This article discusses how to locate and remove duplicate primary keys from a table. However, you should closely examine the process which allowed the duplicates to happen in order to prevent a recurrence.
For this example, we will use the following table with duplicate PK values. In t...
For this example, we will use the following table with duplicate PK values. In this table the primary key is the two columns (col1, col2). We cannot create a unique index or PRIMARY KEY constraint since two rows have duplicate PKs. This procedure illustrates how to identify and remove the duplicates.
create table t1(col1 int, col2 int, col3 char(50))
insert into t1 values (1, 1, 'data value one')
insert into t1 values (1, 1, 'data value one')
insert into t1 values (1, 2, 'data value two')
The first step is to identify which rows have duplicate primary key values:
SELECT col1, col2, count(*)
FROM t1
GROUP BY col1, col2
HAVING count(*) > 1
This will return one row for each set of duplicate PK values in the table. The last column in this result is the number of duplicates for the particular PK value.
Collapse this tableExpand this table
col1
col2

1 1 2


If there are only a few sets of duplicate PK values, the best procedure is to delete these manually on an individual basis. For example:
set rowcount 1
delete from t1
where col1=1 and col2=1
The rowcount value should be n-1 the number of duplicates for a given key value. In this example, there are 2 duplicates so rowcount is set to 1. The col1/col2 values are taken from the above GROUP BY query result. If the GROUP BY query returns multiple rows, the "set rowcount" query will have to be run once for each of these rows. Each time it is run, set rowcount to n-1 the number of duplicates of the particular PK value.

Before deleting the rows, you should verify that the entire row is duplicate. While unlikely, it is possible that the PK values are duplicate, yet the row as a whole is not. An example of this would be a table with Social Security Number as the primary key, and having two different people (or rows) with the same number, each having unique attributes. In such a case whatever malfunction caused the duplicate key may have also caused valid unique data to be placed in the row. This data should copied out and preserved for study and possible reconciliation prior to deleting the data.

If there are many distinct sets of duplicate PK values in the table, it may be too time-consuming to remove them individually. In this case the following procedure can be used:
  1. First, run the above GROUP BY query to determine how many sets of duplicate PK values exist, and the count of duplicates for each set.
  2. Select the duplicate key values into a holding table. For example:
  3. SELECT col1, col2, col3=count(*)
  4. INTO holdkey
  5. FROM t1
  6. GROUP BY col1, col2
  7. HAVING count(*) > 1
  1. Select the duplicate rows into a holding table, eliminating duplicates in the process. For example:
  2. SELECT DISTINCT t1.*
  3. INTO holddups
  4. FROM t1, holdkey
  5. WHERE t1.col1 = holdkey.col1
  6. AND t1.col2 = holdkey.col2
  1. At this point, the holddups table should have unique PKs, however, this will not be the case if t1 had duplicate PKs, yet unique rows (as in the SSN example above). Verify that each key in holddups is unique, and that you do not have duplicate keys, yet unique rows. If so, you must stop here and reconcile which of the rows you wish to keep for a given duplicate key value. For example, the query:
  2. SELECT col1, col2, count(*)
  3. FROM holddups
  4. GROUP BY col1, col2
should return a count of 1 for each row. If yes, proceed to step 5 below. If no, you have duplicate keys, yet unique rows, and need to decide which rows to save. This will usually entail either discarding a row, or creating a new unique key value for this row. Take one of these two steps for each such duplicate PK in the holddups table.
  1. Delete the duplicate rows from the original table. For example:
  2. DELETE t1
  3. FROM t1, holdkey
  4. WHERE t1.col1 = holdkey.col1
  5. AND t1.col2 = holdkey.col2
  1. Put the unique rows back in the original table. For example:
  2. INSERT t1 SELECT * FROM holddups

Tuesday, February 8, 2011

What is Event?

The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of "publisher and subscribers." In this model, you have publishers who will do some logic and publish an "event." Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.
In C#, any object can publish a set of events to which other applications can subscribe. When the publishing class raises an event, all the subscribed applications are notified. The following figure shows this mechanism.
Conventions
The following important conventions are used with events:
  • Event Handlers in the .NET Framework return void and take two parameters.
  • The first paramter is the source of the event; that is the publishing object.
  • The second parameter is an object derived from EventArgs.
  • Events are properties of the class publishing the event.
  • The keyword event controls how the event property is accessed by the subscribing classes.
Example


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace IILButton
{
     public class MyClass
    {
        public delegate void LogHandler(string Message);
        public event LogHandler Log;
        public void Process()
        {
            OnLog("Process() Begin");
            OnLog("Process() End");
        }
        protected void OnLog(string Message)
        {
            if (Log != null)
            {
                Log(Message);
            }
        }
}
public class FileLogger
{
    FileStream fs;
    StreamWriter sw;
    public FileLogger(string FileName)
    {
        fs = new FileStream(FileName, FileMode.OpenOrCreate);
        sw = new StreamWriter(fs);
    }
    public void Logger(string s)
    {
        sw.WriteLine(s);
    }
    public void Close()
    {
        sw.Close();
        fs.Close();
    }
  }
}
on Button Click
FileLogger fl = new FileLogger("C:/Process.log");
MyClass mycls = new MyClass();
mycls.Log += new MyClass.LogHandler(Logger);
mycls.Log += new MyClass.LogHandler(fl.Logger);
mycls.Process();
fl.Close();

On Page
protected void Logger(string s)
{
Response.Write(s);
}

What is Multicast Delegate?


It is a delegate which holds the reference of more than one method. 
Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

 delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y)
{
Console.WriteLine("You r in Method 1");
}

static void Method2(int x, int y)
{
Console.WriteLine("You r in Method 2");
}

public static void "on" />Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.
In the main method, the Delegate object is created using the following statement: 
Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using the -= operator.
 

What is a Delegate?

Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegate delegate_name()
Example:

public delegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate


public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}

Explanation

Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:

delObj(v1,v2);
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Monday, February 7, 2011

Interfaces vs. Abstract Classes




Feature
Interface
Abstract class
Multiple inheritance
A class may implement several interfaces.
A class may extend only one abstract class.
Default implementation
An interface cannot provide any code at all, much less default code.
An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Constants
Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional.
Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
Third party convenience
An interface implementation may be added to any existing third party class.
A third party class must be rewritten to extend only from the abstract class.

What is the difference between the Destructor and the Finalize() method? When does the Finalize() method get called?


Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.