SQL Split function to split an input string

Leave a Comment
This article I am starting with a real life example. In posting an article in a blog we have to define tags (Like  C#.NET, AJAX, ASP.NET,HTML) upon the article. We usually take these tags in a TextBox with separated them by comma(,). To insert these into database we have two ways to do.

First Method using C# :

Using C# you can split the TextBox items and use a for loop to insert into the database. Code is as follow.
string []tags = txtTags.Text.Trim().Split(',');

/* With for loop */
for (int i=0;i<tags.Count ;i++)
{
 /* perform db query with tags[i].ToSting();
}

/* with foreach */
foreach (string i in tags)
{
  /* perform db query with i.ToSting();
}

Second SQL Method :

Here in the SQL we pass the whole items of TextBox into SQL function to split it and then insert these into specific table. Lets see how to do this.
CREATE FUNCTION SplitText
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT
 
      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END
 
      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)
           
            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
           
            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END
 
      RETURN
END
GO

-- Create a temporary table to insert tags
create #tblTemp
(
Id identity (1,1),
tag nvarchar(50)
)

-- Inserting into tmpTable
insert into #tblTemp (temp) values 
SELECT Item FROM dbo.SplitText('ASP.NET,C#.NET,ADO.NET,JavaScript', ',')  
-- Seperated by Comma(,). Place any thing according to you.

Execute your SQL batch query to inserting the tags into table.

Print Page in landscape mode in HTML CSS print media

Leave a Comment
Hi every one, today's topic is to print a HTML page into landscape mode. When we print a HTML page it takes by default portrait mode. But if we have to print it into landscape mode how to do it?

To do this s following...



Create a new HTML page and put the above code in head section.
Page 1
Page 2
Page 3
Page 4

Try it yours.

Output :
Landscape Print

Printing Page size in A4 using CSS Paged media

Leave a Comment
When ever you are sizing a div in your HTML page you size it with width and height in style sheet. Suppose whenever you have to print that div into A4 page size will it work properly? Not necessary it will print in the same size. So what to do? Simple put the div size into A4. But question is HOW? Let me clarify you.

Create a new HTML page and write create a div within body.

Page 1
Page 2
Page 3
Page 4
Now check the CSS once.
    body {
        margin: 0;
        padding: 0;
        background-color: #FAFAFA;
        font: 12pt;
    }
    * {
        box-sizing: border-box;
        -moz-box-sizing: border-box;
    }
    .page {
        width: 21cm;
        min-height: 29.7cm;
        padding: 2cm;
        margin: 1cm auto;
        border: 1px #000 solid;
        border-radius: 5px;
        background: white;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    }
    .subpage {
        padding: 1cm;
        border: 5px black solid;
        height: 237mm;
        outline: 2cm #000 solid;
    }
    
    @page {
        size: A4;
        margin: 0;
    }
    @media print {
        .page {
            margin: 0;
            border: initial;
            border-radius: initial;
            width: initial;
            min-height: initial;
            box-shadow: initial;
            background: initial;
            page-break-after: always;
        }
    }

View your page into browser and press Ctrl + P to check whether its diving the page according the size of A4 or not. I am sure it will work 100%. 

Ajax Control toolkit ModalPopUp in ASP.NET C#

Leave a Comment
Here I am going to show how to create a modal pop up using AJAX control toolkit in ASP.NET and C#. Before I have show how to create a pop up using JQuery and CSS, but now its pure asp. For this you need to add AJAX Control toolkit into your project. You can download as per your version of .NET (3.5,4.0,4.5).
After downloading create a project and add the reference of the AJAX Control Toolkit into your project.

Now your visual studio is ready to begin with AJAX Control Toolkit. Add a new Web Form. In the tool Box you will get the control ModalPopupExtender within AJAX Control Toolkit.

Lets first see how to set a ModalPopup to show any message. Check the following code.


AJAX Modal Popup

Here is the content which you wan to show

Run this example and on the button click you will get a pop up showing in your browser.

Lets move to an example where you will get an message showing with data from back end. Add another page and check following code.


In the CS page write down the following code.
protected void btnClick_Click(object sender, EventArgs e)
{
 /* get data from DB */
 lblusername.Text = TextBox1.Text;
 this.ModalPopupExtender1.Show();
}

Output :
Direct Message showing

Message from code behind


I hope its clear how to create popup and how to show message or show message from code behind. For further download the full source code here.

Polymorphism(Method Overloading and Overriding) in C#

Leave a Comment
Today's topic is a old one. Maximum among you are familiar with this topic. I am talking about one of the OOPs(Object Oriented Programming) feature polymorphism. In your college life you had come to know about polymorphism, but today I will discuss about this very known topic with the help of C#. As usual I have taken Find Area as an example like you did in your college.

Lets come to the point straight way.  Polymorphism has two parts.
  1. Method Overloading
  2. Method Overriding
Method Overloading :
So, lets start with the Method Overloading. Create a new project and take two textboxes, one button and one label for showing result.  Before starting one question came into the mind.. What actually method overloading is. Before this let me say about one very important issue about methods or function. A method name depends not only its name but also on its return type and argument. If you keep the name same and create a new method with a different return type and arguments it will act as a different method. This is  Method overloading. Calling the particular method, which has named more than one, but with distinct return type and argument.

In calculating area of a rectangle and a circle, the only difference is no of argument. In the first case you have to provide two argument(length and breath) but in the case of circle only one(radius) is enough to get the area. So, we will create two methods named FindArea() with 2 different argument. Lets check the following example.

/// 
/// For circle
/// 
/// 
/// 
private Double FindArea(string r)
{
     return 22 / 7 * Math.Pow(Convert.ToInt32(r),2);
}

/// 
/// For rectangle
/// 
/// 
/// 
/// 
private int FindArea(string l, string b)
{
     return (Convert.ToInt32(l) * Convert.ToInt32(b));
}        

Your methods are ready. Now you have to call these. For this generate click event of the button, and write down the following code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
 /* For rectangle */
 if (txt1.Text != "" && txt2.Text != "")
 {
  lblArea.Text =  FindArea(txt1.Text.Trim(), 
   txt2.Text.Trim()).ToString();
 }
 /* for circle */
 else if (txt1.Text != "" && txt2.Text == "")
 {
  lblArea.Text = FindArea(txt1.Text.Trim()).ToString();
 }
 else
 {
  lblArea.Text = "Fill any of the two input box !";
 }
}

I hope it is clear to you what is method overloading and how its work. Now lets move to method overriding.

Method Overriding :

Not like method overloading its about inheritance. Before starting discussing about the inheritance is important. Inheritance is one of the property of OPPs programming concept, to get the all properties and methods of a parent class to the child class. Like all of your parents property is yours, because you are inheriting your parents.

So here we have taken two classes, parent.cs and child.cs and child.cs is inheriting parent.cs. So what ever variables or methods are declare in the parent.cs is accessible for child.cs.

We have declare abc() method in both class and creating  an object of child class. Using this object we are calling the abc() method. Now in the child class there are two abc() methods are present. One is its own and another is inherited from parent class. So, which method will be called? Answer is child class one. The child class method will override the parent class method to execute. Lets check the code once.
public class parent
{
 public parent() { }

 public string abc()
 {
  return "parent -> abc";
 }
}

public class child : parent
{
 public child() { }

 public string abc()
 {
  return "child -> abc";
 }
}

Now call the method.

child obj = new child();
Response.Write(obj.abc());

Output : child -> abc

Hope so both are clear for you, for your help you can download the full source code here.

JQuery DatePicker with previous or future date disable in ASP.NET

Leave a Comment
Hi, in this example i will show you how to use JQuery DatePicker in ASP.NET along with disable future date or previous date. Before you start this lets check how to use JQuery DatePicker.

Take a html page and add JQuery api into your page. After this take a input textbox and write down the following code.






Now your problem is to get it in an ASP TextBox. So how to do this. Very simple replace the textbox with an ASP TextBox and in the place of #datePicker write down
<%= txtDatePicker.ClientID %>
where txtDatePicker is the ID of the ASP TextBox.
Now its time to disable the previous date and past date in the calender. For this we will get help of maxDate and minDate in DatePicker. Check the following code
$(function() {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
/* For future date */
$('<%= txtDatePicker.ClientID %>').datepicker({
maxDate: new Date(currentYear, currentMonth, currentDate)
});

/* For past date */
$('<%= txtDatePicker.ClientID %>').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate)
});

