Tuesday, March 30, 2010

Get Nth Max Salary

Data Base used for the query processing :-

Table Name Employee
pkid Name Salary
1 apekshit 5000
2 gaurav 6000
3 sunil 7000
4 rajnish 6500
5 amit 8000

For finding Nth highest salary from a table without using TOP, GROUP BY AND ROW COUNT or any other SQL Keywords,

There are two options for this :-

1. OPTION

SELECT TOP 1 SALARY FROM (SELECT DISTINCT TOP N SALARY
FROM EMPLOYEE ORDER BY SALARY DESC)a
ORDER BY SALARY



2. OPTION

SELECT MAX(SALARY) FROM EMPLOYEE as E1
WHERE N=(SELECT COUNT(DISTINCT SALARY)
FROM EMPLOYEE E2 WHERE E1.SALARY<=E2.SALARY)

PASS THE NUMBER N VALUE...

Tuesday, March 23, 2010

Find Active IP Addresses Only with Mac Address

private void FillGrid()
{
Process netsend = new Process();
netsend.StartInfo.FileName = "net.exe";
netsend.StartInfo.CreateNoWindow = true;
netsend.StartInfo.Arguments = "view";
netsend.StartInfo.RedirectStandardOutput = true;
netsend.StartInfo.UseShellExecute = false;
netsend.StartInfo.RedirectStandardError = true;
netsend.Start();

StreamReader sr = new StreamReader(netsend.StandardOutput.BaseStream, netsend.StandardOutput.CurrentEncoding);

DataTable myDataTable = new DataTable();

DataColumn myDataColumn;
DataRow myDataRow;



myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "ServerName";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "IpAddress";
myDataTable.Columns.Add(myDataColumn);

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "MacAddress";
myDataTable.Columns.Add(myDataColumn);

ArrayList Name = new ArrayList();
ArrayList IpAddress = new ArrayList();

int i = 0;
string sss = "";
try
{
while ((sss = sr.ReadLine()) != null)
{
if (sss.StartsWith("\\"))
{
myDataRow = myDataTable.NewRow();
Name.Add(sss.Substring(2).Substring(0, sss.Substring(2).IndexOf(" ")).ToUpper());
if (Name[i].ToString() != "PS1")
{
myDataRow["ServerName"] = Name[i].ToString();
IPHostEntry myIP = System.Net.Dns.GetHostByName(Name[i].ToString());
IPAddress[] addr = myIP.AddressList;
myDataRow["IpAddress"] = addr[0].ToString();
myDataRow["MacAddress"] = GetMacAddress(addr[0].ToString());
myDataTable.Rows.Add(myDataRow);
i++;
}
}
}
dataGrid1.DataSource = myDataTable;

}
catch { }
}

Find All Ip Addresses on Lan

private void button1_Click(object sender, EventArgs e)
{
DirectoryEntry de = new DirectoryEntry();
ArrayList computer_name = new ArrayList();

de.Path = "WinNT://" + "yoursite.com";
foreach (DirectoryEntry d in de.Children)
{
if (d.SchemaClassName == "Computer")
{
computer_name.Add(d.Name);
}
}

foreach (string cn in computer_name)
{
GetAllIP(cn);

}
}


public void GetAllIP(string args)
{
try
{
string strHostName = "";
ArrayList ipaddr = new ArrayList();
ArrayList hostname = new ArrayList();

IPHostEntry ipEntry = Dns.GetHostByName(args);

IPAddress[] addr = ipEntry.AddressList;

int i = 0;

listBox1.Items.Add(addr[i].ToString());
listBox2.Items.Add(args);

}
catch { }
}

Wednesday, March 10, 2010

Remove Duplicate Records From Table With Sql Server 2005

--FOR CREATING TABLE USE THIS QUERY

CREATE TABLE Duplicate(
ID INT,
FNAME VARCHAR(10),
MNAME VARCHAR(10)
)

--FOR INSERT VALUES IN CREATED TABLE USE THIS QUERY

INSERT INTO Duplicate VALUES(1, 'AAA','CCC')
INSERT INTO Duplicate VALUES(2, 'BBB','DDD')
INSERT INTO Duplicate VALUES(1, 'AAA','CCC')
INSERT INTO Duplicate VALUES(2, 'BBB','DDD')
INSERT INTO Duplicate VALUES(1, 'AAA','CCC')
INSERT INTO Duplicate VALUES(2, 'BBB','DDD')
INSERT INTO Duplicate VALUES(3, 'BCB','DGD')

--FOR DISPLAY ALL RECORDS USE THIS QUERY

SELECT * FROM Duplicate

--FOR SELECT DUPLICATE DATA USE THIS QUERY

