Monday, 3 September 2012

Iterating items in XML using cursor in sql server

DECLARE @CUR CURSOR
DECLARE @VAR1 VARCHAR(20)
DECLARE @XML XML

SET @XML = '
      <contacts >
         <contact>
            <names>Bob1</names>           
         </contact>
         <contact>
            <names>Bob2</names>           
         </contact>
         <contact>
            <names>Bob3</names>           
         </contact>
      </contacts>'

SET @CUR = CURSOR FOR
 SELECT  convert(VARCHAR(20),contact.ITEM.query('./names').value('.','VARCHAR(20)')) names
                                            FROM @XML.nodes('/contacts/contact') AS contact(ITEM)
                                           
OPEN @CUR
FETCH NEXT
FROM @CUR INTO @VAR1

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @VAR1
PRINT '------------------------------------------------'
FETCH NEXT
FROM @CUR INTO @VAR1
END
CLOSE @CUR
DEALLOCATE @CUR




Above is the sample used to iterating item in xml using cursor in sql server
 

Thursday, 28 June 2012

Call Page Method from JavaScript

Call Page Method from JavaScript



Write Page Method that You want to call (Method Must be Static):

public partial class PageMethod : System.Web.UI.Page
{
   [System.Web.Services.WebMethod()]
    public static string GetMenuItem()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(“<ul>”);
        sb.AppendFormat(“<li>{0}</li>”,”First”);
        sb.AppendFormat(“<li>{0}</li>”, “Second”);
        sb.AppendFormat(“<li>{0}</li>”, “Third”);
sb.AppendFormat(“<li>{0}</li>”, “Forth”);
        sb.AppendFormat(“<li>{0}</li>”, “Fifth”);
        sb.Append(“</ul>”);
        return sb.ToString();
    }
}


Write JavaScipt to call Page Method :



    <script type=”text/javascript” language=”javascript”>
        function CallWebServiceMethod() {
        PageMethods.GetMenuItem(GetMenuItemComplete, errormethod);
        }

       function GetMenuItemComplete(val) {   /// Called When page method execute successfully
            $get(“divItem”).innerHTML = val;
        }

        function errormethod(val) {    ///  called when error occurs in execution
        alert(“Error” + val)
        }
    </script>


At last Write HTML for display result :


<body onload=”CallWebServiceMethod();”>
    <form id=”form1? runat=”server”>
    <asp:ScriptManager ID=”ScriptManager1? EnablePageMethods=”true” runat=”server”>
/// Bold written Attribute required for calling Page  method
    </asp:ScriptManager>
    <div id=”divItem”>
    </div>
    </form>
</body>

SESSION IN JAVASCRIPT


Session in Javascript



<script type=”text/javascript”>
 //To set Session
function Setsession() {
    if (window.sessionStorage) {
       sessionStorage.setItem(“key1″, document.getElementById(‘<%= Write.ClientID %>’).value);               
    }
}

//To get Session
 
function GetSession() {
     if (window.sessionStorage) {
         document.getElementById(‘<%= Get.ClientID %>’).value = sessionStorage.getItem(“key1″);
      }
}


</script>



To get Session Value using javascript

 <script type=”text/javascript”>
var session = '<%= Session["VALUE"] %>'; 

</script> 

Thursday, 29 March 2012

How to create a database backup using visual studio

I am going to create a backup using a C# Windows forms project. The project is simple. You will have a button to create a database backup in the windows form. Every time that you click the button, a new backup is created.



This project includes the following components:
  • A database backup: test.zip
  • The Windows form project: backup.zip
  • A script with the backup stored procedure: createBackup.sql

Requirements

The requirements to build this are:
  • Visual Studio 2008 or later
  • SQL Server 2005 or later

Getting started

Let’s start. We are going to create a stored procedure first that creates a backup of the test database (you can create a test database or restore from the test.bak attached manually).
The following T-SQL will do this:
create procedure [dbo].[backupdb]
as

