Sunday, September 21, 2014

GET POST Method in ASP.NET C#

Many of you are aware of the GTE, POST, PUT & DELETE methods in ASP.NET, these are the basic method to send the value form one Form to another Form. Lets see how these work in ASP.NET project using C#.

GET :
Using GET method you can send all the input (textbox,textarea,radio button, checkbox etc..) to another form or another page. So how to do this?

Take a HTML page and write down the following HTML codes.

In Default.aspx to get the value of these two text boxes values we have to write code in Page_Load method. Make one thing clear, in the time of GET, POST we use NAME instead of ID. So lets check what will be for get method.
protected void Page_Load(object sender, EventArgs e)
{
     string name = ""; string pass = "";
     if (Request.QueryString["Name"] != null && Request.QueryString["Password"] != null)
     {
           name = Request.QueryString["Name"].ToString();
           pass = Request.QueryString["Password"].ToString();
     }
}

By Request.QueryString["Name"].ToString() this one we can get the value of a field which is sending through GET method. When we hit the submit button the URL will be something like this.

localhost/default.aspx?Name=arka&Password=arka1 

Normally we don't use GET to send sensitive fields like Passwords because it shows in the URL, I used it here just for an example.

POST :
Unlike GET in the POST method we can't see the values in the URL. It sends the values internally. Basically it has 2 parts. Head and body. In the head section it holds the variable name and in the body part holds the value. We will use the same example for the POST also.
Now lets check how to get the value using POST method in C# coding.
protected void Page_Load(object sender, EventArgs e)
{
     string name = ""; string pass = "";
     if (Request.Form["Name"] != null && Request.Form["Password"] != null)
     {
           name = Request.Form["Name"].ToString();
           pass = Request.Form["Password"].ToString();
     }
}
use Request.Form instead of Request.QueryString to get the value from POST method. And rest of the thing is same as GET.

AJAX UpdateProgress Image(GIF) and Text in ASP.NET C#

Hi, today I will show you how use AJAX Update Progress Bar to show loading process. You can show this with a loading GIF image or any text. Its better to use an image. You can download any one, as various kinds of GIF images are available in Google or you can create your own one.

Step #1 :
So, first off all create a new project and add  a new WebForm. Add a Script Manager at the top of the form before it flushes out from you mind and get an error. After adding take an Update Panel and within that UpdatePanel take a ContentTemplate. Each and every HTML and ASP controls have to be design within the ContentTemplate if you are putting them within UpdatePanel.

Step #2:
Take a new Button and a Label to execute the operation. And then add the most important thing for this article, the UpadateProgress. You will get this tool in the tool box within AJAX Extensions.


Add the UpdateProgress into the page and change the attribute AssociatedUpdatePanelID to the UpdatePanel name. and Dynamiclayout to true.

 AssociatedUpdatePanelID="UpdatePanel1"   DynamicLayout="true"

Step #3:
Here UpdatePanel1 is the UpdatePanel, which I have taken in the project. Place the image of loading into the ProgressTemplate within UpdateProgress with normal HTML image tool or write down the Text you want to display during the process.

Lets check the code how it works.

  
     
     
     
        
            Loading.. 
            Loading...
        
     
  


In the project I haven't done any such work that will took so much time to show the loading message. So I am using Thread.Sleep(3000) to gain a loading time of 3 seconds. Write down the following code into the button click event.
using System.Threading;

protected void btnShow_Click(object sender, EventArgs e)
{
     Thread.Sleep(3000);
     Label1.Text = "done !";
}

Now it should be clear how to show a progress bar (image or text) during  loading of some thing in ASP.NET. Hope it will help you to build your project successful. Happy coding... :)

Friday, September 19, 2014

Required field and email verification using Angular JS

In my previous post I have shown how to use Angular JS in your project , now in this post I will show you how to valid a required field or an email field using Angular JS. You can do this using ASP validation process or  using JavaScript or JQuery. But in this  post I will show you how to use Angular JS to validate the HTML fields.

Username: Username is required.
Email: Email is required. Invalid email address.

Run your page into local server to validate your HTML controls using Angular JS. Happy coding .... :)

Show instantly as write into the TextBox using Angular JS

This is my first post about Angular JS. Here in this post I will show you how to show the text into <p> tag as you type into a TextBox. I will do it with the help of Angular JS. Before starting it is important to discuss some thing about Angular JS.

So, what is Angular JS actually?

  1. AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you currently have to write.
To add this into your project add the following line into the head section.