/* For current date */
$('<%= txtDatePicker.ClientID %>').datepicker({
minDate: 0
});
});

Run your project or HTML page to check and enjoy... Happy coding... :)

How to execute or perform a task at a specific time like 12 at night in SQL Server

Leave a Comment
Here in this example I will show you how to execute a task or call a store procedure at a specific time(like at midnight) using SQL Server or I can say how to schedule a job at a specific time. Some times you have to perform some thing daily, weekly or at a specific gap of time. Repeat the same task every time by a person is little bit difficult. So in that case SQL is here to solve your problem using SQL Job Scheduler. This is a task you fixed in your server, set timer on at particular time and write down the SQL query to perform. That's all you have to do. Lets see how to schedule your Job at a specific time.

Open your Management Studio and check the SQL Server Agent. Start the SQL Server Agent by following steps.


Now go to Job section in your SQL Server Agent and click to New Job.


After selecting the New Job a new window will be opened with all the properties of  a New Job. Now fill up each and every field according to your specification. 

In the General tabs write down any name according to your project and left the others as it is.


In the Step tab click on the New button, and a new window will be opened. 


Write a name for your step and your query to be executed and click on the OK button.


In the Schedule tab follow the steps as the image bellow.

Now your job is almost done. The only thing is left to start your job. To start the job follow the step.