BACKUP DATABASE [test] TO  DISK = N'C:\backup\test.bak'
  WITH NOFORMAT
     , NOINIT
     , NAME = N'test copy'
     , SKIP
     , NOREWIND
     , NOUNLOAD
     , STATS = 10
Peace of cake, isn’t it? We are creating the test database backup in the c:\backup folder and the backup name is test.bak. Subsequent backups are all written to the same file. Everything to do this is in the stored procedure named dbo.backupdb.
To execute the stored procedure use the following command:
exec [dbo].[backupdb]
The stored procedure will create a backup inside the test.bak file. 
Now, let’s start with the Visual Studio application. Open the backup.sln in the backup.zip file. In the Solution Explorer, double click in the app.config item.  The content of the file should be the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="connectionStringName"
         connectionString="Data Source=.\SQLEXPRESS
         ;Initial Catalog=test;Integrated Security=True;async=true "/>
  </connectionStrings>
</configuration>
Let me explain this part of the app.config:
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;async=true "/>
This file contains the connection to the SQL Server. In this case, it is a local SQL Server Express Edition. The initial catalog is the database test and it is using integrated security (Windows authentication).
To use the app.config file it is necessary to add the System.configuration:



The system configuration references needs to be added. To do this, in the Solution Explorer, in references right click the button mouse and select add references.
In the references window, select the System Configuration.

In the design pane, double click the backup button to see the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace backup
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string ConnectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ToString();
                SqlConnection cnn = new SqlConnection(ConnectionString);

                SqlCommand cmd = new SqlCommand("backupdb", cnn);
                cmd.CommandType = CommandType.StoredProcedure;

                cnn.Open();

                cmd.ExecuteNonQuery();

                MessageBox.Show("Backup completed successfully");

                Cnn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

Note that the following lines are not created by default. These lines of code need to be added in order to connect to SQL Server and to use the App.config file.
using System.Data.SqlClient;
using System.Configuration;
Let me explain these lines of code:
string ConnectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ToString();
This line of code will save the connection data created in the app.config file in the connectionString.
The following lines of code are used to call the stored procedure backupdb and execute the stored procedure using Visual Studio.
SqlCommand cmd = new SqlCommand("backupdb", cnn);

cmd.CommandType = CommandType.StoredProcedure;

cnn.Open();

cmd.ExecuteNonQuery();
These lines of code will call the stored procedure created and execute it.
That’s it !. You have a button to create a backup.
In the project, just press F5 in order to start the project. In the Windows form press the backup button. You will create the database backup in the c:\backup\test.bak. If the file was created, you successfully created a Project in Visual Studio to generate SQL Server backups !. 



Reference: 
http://www.sqlservercentral.com/articles/C%23/88007/

Wednesday, 7 March 2012

Microsoft .NET Frameworks features details

Microsoft .NET Frameworks....


Features and enhancements that has happened with respect to Microsoft .NET Frameworks

Objective


To know the series of events happened with respect to .NET framework.

Microsoft .NET Framework Details

Features: .NET Framework Version - V1.0/1.1: Released in Year 2002/2003
  1. CLR 1.0/1.1
  2. C#.NET was introduced
  3. Upgraded to VB.NET from VB 6
  4. Upgraded to ASP.NET from ASP 3
  5. Upgraded to ADO.NET from ADO
  6. Remoting (previously DCOM) was introduced
  7. Web Services introduced
  8. Visual Studio Versions:  2002/2003
Features: NET Framework Version - V 2.0: Released in Year/2005
  1. CLR 2.0
  2. C#/VB/ASP/ADO.NET 2.0
  3. Web Services Enhancements (WSE)
  4. ASP.NET AJAX
  5. Visual Studio Versions:  2005
Features: NET Framework Version - V 3.0: Released in Year/2006
  1. CLR 2.0
  2. C#/VB/ASP/ADO.NET 2.0
  3. Windows Presentation Foundation (WPF) introduced
  4. Windows Communication Foundation (WCF) introduced
  5. Windows Workflow Foundation (WF) introduced
  6. Windows CardSpace introduced
  7. Visual Studio Versions:  VS 2005