aNow its time to start the project. Once again I clarify the aim of the project. There will be one TextBox and one <p> tag. As you type in the TextBox the text will be show in the <p> tag. You can do this in the TextChange event in the JavaScript or JQuery. But with the help of Angular JS its a matter of one line.

Lets come how to do this.

Type Text:

ng-app : directive defines an AngularJS application.
ng-model : directive binds the value of HTML controls like input, select, textarea etc. to application data.
ng-bind : directive binds application data to the HTML view. Now run your HTML page and check it out.

Your first Angular JS page is ready to rock n roll. 

Get HTML Select(Drop Down List) value in Code Behind (C#) in ASP.NET

Sometimes its very mush important to get the value of the HTML Drop Down List, Select value from the code behind (C#). So how to get the value of a HTML control value in the code behind. A very easy thing to do.

Create a new project and add a WebForm and add a new select tag with some value. Like this



Now in the C# page write the code to get the value.
string ddl = "";
// to get the selected value
ddl = Requets.Form["ddl"].ToString();

To get the selected value the actual code is
Requets.Form["ddl"]

In this way you can get the data of a HTML field from code behind (C#). With in that click event write down the following code

Thursday, September 18, 2014

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'

Sometime you found "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'." in your ASP project when you are running the project.

As a remedy of the project  "Please add a ScriptResourceMapping named jquery(case-sensitive)." What is this ? How to solve this? Very easy stuff to do.

If your project if there is no Global.asax added then add one into your project by clicking on the Add New Item. After adding this you will see there is a method Application_Start. Add the following script into that method.

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", 
    new ScriptResourceDefinition
{
  Path = "~/scripts/jquery-1.7.2.min.js",
  DebugPath = "~/scripts/jquery-1.7.2.min.js",
  CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
  CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
});

Now save the Global.asax and run your project. It will run successfully. :)

Saturday, September 13, 2014

SQL Split function to split an input string

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

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

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%. 

Friday, September 12, 2014

Ajax Control toolkit ModalPopUp in ASP.NET C#

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#

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.

Tuesday, September 9, 2014

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

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

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. :)

Saturday, September 6, 2014

MD5 encryptions in ASP.NET using C#

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.

Popular Posts

Tags

.net architecture (1) 2 step (1) 3 tier architecture (1) a4 size print (1) about (1) AbsoluteUri (1) access (2) add reference (1) ajax (6) ajax toolkit (3) angular js (2) application (1) array (1) ashx (2) asp.net (70) bin (1) binary tree (2) bitmap (1) C# (65) C#.net (21) captcha (1) check box (1) class (2) command argument (1) command name (1) connection string (1) console application (1) controls (1) convert ip to url (1) cookies (1) css (2) database (8) dataset (2) datatable (3) datepicker (1) debug (1) delegates (1) delete (2) deploy site in local iis (1) design (1) directory (1) dll (1) document (1) drawing (1) drop down list (4) dynamically aspx page create (1) edit (2) encryption (1) error (1) example (2) facebook (2) file (2) file upload (2) fillreectangle (1) folder (1) ftp (1) Genealogy (1) generic handler (2) get (1) global.asax (1) gmail (3) godaddy (1) google (1) graphics (1) gravatar (1) grid view (3) guid (1) hotmail (1) html (10) httpapplication (1) identity (1) iis (3) image (1) input output (1) instance (1) instant search (1) ip (1) itextsharp (1) java script (13) jquery (6) json (1) key logger in C# (1) lan (1) landscape print (1) link (1) linkedin (1) login (2) logout (1) mail (2) management console (1) master page (1) md5 (1) me (1) method overloading (1) metod overriding (1) mlm (2) model popup (1) moveable title (1) multiple table (1) mysql (1) object (1) off line (1) oledb (1) oops (1) outlook (1) page (2) pdf (1) pdfwriter (1) polymorphism (1) post (1) progress bar (1) quiz (1) random (1) regex (2) regular expression (1) repeater (5) routecollection (1) screen shot (1) ScriptManager (1) send mail (2) seo (1) server (1) server control (1) server urlencode (1) session (1) site (1) slider (1) sms (1) split string in sql (1) sql job scheduler (1) sql server (9) sqldatasource (1) store procedure (1) System.IO (1) system.net (1) template (1) text box (1) text to image (1) title (2) twitter (1) txt file (1) unable to copy (1) update panel (1) upload (1) url (3) url rewritting (1) virtual page (1) wcf (1) web (1) web user control (2) web.config (1) webclient (1) webmethod (1) windows (5) yahoo (2)

Total Pageviews