WITH CTE as(
SELECT ROW_NUMBER() OVER(PARTITION BY ID, FName, Mname ORDER BY (SELECT 1)) AS RowID,
*
FROM Duplicate
)
DELETE FROM CTE WHERE RowID > 1

--FOR DELETE DUPLICATE DATE USE THIS QUERY

WITH CTE as(
SELECT ROW_NUMBER() OVER(PARTITION BY ID, FName, MName ORDER BY (SELECT 1)) AS RowID,
*
FROM Duplicate
)
SELECT ID, FName, MName
FROM CTE
WHERE RowID > 1

Thursday, March 4, 2010

How to add click event for dynamically generated button

Hi,

In this article iam going to discuss about adding onclick

event to a dynamically generated button.See the code below

TextBox txt = new TextBox();
Button btn = new Button();
Label lbl = new Label();
protected void Page_Load(object sender, EventArgs e)
{
lbl.Text = "Enter Text : ";
lbl.Font.Bold = true;

this.Form.Controls.Add(lbl);
this.Form.Controls.Add(txt);
btn.Text = "btnsave";
btn.Attributes.Add("runat", "server");
this.Form.Controls.Add(btn);
btn.Click += new System.EventHandler(this.Button_Click);


}

protected void Button_Click(object sender, EventArgs e)
{
Response.Write(txt.Text);

}

Thanks & Regards
Umar Daraj

Microsoft .NET Framework 4.0

Microsoft .NET Framework

The Microsoft .NET Framework is a software framework that can be installed on computers running Microsoft Windows operating systems. It includes a large library of coded solutions to common programming problems and a virtual machine that manages the execution of programs written specifically for the framework. The .NET Framework is a Microsoft offering and is intended to be used by most new applications created for the Windows platform.

In this articles we talk about Microsoft .NET Framework 4.0

What’s new in .NET Framework 4.0?

1. Next versions of Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) will provide better support for Web 2.0 technologies like REST, POX, and ATOM.

2. Performance and Scalability of WCF and WF are expected to increase by minimum 10X.

3. New workflow models.

4. Seamless integration between WCF and WF including a new Visual Designer.

5. Parallel Programming framework using PLINQ, Task Parallel Library and Coordination Data Structures to better utilize power of multi-processor and multi-core machines.

6. Build declarative applications with WF, WCF and WPF using XAML. So, XAML is no more only for WPF and WF.

7. WCF enhancements:

1. RESTful enhancements

1. Simplifying the building of REST Singleton & Collection Services, ATOM Feed and Publishing Protocol Services, and HTTP Plain XML Services using WCF

2. WCF REST Starter Kit to be released on Codeplex to get early feedback

2. Messaging enhancements

1. Transports - UDP, MQ, Local in-process

2. Protocols - SOAP over UDP, WS-Discovery, WS-Business Activity, WS-I BP 1.2

3. Duplex durable messaging

3. Correlation enhancements

1. Content and context driven, One-way support

4. Declarative Workflow Services

1. Seamless integration between WF and WCF and unified XAML model

2. Build entire application in XAML, from presentation to data to services to workflow

8. WF enhancements:

1. Significant improvements in performance and scalability

1. Ten-fold improvement in performance

2. New workflow flow-control models and pre-built activities

1. Flowcharts, rules

2. Expanded built-in activities – Power Shell, database, messaging, etc.

3. Enhancements in workflow modeling

1. Persistence control, transaction flow, compensation support, data binding and scoping

2. Rules composable and seamlessly integrated with workflow engine

4. Updated visual designer

1. Easier to use by end-users

2. Easier to rehost by ISVs

3. Ability to debug XAML

Thanks & Regards
Umar Daraj

Wednesday, March 3, 2010

Mvc architecture

Model View Controller

Model view controller is nothing but a design pattern used to achieve customizability in our application. Change is the only thing in the world, which will never change. All the products that we develop to our clients will undergo many changes. To accommodate these changes we should concentrate more on our design. Directly jumping in to the code may give quick solutions to our problem but they will not solve our future problems of customizability and re-usability. So friends in this article we will discuss about MVC a most popular design pattern, which helps us to overcome most of our problems. Initially we may feel that this design pattern will need more time before starting the development. Yes it is true, but the time, which we spend on design, will give some fruitful benefits.

Good Layering Approach

MVC follows the most common approach of Layering. Layering is nothing but a logical split up of our code in to functions in different classes. This approach is well known and most accepted approach. The main advantage in this approach is re-usability of code. Good example of layering approach is UI, Business Logic, and Data Access layer. Now we need to think how we can extend this approach to give us another great advantage customizability. The answer to this is using Inheritance. Inheritance is one of the powerful concepts in oops. .Net supports this in a nice way.

Visual Inheritance in .Net