After successfully starting of the job you will get a successful alert message.


So, your job schedule is done. Enjoy with your new job schedule. :)

MD5 encryptions in ASP.NET using C#

Leave a Comment
In the world of network encryption is one of the vital concept to secure your users' data from out side hackers. Generally when user input any password related field  its getting encrypted and then put that encrypted password into database. And in the case of retrieving there are two process are there. you can encrypt the imputing password and match it with the field in database or you can decrypt the stored password and match it with the input. I thing first one is much better and less time consuming.

So, how to encrypt your inputted password field. The most common  encryption method is MD5. Here in this example I will show you how to encrypt a string into an encrypted password using MD5 in ASP.NET using C#.

Create a new project and add a new WebForm to start your encrypted application. In the ASPX page add a new TextBox. Create a TextChange event and on the AutoPostBack property of the TextBox.

In the ASPX page design will be like this.

    
Encrypted password :

In the C# page write the following code.

using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;
using System;

namespace md5
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

            Byte[] ePass;

            UTF8Encoding encoder = new UTF8Encoding();

            ePass = md5Hasher.ComputeHash(encoder.GetBytes(TextBox1.Text));

            Label1.Text = Convert.ToBase64String(ePass);
        }
    }
}

In the Label1 you can see the encrypted password. Just put the ePass into the database to store as an encrypted password. Your encryption is over. Use it in your other projects and enjoy.

You can download the full source code here.

Insert into Database with GridView Edit Update and Delete in ASP.NET using C#

Leave a Comment
Hi everyone, today I will show you how to insert into a database and update, edit, delete into a GridView using ASP.NET and C# as a request of  Shruti Upari.

So create a new project in your Visual Studio and also open the SQL management Studio to create the database. First lets check the database. Create a new database and creata a new table for your project. Here i am working with just one table ie tblUser.

CREATE TABLE [dbo].[tblUser](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](50) NULL,
    [Email] [nvarchar](50) NULL,
    [pass] [nvarchar](50) NULL
) ON [PRIMARY]


Now come back to the ASP project and create three pages, one for insert, second for show data and last one for edit & delete.

In the Insert page add the TextBoxes according to your table. Here you have to take TextBox for name, email and password. The design of insert page...

Insert into DB

Name :
Email :
Password :
Confirm Password :

Here I have show with TextBox with validations.
Now lets check the coding of the insert page.

SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DemoDBConnectionString"].ToString());

protected void btnSave_Click(object sender, EventArgs e)
{
	SqlDataAdapter da;

	try
	{
		/* Check Email is already present or not */
		DataTable dt_email = new DataTable();
		da = new SqlDataAdapter("select * from tblUser where email='" + txtEmail.Text.Trim() + "'", con);
		da.Fill(dt_email);
		if (dt_email.Rows.Count > 0)
		{
			lblMessage.Text = "Email already exists.";
			lblMessage.ForeColor = Color.Red;
			return;   // important because it helps not to use else part
		}
		/* End chekcing */

		/* Entry into database */
		con.Open();
		SqlCommand cmd = new SqlCommand("INSERT INTO [DemoDB].[dbo].[tblUser] ([name],[Email] ,[pass]) VALUES ('" + txtName.Text.Trim() + "','" + txtEmail.Text.Trim() + "' ,'" + txtPassword.Text.Trim() + "')", con);
		cmd.Connection = con;
		if (cmd.ExecuteNonQuery() == 1)
		{
			lblMessage.Text = "Successfully done !";
			lblMessage.ForeColor = Color.Green;
		}
		else
		{
			lblMessage.Text = "Error !";
			lblMessage.ForeColor = Color.Red;
		}

		/* end entry */
	}
	catch (Exception ae)
	{
		lblMessage.Text = ae.Message;
		lblMessage.ForeColor = Color.Red;
	}
	finally
	{
		con.Close();
	}
}

