Search This Blog

Monday, June 25, 2012

Delete duplicate records or rows in sql server

Our datatable does not contain any primary key column because of that it contains duplicate records that would be like this
Actually above table does not contain any primary key column because of that same type of records exist.
Now I want to get duplicate records from datatable for that we need to write query like this
WITH tempTable as
(
SELECT ROW_NUMBER() Over(PARTITION BY Name,Position ORDER BY Name) As RowNumber,* FROM EmployeData
)
SELECT * FROM tempTable
Once we run above query we will get data like this
If you observe above table I added another column RowNumber this column is used to know which record contains duplicate values based on rows with RowNumber greater than 1.  
Now we want to get the records which contains unique value from datatable for that we need to write the query like this
WITH tempTable as
(
SELECT ROW_NUMBER() Over(PARTITION BY Name,Position ORDER BY Name) As RowNumber,* FROM EmployeData
)
DELETE FROM tempTable where RowNumber >1
SELECT * FROM EmployeData order by Id asc
Once we run above query all duplicate records will delete from our table and that would be like this

Sunday, June 24, 2012

Water Mark Text using JQUERY


Implementation

Step 1

Let’s start to create a simple page with two textbox using visual studio 2008 as below.
Design Output
Image Loading
HTML Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <table cellpadding="2" width="250px" style="border:solid 1px gray;" 
           cellspacing="2">
        <tr>
            <td colspan="3" align="center">
                <b>Welcome to Signin</b>
            </td>
        </tr>
        <tr>
            <td colspan="3" style="height: 5px;">
            </td>
        </tr>
        <tr>
            <td>
                User Name
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                Password
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtpass" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="3" style="height: 5px;">
            </td>
        </tr>
        <tr>
            <td colspan="3" align="right">
                <asp:Button ID="btnSign" runat="server" Text="Sign In" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
The above login is screen is very simple screen has two input field with one button. Now I’m going to work for display water mark for both input fields. To that we have to import JQuery library and then have to write a simple CSS to apply for water mark with JQuery.

Step 2

Import JQuery library from Google under the HEAD section, like below
<head runat="server">
    <title>The Watermark Demonstration</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" 
            type="text/javascript"></script>
</head>

 Step 3

Let’s create a simple style to apply watermark effect to username and password textbox.
<head runat="server">
    <title></title>
    <style type="text/css">
        .watermarkOn
        {
            color: #CCCCCC;            
            font:Verdana normal 10px;
        }
    </style>
</head>
Note: When you are work real world web application down write your style sheet within the page. Its increase your page size and Browser does NOT cache your CSS. So better to write as separate CSS file and import in your into your page.

Step 4

Let’s apply the default style effect to textbox. Because when user does not focus the input field, we have to show the watermark, if focused, we have to clear style.
Image Loading
Html Code
<tr>
            <td>
                User Name
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox CssClass="watermarkOn" Text="UserName" ID="txtusername" runat="server"></asp:TextBox>
            </td>
        </tr>
In above snippets, I have applied the default watermarkon style and default text for the user name input field. Apply same to password input field as well.

Step 5

Write few line of JavaScript code to ingrate style and JQuery as like below,
<script language="javascript" type="text/javascript">
  $(document).ready(function() {
      $("#txtusername").focus(function() {
         $(this).filter(function() {return $(this).val() == "" || 
         $(this).val() == "UserName"}).removeClass("watermarkOn").val("");

       });
       $("#txtusername").blur(function() {
          $(this).filter(function() {
           return $(this).val() == ""}).addClass("watermarkOn").val("UserName");
       });
       $("#txtpass").focus(function() {
         $(this).filter(function() {return $(this).val() == "" ||
         $(this).val() == "Password"}).removeClass("watermarkOn").val("");

       });
       $("#txtpass").blur(function() {
         $(this).filter(function() { 
           return $(this).val() == ""}).addClass("watermarkOn").val("Password");
       });
   });
</script>
 In above code line, I just apply style and remove for two events. When user focus input field, remove style class.
.removeClass("watermarkOn").val("");
As like within in the onblur event, add stlye again to inout field.
.addClass("watermarkOn").val("UserName");
Note: When we are adding watermark style, we have to add default text to input filed.
Let’s run application. output will be like follow,