Before getting in to Visual Inheritance, we will discuss the basic difference between Inheritance and Interfaces.

Inheritance -- what it is?
Interfaces -- How it should be? (It’s a contract)

Both these answers target the classes, which we are designing in our application. Many of us know this definition but we will not use this extensively in our application including me. Unless we work in a design, which uses these concepts to a great extent, we will not agree this. Many of the Microsoft products use this to a great extent. For example how Commerce Server pipeline components achieves the customizability. Commerce Server allows us to create our own component in com and allow us to add it as one of a stage in the pipeline. How they achieve this, only through interfaces. We need to create a com component and the com component should implement a interface. All the objects in our .Net Framework class libraries are inherited from System.Object. This tells us the importance of Inheritance.

Jumping into Visual Inheritance

Let's try out one of .Net most interesting feature, Visual Inheritance. What exactly is it? Now we do know what is inheritance right? No I don't mean the money that you get from your parents/grand parents, I'm talking about class and interface inheritance, which saves you the headache of re-typing code and provides the luxury of code reusability. Now wouldn't it be nice if the same feature that applies to classes and their methods could also be applied to the GUI forms that we create, I mean create a base form with our corporate logo so that it appears on all of the firm's screens? Well such a feature now exists! Yes, you've guessed it, its Visual Inheritance! Visual Inheritance alone will not solve our problem of extensibility. This will help us to start digging our mind for solution. Cool guys now we will directly jump in to our problem with a good example.

Problem Statement

I have an employee master screen, which takes Name and Age as inputs and save the same in our database.



Lets assume this is my basic functionality in my product, which serves most of my customer’s requirement. Now let us assume one of my new client asks for a change in this form. He needs an additional field in this form, which takes the employee’s address and stores the same in the database. How will we achieve this? Normally we will create a new screen which will also has a textbox to get the address input, in the same time we will also add another column in the employee master table and supply the new binaries and modified table and stored procedure scripts to the client. Do you think this is the right approach? If you ask me this is one of the crude way to satisfy an customer. Requirement like this will be very easy to re-write the entire code. But think if a customer asks a change in Payroll Calculation logic. Re-writing code for some specific customers will not helps us in long run. This will end up in maintaining separate – separate Visual source safe for each and every client. These types of solutions are very difficult to handle and after some time we will feel that we have a messy code.

The right way to solve this problem is by having a good design pattern in place and make sure that the entire team clearly understands the design and implements the same in their code. We can solve this by doing a layered approach using MVC and Visual Inheritance.

Solution to our problem

1. Don’t alter the table add another table which stores the additional columns like address and the junction/extended table should have a foreign key relationship with our main employee table.
2. Create a new Inherited form, which inherits from our main employee master screen. To use Visual Inheritance we need to change the Access Modifiers to Protected from Friend. By default VS .Net puts the access modifier as friend.

View Layer

Our View /UI layer should only have UI related validations in it. We should not have any Business Logic in to it. This gives us the flexibility to change the UI at any time and we can also have different UI for different customers. We can even have web based UI for some of the clients.

Controller /Director

Controller is the layer, which responds to the events in the UI. For example Save button click on my employee master screen. This layer should act as an intermediate between our View and Model. Initially we may think that this layer is not necessary. I am also not convinced with this layer. But still we need to think. May be after some days we will get answer for this. This layer will act as just event redirector.

Model

This layer has all our business logic. This is the most important layer. This layer will have our core functionality. This layer should be designed in such a way that out core and complex logic should be designed as functions and these function should be marked as overridable so that the inheriting classes can re-use the logic or override the logic. We should not make all the functions in the layer as overridable this may raise some security threats.

Database Operations

All the database operations should be done in the Model base class. All the inheriting classes should call this method to do database updates. The design can be like this. In my EmpModel base class I will have a protected array list which will store all the objects which needs to get updated. All the classes which inherits this class should add there objects to this array list and they should call the base class Update method. This helps us to do all the db operations in a single transaction.

For example in our example, we should create an EmployeeBase class, which will have properties for name and age. Our EmpModelBase should have a new instantiated EmployeeBase object and our view should fill the object properties. Finally the view will call the controller’s Save method and the controller should call the Model save method, there we will add the Employee object to the array list and the function should call the mybase.Update method. This method should loop through the array list and it should fire corresponding db update statements. This is just an example. We need to enhance this depending upon our requirement.

Conclusion

1. Layering Approach helps us a lot and we need to enhance it to get full customizability.
2. We need to enhance this with all our design knowledge.
3. No IDE enforces these patterns, it is up to us to do clean and disciplined way of coding.
4. Once we are used to these approaches / patterns then we are addicted to it.


Thanks & Regards
Umar Daraj