Now the inserting is over. Now its time to show the data into show page. In show page we are using only a GridView to show the data. Lets check once.


	
	
		
		
		
		
	
	
	
	
	
	
	
	
	
	
	


Show page is also over. Its time for edit and delete. For this we will code in edit page. Check the front coding of the GridView.

	
	
		
			
				
			
		
		
			
				
			
			
				
			
		
		
			
				
			
		
		
			
				
			
			
				
			
		
		
		
	
	
	
	
	
	
	
	
	
	
	


Now lets check the coding to edit or delete the data. Previously in show page we are showing the GridView as AutoColumnGenerator=true. But here we made it false. And using a fillgrid() method to bind the GridView.
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DemoDBConnectionString"].ToString());

private void fillgrid()
{
	SqlDataAdapter da = new SqlDataAdapter("select * from tblUser",con);
	DataTable dt = new DataTable();
	da.Fill(dt);
	GridView1.DataSource = dt;
	GridView1.DataBind();
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
	try
	{
		string ID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblId")).Text;

		/* query to update db*/
		con.Open();
		SqlCommand cmd = new SqlCommand("delete tblUser  where id='" + ID + "'", con);
		cmd.Connection = con;
		if (cmd.ExecuteNonQuery() == 1)
		{
			lblMsg.Text = "Done !";
			lblMsg.ForeColor = Color.Green;
		}
		else
		{
			lblMsg.Text = "Error !";
			lblMsg.ForeColor = Color.Red;
		}
		/* end query */
	}
	catch (Exception ae)
	{
		lblMsg.Text = ae.Message;
		lblMsg.ForeColor = Color.Red;
	}
	finally
	{
		con.Close();
	}
	GridView1.EditIndex = -1;
	fillgrid();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
	try
	{
		string ID = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblId")).Text;

		string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName")).Text;
		string pass = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPass")).Text;

		/* query to update db*/
		con.Open();
		SqlCommand cmd = new SqlCommand("update tblUser set name='" + name + "', pass ='" + pass + "' where id='" + ID + "'", con);
		cmd.Connection = con;
		if (cmd.ExecuteNonQuery() == 1)
		{
			lblMsg.Text = "Done !";
			lblMsg.ForeColor = Color.Green;
		}
		else
		{
			lblMsg.Text = "Error !";
			lblMsg.ForeColor = Color.Red;
		}
		/* end query */
	}
	catch (Exception ae)
	{
		lblMsg.Text = ae.Message;
		lblMsg.ForeColor = Color.Red;
	}
	finally
	{
		con.Close();
	}
	GridView1.EditIndex = -1;
	fillgrid();
}

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
	GridView1.EditIndex = e.NewEditIndex;
	fillgrid();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
	GridView1.EditIndex = -1;
	fillgrid();
}

Now run the project and check your db to be filled or not. Download the full source code to execute.

Delegates in C#

1 comment
We have used pointers in C, delegates are something like pointers in C but type safe. Previously we send data as parameter but today we send methods as parameter through objects. In C# 2.0 delegates are introduced. It used to send methods to pass through its object. Its like a reference variable to the reference of the method which you have to execute.It is derived  from System.Delegate class and generally use for implementing events and call back method. In the next few lines I will show you how to declare a delegate and how to execute through the object of the delegate.

First we lets see how to declare the delegate in C#.

public delegate int delegate1 (string input);
public delegate void delegate2 (string input);
public delegate string delegate3 (string input);

In these above code two delegates are declared. First one for a method which takes an input string and return a integer value. Second one is taking an input string as first one but returning nothing(void). And third and the last one denotes a method which takes string also return string. So is clear how to declare different delegate. Now lets check how to call the delegates. To call using these delegates we need to create objects of these three delegates. Lets create three objects of these three.

public delegate int delegate1 (string input);
public delegate void delegate2 (string input);
public delegate string delegate3 (string input);

delegate1 obj1 = new delegate1(methodReturnInt);
delegate2 obj2 = new delegate2(methodReturnVoid);
delegate3 obj3 = new delegate3(methodReturnString);

So objects are created of these different delegates.methodReturnInt, methodReturnVoid, methodReturnString  these are the method name which are called by the three delegate objects. Suppose the three methods are like...
 
// return int 
public static int methodReturnInt(sting ip)
{
   return 0;
}

// return void
public static void methodReturnVoid(sting ip)
{
   return ;
}

// return string
public static string methodReturnString(sting ip)
{
   return "Hi !";
}