With Master Page

If you are use the master page above code does not work,beuase when we are use the master page ASP.NET add prefix to all server controls ct100_.... so we have to modify the code work to all situation.
<script language="javascript" type="text/javascript">
        $(document).ready(function() {
            $("[id$=txtusername]").focus(function() {
                $(this).filter(function() {
                    return $(this).val() == "" || $(this).val() == "UserName"
                }).removeClass("watermarkOn").val("");

            });
            $("[id$=txtusername]").blur(function() {
                $(this).filter(function() {
                    return $(this).val() == ""
                }).addClass("watermarkOn").val("UserName");
            });
            $("[id$=txtpass]").focus(function() {
                $(this).filter(function() {
                    return $(this).val() == "" || $(this).val() == "Password"
                }).removeClass("watermarkOn").val("");

            });
            $("[id$=txtpass]").blur(function() {
                $(this).filter(function() {
                    return $(this).val() == ""
                }).addClass("watermarkOn").val("Password");
            });
        });
    </script>
If you are going to apply watermark style with master,please use the above code.


You Can dowlload JQUERY library from the below link

1.    http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js
2.    http://code.jquery.com/latest/ jquery.min.js
 

Monday, June 18, 2012

What is JSON?

Introducing JSON

JSON has simple types and two structures which are very similar to the universally used data structures such as dictionary objects, hash values, key/value pairs, lists, sequences, record sets, arrays and so on. The basic data types supported by JSON are as follows:
  • Number - Includes integer, real, and floating point
  • String – Supports Unicode
  • Boolean - true and false
  • Array – It is represented as an ordered sequence of values, with each value being comma-separated and enclosed in square brackets.
  • Object – Represents a collection of key/value pairs that are comma-separated and enclosed in curly brackets
  • null
Let us consider the key characteristics of JSON in the next few sections.

JSON Object

A JSON object is an unordered set of key/value pairs, with keys separated by values using a colon (:). The members inside the object are separated by a comma (,).
var prod = {"ProductID":1, "Name":"Adjustable Race", "ProductNumber":"AR-5381"};
Here is a variable that represents a JSON object with three members. A JSON object is always enclosed between curly brackets and the members inside the object are separated by a comma.
var prod = {"ProductID":1, "Name":"Adjustable Race", "ProductNumber":"AR-5381"};
As you can see, the first member has the name ProductID with the value of 1.
Once you convert the string into a JSON representation, you can access any member value using the dot notation as shown below:
alert(prod.ProductID);

JSON Array

Unlike JSON objects, JSON arrays are enclosed between square braces [ ]. The JSON array is an ordered sequence of values separated by a comma (,). The values can be any of the primitive types as well as the JSON objects. In addition, you can also embed a JSON array inside another JSON array. Consider the following JSON array that has four string variables:
var colorArray =["Red", "Blue", "Yellow", "Magenta"];
You will be able to access the above zero based array item through the array index.
<Script Language="JavaScript">
  var colorArray =["Red", "Blue", "Yellow", "Magenta"];
  for (i=0; i<4; i++){
    document.write( myJsonArray[i]+ "<br>" );
  }
</Script>

Advantage of JSON

Syntax: JSON syntax is quite light and definitely less verbose than XML, with all of its start and end tags. When it comes down to pure byte-size, JSON can represent the same data as XML using fewer characters.

Weight: Since JSON syntax requires fewer characters, it is lighter on the wire than XML. The question is if this really matters. Any large data set is going to be large regardless of the data format you use. Add to that the fact that most servers gzip or otherwise compress content before sending it out, the difference between gzipped JSON and gzipped XML isn’t nearly as drastic as the difference between standard JSON and XML.

Browser Parsing: On the browser, there’s no such thing as a JSON parser. However, there is eval(), which interprets JavaScript code and returns the result. Since JSON syntax is a subset of JavaScript syntax, a JSON string can be evaluated using eval() and quickly turned into an object that is easy to work with and manipulate. XML parsing on the browser is spotty at best. Each browser implements some different way of dealing with XML and none of them are terribly efficient. In the end, the XML ends up as a DOM document that must be navigated to retrieve data. Native JavaScript objects are much easier to work with in JavaScript than DOM documents, although the playing field would level out considerably if every browser supported ECMAScript for XML (E4X), which makes working with XML data as easy as working with JavaScript objects.

