Copy table

select * into employee1  from employee where id=5

select * into employee1  from employee

//CREATE NEW TABLE AND COPY ALL THE TABLE CONTENT

select * from employee1

drop table employee1

SELECT *
INTO employee1
FROM employee
WHERE 1=2

//ONLY COPY STRUCTURE

INSERT INTO employee1 (empname, address)
SELECT empname, address
FROM employee
WHERE id = 2


select * into <destination table> from <source table>


Example:

Select * into employee_backup from employee

 We can also select only a few columns into the destination table like below

select col1, col2, col3 into <destination table>

from <source table>




Example:


Select empId, empFirstName, empLastName, emgAge into employee_backup

from employee

Use this to copy only the structure of the source table.
select * into <destination table> from <source table> where 1 = 2



Example:

select * into employee_backup from employee where 1=2

Use this to copy a table across two database in the same Sql Server.
select * into <destination database.dbo.destination table>

from <source database.dbo.source table>


Example:

select * into Mydatabase2.dbo.employee_backup

from mydatabase1.dbo.employee














Iterate through the table and calculate the total price through storeprocedure

create proc test
as
Select price_id Into  #Temp From   agreement_price
Declare @Id int
declare @val int
Declare @calc int
declare @it int

set @val=0
set @it=(Select Count(*) From #Temp)
While (@it) > 0
Begin
  set @calc=(select price from price where price_id in (Select Top 1 price_id From  #Temp))
  set @val=@val+@calc
set @id=(Select Top 1 price_id From  #Temp)
 Delete from #Temp Where price_id= @Id
set @it=@it-1
End
select @val
exec test

WCF

http://www.codeproject.com/KB/WCF/WCF_Example.aspx


Abstract

In this article, I am going to show you a small Addition programme using WCF. After going through this snippet, the reader will get a clear and basic understanding of the WCF programme.

Introduction

WCF (Windows Communication Framework) is a unification technology, which unites the following technologies:
  • NET remoting
  • MSMQ
  • Web services
  • COM+
It is based on SOA (Service Oriented Architecture).

What are Ends, Contract, Address, and Bindings?

The above terminologies are the core on which SOA stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things: where, what and how:

Contract (What)

Contract is an agreement between two or more parties. It defines the protocol how the client should communicate with your service. Technically, it describes parameters and return values for a method.

Address (Where)

An address indicates where we can find this service. Address is a URL, which points to the location of the service.

Binding (How)

Bindings determine how this end can be accessed. It determines how communications are done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communications medium two bindings will be created.

The Important Principles of SOA?

WCF is based on SOA. SOA is based on four important concepts:

Boundaries are Well Defined

In SOA, everything is formalized. The client who is consuming the service does not need to know how the implementation of the service is done. If you look at some old methodologies of communication like DCOM, any changes at server level the client also has to change. Therefore, the server and client implementation was so much bound that changes need to be done at all places. In SOA, the rule is if you do enhancement you do not need to change anything at the client. SOA based application only understands that there is an end point, contract, and bindings.
Note: Just to clarify shortly about end point and contract, any SOA service is exposed through an end point. End point defines three important aspects What, Where and How.

Services Evolve

Change is the law of nature and services will evolve. In SOA, services can be versioned and you can host those services in new ends. For instance, you have a service called as “Search Tickets (Ticket Number)“ which gives details based on Ticket Number and it's exposed on end point “ep1”. Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end “ep2” with service “Search Tickets (Ticket Number, Passenger Name)”. So the client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.

Services Share Only Schemas and Contracts

Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is no heavy coupling between environments.

Service Compatibility is Policy Based

Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance, your service needs to be hosted for two types of clients, one which uses Remoting as the communication methodology while the other client uses DCOM. An ideal SOA service can cater to both of them according to their communication policies.

Code Snippet

(Service/Server Side)
Steps Involved:
Step 1: Open VS2008 , File->New -> Website->WCF Service->Browse->Click or select default Website ->Right to corner Create New Web Application->Rename to" MyService" ->Open->OK 
Step 2: You will see the solution window, in that open "service.cs".



Step 3: Open "service.svc.cs" and write code here as I have written code for my "addfunction". You can write your code inside your function. The picture is shown below:


Step 4: This is the most important step. In this, we are declaring the end point. Inside this, we can define an end point as shown in the picture. End point is defined automatically. We can also define it by program.

Step 5: Save the project and run it. This will display like this. Copy the address from explorer address bar.

Code Snippet

(Client Side)
Let the server service run (the above page).
Step 1: Open VS2008 , File->New -> Website->Asp .NET Website->Browse->Click or select default Website ->Right to corner Create New Web Application->Rename to" WCF Client" ->Open->OK   Right click on solution name and then go to "Add Service Reference" one window will open paste the previously copied link to the address bar and press GO. Then the service will appear in service section, then press OK. The service reference will appear in solution explorer as below:

Step 2: Now add one button on the default page, then double click on button you'll be in code behind section. Here create the object of the service which appeared in the solution explorer. Something like this:
protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.ServiceClient cls = 
 new ServiceReference1.ServiceClient();
cls.Open();
Response.Write( cls.GetData(5));
cls.Close();
}
Step 3: Now save the project and run it. If everything goes fine, then the output will be like this:

Hope this article may helped you to understand and build a simple addition program in WCF.
Thanks.

Web service in asp.net

http://msdn.microsoft.com/en-us/library/8wbhsy70.aspx#Y1444

To create a Web service


  1. Open Visual Web Developer.
  2. On the File menu, click New Web Site.
    The New Web Site dialog box appears.
  3. Under Visual Studio installed templates, click ASP.NET Web Service.
  4. Click Browse.
  5. Click Local IIS.
  6. Click Default Web Site.
  7. Click Create New Web Application.
    Visual Web Developer creates a new IIS Web application.
  8. Type the name TemperatureWebService.
  9. Click Open.
    The New Web Site dialog box appears, with the name of the new Web site in the rightmost Location list. The location includes the protocol (http://) and location (localhost). This indicates that you are working with a local IIS Web site.
  10. In the Language list, click the programming language that you prefer to work in.
    The programming language that you choose will be the default for the Web site. However, you can use more than one language in the same Web application by creating pages and components in different programming languages. For more information about how to create components using different languages, see Shared Code Folders in ASP.NET Web Projects.
  11. Click OK.
    Visual Web Developer creates the new Web service and opens a new class named Service, which is the default Web service. However, in the following procedure you will create a new Web service with a specified name and you will not use the Service class.
  12. Close the Service class.

    Creating Webservices

    You will create a Web service that converts temperature from Fahrenheit to Celsius and vice versa.

    To create the Web service

    1. In Solution Explorer, right-click the Web site name (http://localhost/TemperatureWebService), and then click Add New Item.
    2. Under Visual Studio installed templates, click Web Service, and then in the Name box, type Convert.
    3. Make sure that the Place code in separate file check box is selected, and then click Add.
      Visual Web Developer creates a new Web service that is made up of two files. The Convert.asmx file is the file that can be invoked to call Web service methods, and it points to the code for the Web service. The code itself is in a class file (Convert.vb, Convert.cs, or Convert.jsl, depending on the programming language) in the App_Code folder. The code file contains a template for a Web service. The code file includes some code for a Web service method.
    You will create two methods in the Web service. The first method converts Fahrenheit temperatures to Celsius, and the second method converts Celsius temperatures to Fahrenheit.

    To create the conversion methods

    Add the following code inside the class, after the HelloWorld method:
[System.Web.Services.WebMethod()]
public double FahrenheitToCelsius(double Fahrenheit)
{
    return ((Fahrenheit - 32) * 5) / 9;
}

[System.Web.Services.WebMethod()]
public double CelsiusToFahrenheit(double Celsius)
{
    return ((Celsius * 9) / 5) + 32;
}
  1. Notice that the function names are preceded with an attribute ([System.Web.Services.WebMethod()] or <System.Web.Services.WebMethod()>) as part of the function declaration.
  2. After you have entered the functions, save the file.
Now, you can test the Web service in Visual Web Developer.

To test the Web service

  1. In Solution Explorer, click Convert.asmx, and then press CTRL+F5.
    The Web service is invoked and a page appears in the browser that shows the methods that are exposed by the Web service.
  2. Click CelsiusToFahrenheit, which invokes that method.
    A page appears that prompts you for parameter values for the CelsiusToFahrenheit method.
  3. In the Celsius box, type 100, and then click Invoke.
    A new window appears that displays the XML that the Web service returns when the CelsiusToFahrenheit method is invoked. The value 212 appears in the XML.
  4. Close the browser that contains the method results.
  5. In the original browser, click Back to return to the list of methods.
  6. Click FahrenheitToCelsius and test to make sure that the method is returning the results that you expect.
    If you type 212, the FahrenheitToCelsius method will return 100.
  7. Close the browser.
You have finished creating the Web service; the next step is to use it.

Using the webservices


Now that you have a Web service, you will create a Web site where you will reference and use the Web service that you created. For the walkthrough, you will create a separate Web site that has a page where you start the Web service methods that you just created.

To create a Web site to use the Web service

  1. On the File menu, click New Web Site.
  2. Under Visual Studio installed templates, click ASP.NET Web Site.
  3. Click Browse.
  4. Click Local IIS.
  5. Click Default Web Site.
  6. Click Create New Web Application.
    Visual Web Developer creates a new IIS Web application.
  7. Type the name TemperatureWeb.
  8. Click Open.
  9. In the Language list, click the programming language that you prefer to work in.
  10. Click OK.
    Visual Web Developer creates a new local IIS Web site and a new page named Default.aspx.
  Adding the Web Service as a Component

To create a reference to the Web service

  1. On the Web Site menu, click Add Web Reference.
    The Add Web Reference dialog box appears, as shown in the following screen shot.
    Add Web Reference dialog box

    Add Web Reference dialog box
  2. In the URL list, enter the following URL for the Web service, and then click Go:
    http://localhost/TemperatureWebService/Convert.asmx
    When Visual Web Developer finds the Web service, information about the Web service appears in the Add Web References dialog box.

    Note
     
    If you cannot add a reference to a Web service, it might be that the proxy server is not configured correctly. In Microsoft Internet Explorer, on the Tools menu, click Internet Options, click Connections, and then click LAN Settings. Select the Bypass proxy server for local addresses check box. Additionally, set the proxy server address to the exact name of the proxy server instead of allowing Internet Explorer to detect the proxy server. For more information, contact the network administrator.

  3. Click one of the method links.
    The test page for the method appears.
  4. Click Add Reference.
    Visual Web Developer creates an App_WebReferences folder and adds a folder to it for the new Web reference. By default, Web references are assigned a namespace corresponding to their server name (in this case, localhost). Make a note of the name for the Web reference namespace. In the folder, Visual Web Developer adds a .wsdl file that references the Web service. It also adds supporting files, such as discovery (.disco and .discomap) files, that include information about where the Web service is located.
Note Note
 
If the server name for the Web service contains characters that cannot be used for a class name, such as a hyphen (-), Visual Web Developer converts those characters to an underscore character (_). Therefore, the namespace in Visual Web Developer for the Web service might not match the server name exactly.
You can now use the Web service. In this walkthrough, you will add controls to Default.aspx, and then program the controls to convert a specified temperature to both Fahrenheit and Celsius. When the page is running, it will look something like the following illustration.


Temperature conversion page

VenusWebServicesWalkthroughConsumePage screenshot

To call the Web service methods

  1. Open the Default.aspx page and switch to Design view.
  2. From the Standard group in the Toolbox, drag the following controls onto the page and set their properties as indicated:
    Control
    Properties
    Textbox
    ID: TemperatureTextbox
    Text: (empty)
    Button
    ID: ConvertButton
    Text: Convert
    Label
    ID: FahrenheitLabel
    Text: (empty)
    Label
    ID: CelsiusLabel
    Text: (empty)
  3. Optionally, add text to the page for captions.
    For this walkthrough, the layout of the page is not important.
  4. Double-click ConvertButton to create an event handler for its Click event.
  5. Make sure your event handler code matches the code in the following example.
    protected void ConvertButton_Click(object sender, EventArgs e) { localhost.Convert wsConvert = new localhost.Convert(); double temperature = System.Convert.ToDouble(TemperatureTextbox.Text); FahrenheitLabel.Text = "Fahrenheit To Celsius = " + wsConvert.FahrenheitToCelsius(temperature).ToString(); CelsiusLabel.Text = "Celsius To Fahrenheit = " + wsConvert.CelsiusToFahrenheit(temperature).ToString(); }
  6. Press CTRL+F5 to run the page.
  7. In the text box, type a value, such as 100, and then click Convert.
    The page displays the result of converting the temperature value into both Fahrenheit and Celsius.
You can debug a Web service in the same way that you debug Web pages.

Note Note
 
Visual Web Developer Express and Visual Studio Standard do not support stepping into a Web service from a page that references it. If you are using Visual Web Developer Express or Visual Studio Standard, skip this section and the ones following. For more information about how to debug Web sites, see Walkthrough: Debugging Web Pages in Visual Web Developer.
To start, you must configure the Web site that contains the Web service to enable debugging.

To enable debugging in the Web services Web site

  1. On the File menu, click Open Web Site.
  2. Click Local IIS.
  3. Click TemperatureWebService, and then click Open.
  4. On the Website menu, click ASP.NET Configuration to open the Web Site Administration Tool.

    Note Note
     
    If this is the first time that you have run the Web Site Administration Tool, there might be some delay before it appears.
  5. Click Application, and then click Application Configuration.
  6. Under Debugging and Tracing, click Configure debugging and tracing.
  7. Select the Enable debugging check box.
    The Web Site Administration Tool creates a Web.config file for the Web site and sets a configuration option to enable debugging.

    Note Note
     
    To see the Web.config file in Solution Explorer, click the Web site name and then, on the Solution Explorer toolbar, click Refresh.
  8. Close the Web Site Administration Tool.
You must now enable debugging for the Web site that uses the Web service.

To enable debugging in the Web site

  1. Open the TemperatureWeb site.
  2. On the Website menu, click ASP.NET Configuration to open the Web Site Administration Tool.
  3. Click Application, click Application Configuration, under Debugging and Tracing, click Configure debugging and tracing, and then select the Enable debugging check box.
  4. Close the Web Site Administration Tool.

    Note Note
     
    To see the Web.config file in Solution Explorer, select the Web site name and then, on the Solution Explorer toolbar, click Refresh.
  5. In Solution Explorer, right-click Default.aspx, and then click View Code.
    Visual Web Developer opens the code file for the page.
  6. Position the pointer in the following line:
    double temperature =
        System.Convert.ToDouble(TemperatureTextbox.Text);
    
    
    
  7. Press F9 to set a breakpoint on the line.


Both the Web site and the Web service are configured for debugging, so that you can now try debugging. You will start in the Default.aspx page and step through the code until the code invokes the Web service. The debugger will switch to the Web service and continue stepping through the code.

To debug the page and Web service

  1. Press F5 to run the Default.aspx page with debugging.
    The page appears in the browser.
  2. In the box, type a value, such as 100, and then click Convert.
    Visual Web Developer starts running the code for the page, but stops and highlights the line with the breakpoint on it.
  3. Press F11 to step to the next line.
  4. Press F11 again.
    Because the next line invokes the Web service, the debugger steps into the Web service, stopping on the first line of the FahrenheitToCelsius method.
  5. Continue pressing F11.
    The debugger steps through the rest of the method, and then returns to the calling page. If you continue stepping, the debugger will step back into the Web service and into the CelsiusToFahrenheit method.
  6. Close the browser, which also closes the debugger.

Xml operation

****************Creating new xml file************************

XmlTextWriter newXmlFile = new   XmlTextWriter(Give path and name of xml file to create,System.Text.Encoding.Default);

newXmlFile.WriteStartDocument();

//creating the name of the main node
newXmlFile.WriteStartElement("Start","");

//creating child nodes
newXmlFile.WriteElementString("First");
newXmlFile.WriteFullEndElement();
       newXmlFile.WriteEndElement();
newXmlFile.Flush();
newXmlFile.Close();

************************Insert data to xml file************************

// Create xml dom
XmlDocument XMLDom = new XmlDocument();

//load your xml file
XMLDom.Load(@"path of your xml file");

//Select main node
XmlNode newXMLNode = XMLDom.SelectSingleNode("/Main node name");

//get the node where you want to insert the data
XmlNode childNode = XMLDom.CreateNode(XmlNodeType.Element,"your node name where you want to insert data","");

//In the below step "name" is your node name and "sree" is your data to insert
XmlAttribute newAttribute = XMLDom.CreateAttribute("name","sree","");
childNode.Attributes.Append(newAttribute);
newXMLNode.AppendChild(childNode);

************************Modify data in xml file************************
// Select childnode where you want to modify data. The following step "PNode" is parent node and "Node1" is the one which you want to update the data

XmlNodeList newXMLNodes = XMLDom.SelectNodes("/PNode/Node1");
foreach(XmlNode newXMLNode in newXMLNodes)

//Updating data where "Node1" is "sree" with "kambham"
if(newXMLNode.InnerText == "sree")
newXMLNode.InnerText = "kambham";
XMLDom.Save("Path of your XML file");
XMLDom = null;
//The above step updates xml file where ever it finds "sree" with "kambham"

************************Delete data in xml file************************

XmlNodeList newXMLNodes = XMLDom.SelectNodes("/PNode/Node1");
foreach(XmlNode newXMLNode in newXMLNodes)
if(newXMLNode.InnerText == "sree")
newXMLNode.ParentNode.RemoveChild(newXMLNode);
XMLDom.Save("Path of your XML file");
XMLDom = null;
//The above step deletes data in xml file where ever it finds "sree"

XML

Here is an XML file named "countries.xml":

<?xml version="1.0" encoding="ISO-8859-1"?>

<countries>

<country>
  <text>Norway</text>
  <value>N</value>
</country>

<country>
  <text>Sweden</text>
  <value>S</value>
</country>

<country>
  <text>France</text>
  <value>F</value>
</country>

<country>
  <text>Italy</text>
  <value>I</value>
</country>

</countries>

<%@ Import Namespace="System.Data" %>

Next, create a DataSet for the XML file and load the XML file into the DataSet when the page is first loaded:
<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
end if
end sub
To bind the DataSet to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:
<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server" AutoPostBack="True" />
</form>

</body>
</html>
Then add the script that builds the XML DataSet:
<%@ Import Namespace="System.Data" %>

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
  rb.DataSource=mycountries
  rb.DataValueField="value"
  rb.DataTextField="text"
  rb.DataBind()
end if
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
</form>

</body>
</html>
Then we add a sub routine to be executed when the user clicks on an item in the RadioButtonList control. When a radio button is clicked, a text will appear in a label:

Example

<%@ Import Namespace="System.Data" %>

<script runat="server">
sub Page_Load
if Not Page.IsPostBack then
  dim mycountries=New DataSet
  mycountries.ReadXml(MapPath("countries.xml"))
  rb.DataSource=mycountries
  rb.DataValueField="value"
  rb.DataTextField="text"
  rb.DataBind()
end if
end sub

sub displayMessage(s as Object,e As EventArgs)
lbl1.text="Your favorite country is: " & rb.SelectedItem.Text
end sub
</script>

<html>
<body>

<form runat="server">
<asp:RadioButtonList id="rb" runat="server"
AutoPostBack="True" onSelectedIndexChanged="displayMessage" />
<p><asp:label id="lbl1" runat="server" /></p>
</form>

</body>
</html>

Event handling

Event Handling in C#



No GUI application is complete without enabling actions. Even though arranging components is a significant issue, applying actions is also equally important. These actions are what instructs the program to act when something happens.  For example, Mouse clicks, Keyboard presses, etc. Before beginning our discussion let's review how different API’s handle events.

Microsoft Foundation Classes (MFC): These classes are based upon Microsoft's Win32 API. Normally development work is done through Visual C++.  

Java API: Here, the majority of work is done by employing AWT and Swing packages. Actions are enabled by applying Interfaces. The main difficulty is that you should learn and remember all methods in the corresponding interfaces.  Otherwise, you receive compile time errors.

As compared to the above, Event handling in C# is much more simplified. It's possible to handle various Mouse and Key related events quickly and in a more efficient manner. Learning will be easier, if you understand the basic principles behind handling events, which are elaborated below 

  1. Invoke the related event by supplying a custom method or event handler using the += operator as shown here:  


b1.Click += new EventHandler(OnClick);


  1. Apply the event handler as described below. It must be in conformance with a delegate of the class System.EventHandler:

          
public delegate void EventHandler(object sender, Event args)


The first argument indicates the object sending the event and the second argument contains information for the current event. You can use this argument object to handle functions associated with the related event. Listing - 1 below illustrates how to print ”Hello C#” inside a Textbox when a Button is clicked:

Listing – 1


using System;
using System.Windows.forms;
using System.Drawing;

public class Butevent:form  {

        TextBox t1 = new TextBox();
        Button b1 = new Button();

        public Butevent() {

            this.Text = "Program developed by Pradeepta M";

            t1.Location = new Point(20,30);

            b1.Text = "Click here to activate";
            b1.Location = new Point(20,55);
            b1.Size = new Size(150,20);

           
// Invoking Method or EventHandler
           b1.Click+=new EventHandler(OnClick);

           this.Controls.Add(t1);
           this.Controls.Add(b1);

           
// Invoking Method or EventHandler
           this.Resize += new EventHandler(OnResize);
    }

  
  //Applying EventHandler
    public void OnResize(object sender,EventArgs ee) {

        MessageBox.Show("oops! form Resized");

    }


     //Applying EventHandler
    public void OnClick(object sender,EventArgs e)   {

        t1.Text = "Hello C#";

    }

    public static void Main() {

        Application.Run(new Butevent());

    }
}

The above example also shows how to handle a Resize event. try resizing the forms border and observe the result.

Handling MouseEvents


You can handle various Mouse actions by using the events specified in the Control class. The following listing shows how to handle a simple MouseUp Event:

Listing – 2


using System;
using System.Windows.forms;
using System.Drawing;

public class Mousedemo:form  {

    public Mousedemo()  {

        this.MouseUp += new MouseEventHandler(OnMouseup);

    }

    public void OnMouseup(object sender,MouseEventArgs e)   {

        this.Text = "Current Position (" +e.X + " , " + e.Y +")";

    }

    public static void Main()  {

         Application.Run(new Mousedemo());

    }
}

try out the above example and observe the result.  Click, DoubleClick, MouseEnter, and  MouseLeave events can be handled in a similar way.

Using KeyBoard Events


Every modern programming language contains all necessary functions for handling KeyBoard related events. C# also provides us with three events Keypress, KeyUp and KeyDown, which you can use to handle Keyboard events. Listing – 3, below, shows the usage of the KeyUp Event. Copy the code given below, compile, and observe the output.

Listing – 3


using System;
using System.Windows.forms;
using System.Drawing;

public class Keydemo:form {

    public Keydemo() {

        this.KeyUp += new KeyEventHandler(OnKeypress);
    }

    public void OnKeypress(object sender, KeyEventArgs e)    {

        MessageBox.Show(e.KeyCode.ToString(), "Your input");

    }

    public static void Main()    {

        Application.Run(new Keydemo());
    }
}

I hope you now have significant exposure to Event Handling techniques using the C# language. You can explore more events by going through online help. 



Adding and deleting the option values of a select element of html from javascript.

<html>
<body>
<script language="javascript">
                   
                    function setQuantity()
{


var i=0;
 var myselect=document.getElementById("mySelect");
 //alert(document.getElementById("mySelect").value);
 var len=myselect.length;



for(i=myselect.length-1; i>=0; i--)
    {

  
        myselect.options[i] = null;
    
    }




if(document.getElementById("selHomepageTile").value=="Large")
{
    var newOpt1 = new Option(1, 1);
    myselect.options[0] = newOpt1;
}

if(document.getElementById("selHomepageTile").value=="Medium")
{
for(i=3;i>=1;i--)
{


var newOpt1 = new Option(i, i);
    myselect.options[i-1] = newOpt1;
   

}
myselect.selectedIndex = 0;

}
if(document.getElementById("selHomepageTile").value=="Small")
{
for(i=12;i>=1;i--)
{
    var newOpt1 = new Option(i, i);
    myselect.options[i-1] = newOpt1;
   
    }
     myselect.selectedIndex = 0;
}
   
 }
                   
                    </script>             

<select name="selHomepageTile" id="selHomepageTile" disabled="true"  onChange="setQuantity();">
                        <option value="Large">Large (1) $200</option>
                        <option value="Medium">Medium (3) $120/each</option>
                        <option value="Small">Small (12) $80/each</option>

</select>
<select name="mySelect" id="mySelect" disabled="disabled">

           <option value="1">1</option>
</select>
</body>
</html>

Finding records in one table not present in another table

Difference between NOT IN, LEFT JOIN and NOT EXISTS.
The objective is to fetch all records in one table that are not present in another table. The most common code I’ve seen at client sites includes the use of NOT IN, because this keyword is included in most programming languages and programmers tend to use this technique when writing stored procedures in the database too. The code example I have found in most cases is this simple and understandable
SELECT     a.iFROM       #a AS aWHERE      a.i NOT IN (SELECT b.j FROM #b AS b)           
OR a.i IS NULL
The basic idea is to get all records from table #a where the value in column i is either NULL or not present in column j of table #b. What basically happens behind the scene is that the NOT IN part creates a list of values and stores them in a temporary table and then matches the values from column i in table #a against this temporary table. If there is not a match, or value from table #a is NULL, the column value is valid and returned to query.
There are at least three other ways to do this, which all are much more efficient!
SELECT     a.iFROM       #a AS aWHERE      a.i NOT IN (SELECT b.j FROM #b AS b)
UNION ALL
SELECT     a.iFROM       #a AS aWHERE      a.i IS NULL

SELECT     a.iFROM       #a AS aLEFT JOIN  #b AS b ON b.j = a.iWHERE      b.j IS NULL

SELECT     a.iFROM       #a AS aWHERE      NOT EXISTS (SELECT * FROM #b AS b
 WHERE b.j = a.i)
Running these four queries simultaneously gives exactly the same result.
Original query takes 95% of the batch, second query (first alternative with UNION ALL) takes 2%, and the last two takes only 1% each!
This is the average profiler results for the four queries after 100 executions each 
CPU
Reads
Writes
Duration
Rows
Query 1
1 767
26 292
0
1 772
2 193
Query 2
6
57
0
6
2 193
Query 3
6
24
0
6
2 193
Query 4
3
24
0
3
2 193

   
As you can see, all three alternative approaches are superior to the NOT IN approach!
Next question is obviously “Which approach to use”?
  • Second query can be the best choice if there are few records because there are now 5 table scans compared to two table scans in the original query.
  • Third query is fast, but can be slow if table #b has many more records than table #a.
  • Fourth query will always perform fast because the EXISTS parts ends directly when first matching record is found. But if the second table #b is a mix of more JOINS this will not perform that fast.
It seems that LEFT JOIN and NOT EXISTS are both superior to NOT IN.
Which one of the two approaches you choose, must be decided carefully for every query needing this technique.
Also remember that if table #b were not a temporary table, SQL Server would have places a lot of locks on that table.
http://www.hosinc.com/products/interfaces/interface_documentation.htm
http://www.7edit.com/manual/tutorials/hl7-format-intro/
http://www.otechimg.com/pdf/hl7messaging_ch1.pdf
http://www.doh.state.fl.us/irm/apps/ihis/JADS/elr/JAD%20Documentation/02-18-00/hl7format.pdf

Threading

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. 


Multithreaded applications provide the illusion that numerous activities are happening at more or less the same time. But the reality is the CPU uses something known as “Time Slice” to switch between different threads.
The principal advantage of multithreading is that it enables you to write very efficient programs because it lets you utilize the idle time that is present in most programs. But using too many threads in our programs can actually “degrade” performance, as the CPU must switch between the active threads in the process which takes time. When a thread’s time slice is up, the existing thread is suspended to allow other thread to perform its business. For a thread to remember what was happening before it was kicked out of the way, it writes information to its local storage and it is also provided with a separate call stack, which again put extra load on the CPU.


Multithreading Fundamentals

There are two distinct types of multitasking: process-based and thread-based.
The differences between process-based and thread-based multitasking can be summarized like this:
Process-based multitasking handles the concurrent execution of programs, while Thread-based multitasking deals with the concurrent execution of pieces of the same program.
Process-based: Example — running word processor at the same time you are browsing the net.
Thread-based: Example — A text editor can be formatting text at the same time that it is printing.


The .NET Framework defines two types of threads: foreground and background.
By default when you create a thread, it is a foreground thread, but you can change it to a background thread. The only difference between a foreground and background thread is that a background thread will be automatically terminated when all foreground threads in its process have stopped.


The “Foregroundthreads have the ability to prevent the current application from terminating. The CLR will not shutdown an application until all foreground threads have ended. The “Backgroundthreads are viewed by the CLR as expandable paths of execution that can be ignored at any point of time even if they are laboring over some unit of work. Thus, if all foreground threads have terminated, any background threads operating are automatically killed when the application terminates.


All processes have at least one thread of execution, which is usually called the main thread because it is the one that is executed when your program begins. From the main thread you can create other threads.
The classes that support multithreaded programming are defined in the System.Threading namespace.
Thus, you will usually include this statement at the start of any multithreaded program:


Methods

  • Suspend() -> Suspends the execution of a thread till Resume() is called on that.
  • Resume() -> Resumes a suspended thread. Can throw exceptions for bad state of the thread.
  • Sleep() -> A thread can suspend itself by calling Sleep(). Takes parameter in form of milliseconds. We can use a special timeout 0 to terminate the current time slice and give other thread a chance to use CPU time
  • Join()-> Called on a thread makes other threads wait for it till it finishes its task.

States of a Thread

States of a thread can be checked using ThreadState enumerated property of the Thread object which contains a different value for different states.
  • Aborted -> Aborted already.
  • AbortRequested -> Responding to an Abort() request.
  • Background -> Running in background. Same as IsBackground property.
  • Running -> Running after another thread has called the start()
  • Stopped -> After finishing run() or Abort() stopped it.
  • Suspended -> Suspended after Suspend() is called.
  • Unstarted -> Created but start() has not been called.
  • WaitSleepJoin -> Sleep()/Wait() on itself and join() on another thread. If a thread Thread1 calls sleep() on itself and calls join() on the thread Thread2 then it enters WaitSleepJoin state. The thread exists in this state till the timeout expires or another thread invokes Interrupt() on it. 

Properties of a Thread

  • Thread.CurrentThread -> Static method gives the reference of the thread object which is executing the current code.
  • Name -> Read/Write Property used to get and set the name of a thread
  • ThreadState -> Property used to check the state of a thread.
  • Priority -> Property used to check for the priority level of a thread.
  • IsAlive -> Returns a Boolean value stating whether the thread is alive or not.
  • IsBackground -> Returns a Boolean value stating the running in background or foreground.

PriorityLevels of Thread

Priority levels of thread is set or checked by using an enumeration i.e. ThreadPriority. The valid values are for this enumeration are;
  • Highest
  • AboveNormal
  • Normal
  • BelowNormal
  • Lowest 

Synchronization in Threads

 Monitor

Mutex 

Thread Pool 

When we have multiple threads that share data, we need to provide synchronized access to the data. We have to deal with synchronization issues related to concurrent access to variables and objects accessible by multiple threads at the same time. This is controlled by giving one thread a chance to acquire a lock on the shared resource at a time. We can think it like a box where the object is available and only one thread can enter into and the other thread is waiting outside the box until the previous one comes out.
using System;
using System.Threading;
namespace CSharpThreadExample

{
    class Program
    {
        static void Main(string[] arg)
        {
            Console.WriteLine("*****Multiple Threads*****");
            Printer p=new Printer();
            Thread[] Threads=new Thread[3];
            for(int i=0;i<3;i++)
            {
                Threads[i]=new Thread(new ThreadStart(p.PrintNumbers));
                Threads[i].Name="Child "+i;
            }
            foreach(Thread t in Threads)
                t.Start();

            Console.ReadLine();
        }
    }
    class Printer
    {
        public void PrintNumbers()
        {
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(100);
                Console.Write(i + ",");
            }
            Console.WriteLine();
        }
    }
}
 
In the above example, we have created three threads in the main method and all the threads are trying to use the PrintNumbers() method of the same Printer object to print to the console. Here we get this type of output:
image003.jpg
Now we can see, as the thread scheduler is swapping threads in the background each thread is telling the Printer to print the numerical data. We are getting inconsistent output as the access of these threads to the Printer object is synchronized. There are various synchronization options which we can use in our programs to enable synchronization of the shared resource among multiple threads.

Using the Lock Keyword

In C# we use lock(object) to synchronize the shared object.
Syntax:
lock (objecttobelocked) { objecttobelocked.somemethod(); } Here objecttobelocked is the object reference which is used by more than one thread to call the method on that object. The lock keyword requires us to specify a token (an object reference) that must be acquired by a thread to enter within the lock scope. When we are attempting to lock down an instance level method, we can simply pass the reference to that instance. (We can use this keyword to lock the current object) Once the thread enters into a lock scope, the lock token (object reference) is inaccessible by other threads until the lock is released or the lock scope has exited.
If we want to lock down the code in a static method, we need to provide the System.Type of the respective class.

Converting the Code to Enable Synchronization using the Lock Keyword

public void PrintNumbers() { lock (this) { for (int i = 0; i < 5; i++) { Thread.Sleep(100); Console.Write(i + ","); } Console.WriteLine(); } }

OUTPUT

image004.jpg

Using the Monitor Type

The C# lock keyword is just a notation for using System.Threading.Monitor class type. The lock scope actually resolves to the Monitor class after being processed by the C# compiler.


Converting the Code to Enable Synchronization using the Monitor Class

public void PrintNumbers() { Monitor.Enter(this); try { for (int i = 0; i < 5; i++) { Thread.Sleep(100); Console.Write(i + ","); } Console.WriteLine(); } finally { Monitor.Exit(this); } } Monitor.Enter() method is the ultimate recipient of the thread token. We need to write all code of the lock scope inside a try block. The finally clause ensures that the thread token is released(using the Monitor.Exit() method), regardless of any runtime exception.

OUTPUT

image005.jpg
In this article I have tried to make the explanation as simple as possible. I have referred the book written by Andrew Troelson published by Apress. Please provide your valuable comments and suggestions for improvement of this article. I am always open for future upgradation of the article.


  synchronization can be accomplished using the C# lock keyword and the Pulse 
method  of the Monitor object. The Pulse method notifies a thread in the waiting
queue of a change in the object's state (for more details on pulses, see the  
Monitor.Pulse Method). 
 
Only the current owner of the lock can signal a waiting object using Pulse.
The thread that currently owns the lock on the specified object invokes this method to signal the next thread in line for the lock. Upon receiving the pulse, the waiting thread is moved to the ready queue. When the thread that invoked Pulse releases the lock, the next thread in the ready queue (which is not necessarily the thread that was pulsed) acquires the lock.
Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code. The remarks for Wait(Object, Int32) address an issue that arises when Pulse is invoked before Wait.
To signal multiple threads, use the PulseAll method.
 
 
The example creates a Cell object that has two methods: ReadFromCell and WriteToCell.
Two other objects are created from classes CellProd and CellCons; these objects both have a
method ThreadRun whose job is to call ReadFromCell and WriteToCell. Synchronization is 
accomplished by waiting for "pulses" from the Monitor
 object, which come in order. That is, first an item is produced (the 
consumer at this point is waiting for a pulse), then a pulse occurs, 
then the consumer consumes the production (while the producer is waiting
 for a pulse), and so on.