Now how to call through the objects. Lets see.
static void Main(string[] args)
{
  // creating objects
  delegate1 obj1 = new delegate1(methodReturnInt);
  delegate2 obj2 = new delegate2(methodReturnVoid);
  delegate3 obj3 = new delegate3(methodReturnString);

  // calling methods with value
  obj1("abc");
  obj1("pqr");
  obj1("xyz");
}

I thing now its clear to you how to use delegates in your project after these short session of coding. Try it yourself and bang it. Happy coding.... :)

How to deploy a site in local IIS with database

Leave a Comment
Here I will show you how to deploy your site in your local IIS with your database, so that your site can be access from any other computers connected in your LAN.

The very first thing you have to know what IIS is? Full form of IIS is Internet Information Services. According to Wikipedia IIS is
Internet Information Services (IIS, formerly Internet Information Server) is an extensible web server created by Microsoft for use with Windows NT family.[2] IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP. It has been an integral part of the Windows NT family since Windows NT 4.0, though it may be absent from some editions (e.g. Windows XP Home edition). IIS is not turned on by default when Windows is installed. The IIS Manager is accessed through the Microsoft Management Console or Administrative Tools in the Control Panel.
First of all create your own application with database and then prepare your published project.

To upload your application you need to enable IIS in your local machine. To do that visit my article on Configure your IIS in local machine. It will take 1-2 minutes to configure your IIS. After this go to Run and type inetmgr to open the local IIS. You can verify your IIS is working or not. Go to your browser and type
localhost. It will open your IIS in browser.

Now its time to add your application into IIS. Open your IIS and click on the Default under Site.


Now on the Default you can see there are some sites are uploaded previously in the above image. Now click on the Application Pool and you can see there are previously created application pool. To create your own application pool click on the Add Application pool.


Here input the name and .NET framework and save it. Now back to Site in your IIS. Select the Default and right click on the Default. Select Add Application.


After clicking on the link a window will be opened and there you have to give the alias name. It will be your site name. Suppose you are imputing "arka", so your site will be opened as localhost/arka.  In the physical path select the folder where your published files are situated. Now a main thing, choosing the Application Pool in the DropDownList. Select your application pool that you have created. Now your site is ready to launch after clicking in the OK button. 


Give your files and folders with full permission to access those from any other computer. To do that, select the root folder and go to properties. Within properties choose Security tab. Click on the Edit button and then Add button. From there go to Advance option and click on the Find Now to find your IIS User.  


 Add your IIS_USERS to add users.

 Now another one important thing you have to do. Connect your .NET with IIS. To do that open your command and run these code according to your OS bit, either 32 or 64 bit.

For 64 bit 
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

For 32 bit
%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i

It will install the ASP.NET with IIS connection. Now your application is ready to launch without database. 
It time to connect the database with your IIS.

Open your SQL Management Studio and select your database. Under Security section click on the User, and Add New user.


On the Login name click on the button beside and a new window will be opened with Login object. Click on the Browser and choose the application pool that you have created.


Now after adding click on the OK to add the user. Now go to Server Security section and Add New Login 

Now in the opened window go to User map section and choose your database.


Now click on the button on the left side another new window will be opened with Schema object. There write dbo and click on the Check name. Click on the OK button to proceed. Now back to User Mapping and check db_datawiter and db_datareader. Now again go to the security part of your database. 

Go to Securables  and  choose all the check boxes in Grant and click on the OK button.

Now your application is fully configured to launch. Browse your site and ask your friends to browse your site from other computers in your LAN.

Checkbox in Gridview header to select all rows using JavaScript in ASP.NET

Leave a Comment
In many sites you may watch in a table there are check boxes to select or deselects. And above all these check boxes there is one check box which controls all other text boxes to select and deselect. To day in this example I will show you how to design a check box into a  GridView to design and work like the above statement in ASP.NET.

So, first of all create a new project and add a new WebForm to start. In the C# code add the connection first as per your database and bind your GridView with the DataTable or DataSet. To add a column of check boxes make sure the AutoGenerateColumns property is false. Manually add your database columns and at the last add your check box.

Coding in GridView will be some thing like these.

 
  
   
    
   
   
   
    
   
  
  
  
 


After binding your GridView check it once if it is running successfully or not. If its running successfully come to the JavaScript coding to select or deselect the check boxes using master check box. As here we are taking master check box only in Header, you can take this also in Footer or in both place. Now its time to code in JavaScript. On the Head section of your ASPX page add Script tag and close it. With in that Script tag write down the following js code.



Now run the project and check if your check boxes are working fine or not. I am sure it will run successfully. In the next article I will show you how to take those selected rows on a button click.

You can download the full source code here.
Download Now