Server Parsing: On the server, parsing is just about equal between JSON and XML. Most server-side frameworks have XML parsing capabilities and many now are starting to add JSON parsing capabilities as well. On the server, these parsers are essentially equal, parsing a text format into an object model. JSON holds no advantage over XML in this realm.

Querying: This is where XML really shines. Using XPath, it’s possible to get direct access to a part of multiple parts of an XML data structure; no such interface exists for JSON. To get data from a JSON structure, you must know exactly where it is or else iterate over everything until you find it.
Format Changes: So you have your data in one format but you want it in another. If the data is in XML, you can write an XSLT template and run it over the XML to output the data into another format: HTML, SVG, plain text, comma-delimited, even JSON. XSLT support in browsers is pretty good, even offering JavaScript-level access to it. XSLT support on the server is excellent. When you have data in JSON, it’s pretty much stuck there. There’s no easy way to change it into another data format. Of course it’s possible to walk the structure and do with it as you please, but the built-in support isn’t there as it is with XSLT for XML.

Security: Since the only way to parse JSON into JavaScript objects is to use eval(), it opens up a huge security hole. The eval() function will execute any arbitrary JavaScript code and so is dangerous to use in production systems. Invalid JSON that contains valid JavaScript code could execute and wreak havoc on an application. The solution, of course, is to build a true JSON parser for browsers, but we’re not there yet. On the other hand, XML data is completely safe. There is never a possibility that parsing XML data will result in code being executed.

With all of this considered, the two main advantages that JSON has over XML are 1) the speed and ease with which it’s parsed and 2) the ease of simple data retrieval from JavaScript object. Note that both of these advantages exist on the browser side of things; on the server-side they are essentially equal, unless you take querying and format changes into account, in which case XML is the clear winner. I don’t think that code size really is an advantage when you’re talking about gzipped data. I also believe that if ECMAScript for XML is implemented in all browsers, that JSON’s advantages go away.

Optional Parameters and Named Arguments

Optional Parameters and Named Arguments
When a function has an optional parameter, the caller can decide whether to provide a value or not. (Providing a value for the parameter is optional.) If the caller doesn't provide a value, the function uses a default value.
C++ allows optional parameters. In this example, b is an optional parameter. If the caller doesn't provide a value for b, the function uses the default value, zero.
int DoSomething(int a, int b = 0)
{
        return a + b;
}

This can be called as follows:

// Returns 5 + 7 = 12;
int x = DoSomething(5, 7);
 
// Returns 5 + 0 = 5
int y = DoSomething(5);
VB.Net has allowed optional parameters since version 1.0. C#, however, did not support optional parameters until .NET 4.0.

Method overloading
Prior to .NET 4.0, the closest you could come to optional parameters was method overloading. Here, for example, the method DoSomething has an optional parameter with a default value of 0.
public int DoSomething(int a, int b)
{
return a + b;
}
public int DoSomething(int a)
{
Return DoSomething(a, 0);
}
Method overloading has its problems. For one thing, every optional parameter can double the number of overloads. DoSomething( ) has one optional parameter and two overloads. If we have two optional parameters, there are four overloads:
public void DoSomethingElse(string s, decimal d)
{
        Console.WriteLine( "{0}, {1}" , s, d);
}
public void DoSomethingElse(string s)
{
        DoSomething(s, 5);
}
public void DoSomethingElse(decimal d)
{       
DoSomething("Hello", d);
}
 
public void DoSomethingElse( )
{
        DoSomething("Hello", 5);
}
This can get out of hand quickly. It's also error prone.
Optional Parameters
Optional parameters make life easier. Here is one function to replace the four overloaded methods shown above:
public void DoSomethingElse(string s = "Hello", decimal d = 5)
{
        Console.WriteLine("{0}, {1}", s, d);
}
There are a few restrictions.
  1. All optional parameters must come after the required parameters. So this is invalid:// Invalid:  optional parameter before required parameter
    public void DoSomething(string s = "Hello", decimal d)
    {       ... }
  2. The default value for an optional parameter must be a constant. It can be a string or a number, const, null, or an enum.
    // Invalid:  optional parameter is not a constant.
    public void DoSomething(DateTime dt = DateTime.Now)
    {
          ...
    }
    One possible way to overcome this restriction is as follows:
    // Setting a default value of DateTime.Now
    public void DoSomething(Nullable<DateTime> dt = null)
    {
            if (!dt.HasValue)
                   dt = DateTime.Now;
    }