Features: NET Framework Version - V3.5: Released in Year/2008
  1. CLR 2.0
  2. C#/VB/ASP/ADO.NET 3.5
  3. Language Integrated Query (LINQ)
  4. WCF/WPF/WF 3.5
  5. ASP.NET AJAX is built-in
  6. Visual Studio Versions:  VS 2008
Features: NET Framework Version – V3.5 SP1: Released in Year/2009
  1. Silverlight
  2. Entity Framework
  3. ASP.NET MVC
Features: NET Framework Version – V4.0: Released in Year/2010
  1. CLR 4.0
  2. C#/VB/ASP/ADO.NET 4.0
  3. LINQ/EF 4.0
  4. WCF/WPF/WF 4.0
  5. Silverlight 3.0
  6. ASP.NET MVC 2.0
  7. F#.NET introduced
  8. Dynamic Programming
  9. Parallel Programming
  10. Visual Studio Versions: VS 2010
Features: NET Framework Version – V4.5:  Beta is released
  1. Visual Studio Versions: VS 2011 
For further reading on V4.5, visit http://www.asp.net/vnext/overview/whitepapers/whats-new




Reference:
http://www.dotnetfunda.com

Saturday, 18 February 2012

Printing GridView from ASp.net




<%@ Page Language="C#" %>