Optional Parameters With Named Arguments
One case where optional parameters run into trouble is when there is more than one optional parameter with the same data type. For example:
public void DoSomething(int a = 5, int b = 10)
{
...
}
In this case, it's not clear what a call to DoSomething(37) means. Are you passing in a or b? This is where named arguments come in handy. Named parameters (also new to .NET 4.0) allow you to specify which parameter you intended.
// a = 37.  b = the default value.
DoSomething(a: 37);
 
// a = the default value.  b = 37.
DoSomething(y: 37);
Beware
Using optional parameters in class libraries can cause unexpected problems. Suppose I have a class library that contains the following method:
public int DoSomething( int x = 30)
{
        return x;
}

I wrote a program that uses the class library and calls DoSomething( ). DoSomething returns the default value, 30.

Now suppose I modify the class library and change the default value:
public int DoSomething( int x = 40 )
{
        return x;
}
I recompile the class library and then run my program again. I call DoSomething( ) and it still returns 30.
The only way I can get the correct result is if I recompile my program as well.

Windows Service


What is a Windows Service?
Windows Service applications are long-running applications that are ideal for use in server environments. The applications do not have a user interface or produce any visual output. Any user messages are typically written to the Windows Event Log. Services can be automatically started when the computer is booted. They do not require a logged in user in order to execute and can run under the context of any user including the system. Windows Services are controlled through the Service Control Manager where they can be stopped, paused, and started as needed.
Windows Services, formerly NT Services, were introduced as a part of the Windows NT operating system. They are not available on Windows 9x and Windows Me. You need to use one of the operating systems in the NT generation such as Windows NT, Windows 2000 Professional, or Windows 2000 Server to run a Windows Service. Examples of Windows Services are server products such as Microsoft Exchange, SQL Server, and other applications such as Windows Time that sets the computer clock.
Create a Windows Service
The service we will create does nothing really useful other than serve as a demonstration. When the service is started we will log an entry in a database indicating that it has started. The service will create a database entry on a specified interval during the time in which it is running. The service will create a final database entry when stopping. The service will also automatically log an entry in the Windows Application Log when it is successfully started or stopped.
Visual Studio .NET makes it relatively simple to create a Windows Service. The instructions for starting our demo service are outlined below.
  1. Start a new project
  2. Select Windows Service from the list of available project templates
  3. The designer will open in design mode
  4. Drag a Timer object from the Components tab in the Toolbox onto the design surface (Warning: make sure you use the Timer from the Components tab and not the one from the Windows Forms tab)
  5. Through the Timer properties set the Enabled property to False and the Interval property to 30000 milliseconds
  6. Switch to the code behind view (F7) to add functionality to the service
Makeup of a Windows Service
In the code behind class you will notice that your Windows Service extends the System.ServiceProcess.Service class. All Windows Services built in .NET must extend this class. It requires your service to override the following methods which Visual Studio will include by default.
  • Dispose - clean up any managed and unmanaged resources
  • OnStart - control the service startup
  • OnStop - control the service stoppage

Sample Windows Service
Below is all of the source code for a Windows Service called MyService. The majority of this source code was generated automatically by Visual Studio.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace TestWS
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        #region Event
            protected override void OnStart(string[] args)
            {
                try
                {
                 
                    System.Timers.Timer timer1 = new System.Timers.Timer();
                    timer1.Enabled = true;
                    timer1.Interval = 5000;
                    timer1.Start();
                    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
                    writeLog("EmailService Start..");
                   
                }
                catch
                {
                    writeLog("Exception occur in starting");
                }
            }
            private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                writeLog("Timer Elapse..");
                fetchData();
            }
            protected override void OnStop()
            {
                writeLog("EmailService Stop..");
            }
        #endregion

        #region Methods
            protected void fetchData()
            {
                SqlConnection connection = null;
                SqlCommand command = null;
                try
                {
                    connection = new SqlConnection("Server=localhost;Database=SampleDatabase;Integrated Security=false;User Id=sa;Password=;");
                    command = new SqlCommand("SELECT COUNT(1) FROM SampleDatabase.dbo.TestTable", connection);
                    connection.Open();
                    int numrows = Convert.ToInt32(command.ExecuteScalar());
writeLog(numrows.ToString() + "rows exist in TestTable");
                }
                catch( Exception ex )
                {
                    writeLog(ex.Message);
                }
                finally
                {
                    command.Dispose();
                    connection.Dispose();
                }
            }
            public void writeLog(string str)
            {
                System.IO.StreamWriter streamWriter = File.AppendText(Application.ExecutablePath + DateTime.Now.ToString("ddMMyyyy").ToString() + "log.txt");
                streamWriter.WriteLine(DateTime.Now + ": " + str);
                streamWriter.Close();
                streamWriter.Dispose();
            }
        #endregion

    }
}
Install the Windows Service
Windows Services are different than normal Windows based applications. It is not possible to run a Windows Service by simply running an EXE. The Windows Service should be installed by using the InstallUtil.exe provided with the .NET Framework or through a deployment project such as a Microsoft Installer (MSI) file.
Add an Installer
Having created the Windows Service will not be enough for the InstallUtil program to be able to install the service. You must also add an Installer to your Windows Service so that the InstallUtil, or any other installation program, knows what configuration settings to apply to your service.
  1. Switch to the design view for the service
  2. Right click and select Add Installer
  3. Switch to the design view of the ProjectInstaller that is added
  4. Set the properties of the serviceInstaller1 component
    1. ServiceName = My Sample Service
    2. StartType = Automatic
  5. Set the properties of the serviceProcessInstaller1 component
    1. Account = LocalSystem
  6. Build the Solution
The following code contained in the ProjectInstaller.cs source file was automatically generated by Visual Studio after having completed the steps above.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;


namespace TestWS
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
    }
}
Use InstallUtil to Install the Windows Service
Now that the service has been built you need to install it for use. The following instructions will guide you in installing your new service.
  1. Open a Visual Studio .NET Command Prompt
  2. Locate exe file in bin directory.
  3. Issue the command InstallUtil.exe TestWs.exe to register the service and have it create the appropriate registry entries.
InstallUtil /  i [Path of the exe]
  1. In the Services section underneath Services and Applications you should now see your Windows Service included in the list of services.
Click Run and type “services.msc” then enter
  1. Start your service by right clicking on it and selecting Start
Each time you need to change your Windows Service it will require you to uninstall and reinstall the service. Prior to uninstalling the service it is a good idea to make sure you have the Services management console closed. If you do not you may have difficulty uninstalling and reinstalling the Windows Service. To uninstall the service simply reissue the same InstallUtil command used to register the service and add the /u command switch.
InstallUtil /  u  [Path of the exe]

Debug the Windows Service
As with all other aspects, debugging a Windows Service is different than a normal application. More steps are required to debug a Windows Service. The service cannot be debugged by simply executing it in the development environment as you can with a normal application. The service must first be installed and started, which we covered in the previous section. Once it is started you attach Visual Studio to the running process in order to step through and debug the code. Remember, each change you make to the Windows Service will require you to uninstall and reinstall the service.
Attach to a Running Windows Service
Here are the directions for attaching to a Windows Service in order to debug the application. These instructions assume that you have already installed the Windows Service and it is currently running.
  1. Load the project into Visual Studio
  2. Click on the Debug menu
  3. Click on the Processes menu item
  4. Make sure the Show system processes is selected
  5. Locate your process in the Available Processes list based on the name of your executable and click on it
  6. Click the Attach button
  7. Click OK
  8. Click Close
  9. Set a break point in the timer1_Elapsed method and wait for it to execute
Summary
You should now have a rough idea of what windows services are, how to create, install, and debug them. There is additional functionality with Windows Services that you can explore. This functionality includes the capability to pause (OnPause) and resume (OnContinue). The ability to pause and resume are not enabled by default and are setup through the Windows Service properties.