<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  private DataTable GetDataTable()
  {
      //create table
      DataTable dt = new DataTable("Product");
      dt.Columns.Add("ProductID", Type.GetType("System.Int32"));
      dt.Columns.Add("ProductName", Type.GetType("System.String"));

      //create fields
      DataColumn[] pk = new DataColumn[1];
      pk[0] = dt.Columns["ProductID"];
      dt.PrimaryKey = pk;
      dt.Columns["ProductID"].AutoIncrement = true;
      dt.Columns["ProductID"].AutoIncrementSeed = 1;
      dt.Columns["ProductID"].ReadOnly = true;

      //fill rows
      DataRow dr;
      for (int x = 1; x <= 10; x++)
      {
          //make every other one different
          if (Math.IEEERemainder(x, 2) == 0)
          {
              dr = dt.NewRow();
              dr["ProductName"] = "Riss";

              dt.Rows.Add(dr);
          }
          else
          {
              dr = dt.NewRow();
              dr["ProductName"] = "Product";

              dt.Rows.Add(dr);

          }
      }

      return dt;
  }

  protected void Page_Load(object sender, EventArgs e)
  {
      if (!IsPostBack)
      {

          GridView1.DataSource = GetDataTable();
          GridView1.DataBind();
      }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>

  <script type="text/javascript">
  function CallPrint(strid)
  {
      var prtContent = document.getElementById(strid);
      var WinPrint = window.open('','','letf=0,top=0,width=400,height=400,toolbar=0,scrollbars=0,status=0');
      WinPrint.document.write(prtContent.innerHTML);
      WinPrint.document.close();
      WinPrint.focus();
      WinPrint.print();
      WinPrint.close();

}
  </script>

</head>
<body>
  <form id="form1" runat="server">
      <div id="divPrint">
          <asp:GridView ID="GridView1" runat="server" />
      </div>
      <input type="button" value="print " id="btnPrint" runat="Server" onclick="javascript:CallPrint('divPrint')" />
  </form>
</body>
</html>



use html (<input type="button">)  button instead of <asp:button>>. 

Friday, 17 February 2012

ASP.NET Open PopUp Window Update Refresh Values


In this example i am going to describe how to open popup window from aspx page with values from parent page, and update or refresh values in parent window from child or popup window using javascript and ClientScript.RegisterStartupScript method in ASP.NET

I have added to labels in Default.aspx page and one button to open popup window.

I've also added a PopUp.aspx page which is having two textboxes and a button to update lable values of parent page.


The textboxes in popup window are populated with Text values of lables in parent page (Default.aspx), after making changes in textbox values i'm updating values back in parent page.

















HTML source of Default.aspx (parent) page is
<form id="form1" runat="server">
<div>
First Name :
<asp:Label ID="lblFirstName" runat="server" Text="amiT">
</asp:Label><br />
 <br />
Last Name:&nbsp;
<asp:Label ID="lblLastName" runat="server" Text="jaiN">
</asp:Label><br />
<br />
<asp:Button ID="btnPop" runat="server" Text="Click To Edit Values" />
</div>
</form>
Write this Javascript in Head section of Default.aspx page
In this i m getting values of lables and passing them to popuup page as querystrings
write this code Page_Load event of Default.aspx (parent) page
C# code behind
01protected void Page_Load(object sender, EventArgs e)
02{
03 string updateValuesScript =
04@"function updateValues(popupValues)
05{
06 document.getElementById('lblFirstName').innerHTML=popupValues[0];
07 document.getElementById('lblLastName').innerHTML=popupValues[1];
08}";
09 
10this.ClientScript.RegisterStartupScript(Page.GetType(),
11"UpdateValues", updateValuesScript.ToString(), true);
12btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')");
13}

VB.NET code behind
1Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
2    Dim updateValuesScript As String = "function updateValues(popupValues)" & vbCr & vbLf & "{" & vbCr & vbLf & " document.getElementById('lblFirstName').innerHTML=popupValues[0];" & vbCr & vbLf & " document.getElementById('lblLastName').innerHTML=popupValues[1];" & vbCr & vbLf & "}"
3 
4    Me.ClientScript.RegisterStartupScript(Page.[GetType](), "UpdateValues", updateValuesScript.ToString(), True)
5    btnPop.Attributes.Add("onclick", "openPopUp('PopUp.aspx')")
6End Sub

And this is the HTML code for PopUp.aspx(child) page
<form id="form1" runat="server">
<div>
First Name :
<asp:TextBox ID="txtPopFName" runat="server" Width="113px">
</asp:TextBox><br />
<br />
Last Name:<asp:TextBox ID="txtPopLName" runat="server" 
                       Width="109px">
</asp:TextBox><br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" 
            Text="Button" /></div>
</form>
Code behind for PopUp.aspx
C# code behind
01protected void Page_Load(object sender, EventArgs e)
02{
03 string updateParentScript =
04 @"function updateParentWindow()
05 {                                                                              
06   var fName=document.getElementById('txtPopFName').value;    
07   var lName=document.getElementById('txtPopLName').value;  
08   var arrayValues= new Array(fName,lName);
09   window.opener.updateValues(arrayValues);      
10   window.close();
11 }";
12 this.ClientScript.RegisterStartupScript(this.GetType(),
13     "UpdateParentWindow", updateParentScript, true);
14 if (!IsPostBack)
15 {
16   txtPopFName.Text = Request["fn"];
17   txtPopLName.Text = Request["ln"];
18 }
19   Button1.Attributes.Add("onclick", "updateParentWindow()");
20}
VB.NET code behind
1Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
2    Dim updateParentScript As String = "function updateParentWindow()" & vbCr & vbLf & " {                                                                               " & vbCr & vbLf & "   var fName=document.getElementById('txtPopFName').value;     " & vbCr & vbLf & "   var lName=document.getElementById('txtPopLName').value;   " & vbCr & vbLf & "   var arrayValues= new Array(fName,lName);" & vbCr & vbLf & "   window.opener.updateValues(arrayValues);       " & vbCr & vbLf & "   window.close(); " & vbCr & vbLf & " }"
3    Me.ClientScript.RegisterStartupScript(Me.[GetType](), "UpdateParentWindow", updateParentScript, True)
4    If Not IsPostBack Then
5        txtPopFName.Text = Request("fn")
6        txtPopLName.Text = Request("ln")
7    End If
8    Button1.Attributes.Add("onclick", "updateParentWindow()")
9End Sub

Total Pageviews