Monday 29 December 2014

How to call javascript and jquery function from code behind in ASP.net and c#

Introduction: Here I will tell you how you can call javascript and jquery function 
from codebehind.
Descirption:
Here I will tell you how you can call javascript and jquery function from codebehind.
If you are using scriptmanager on page then you can call
ScriptManager instance.
If you are not using script manager then you can call 
Page.ClientScript instance

Implementation:
In Code Behind 
protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", 
 "MyFunction();", true);
} 

protected void MyButton_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this.GetType(), "myScript", 
  "MyFunction();", true);
} 

Sunday 28 December 2014

Abstract classes in C#.NET, VB.NET

Introduction: Abstract classes are those classes that can not be instantiated, but they can be inherited by 
other classes.
Description: Abstract classes are those classes that can not be instantiated, but they can be inherited by 
other classes. Abstract classes are base classes and inherited classes are called derived classes.
Abstract class can have both abstract and non abstract method in it. 
When to use: It is use to give common functionality to all inherited classes. it works like a base class.
Implementation:
abstract class MyShapes
{ 
abstract public int MyArea();
}
class Square : MyShapes
{
int side = 0;
 public Square(int n)
{ 
side = n; 
}
// Override Area method
public override int MyArea()
{ 
return side * side; 
}
}
class Rectangle : MyShapes
{
int length = 0, width=0;
public Rectangle (int length, int width)
{
this.length = length;
this.width = width;
// Override Area method 
public override int MyArea()
{ 
return length * width; 
}
}

Thursday 4 December 2014

Call web method from page using jquery and ajax without postback

Introduction: In this article I will show you how to call webmethod from aspx page using jquery
and ajax without postback.

Description:  Call webmethod from aspx page using jquery and ajax without postback.



In Aspx Page:

<head runat="server">
    <title></title>
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowTime() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetTime",
        data: '{name: "' + $("#<%=txtName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}
</script>
</head>

<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<div>
Your Name :
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time"
    onclick = "ShowCurrentTime()" />
</div>
</form>
</body>


In Code Behind:

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}


Wednesday 12 November 2014

How to change SQL server database mode from single user to multiuser and multi user to single user

Introduction: In this example you can set database mode to single user or multiuser

Description: Here you will see how to change database mode to single and multiuser.

Implementation:

Set Multi User Mode  to Single User Mode
 
USE MASTER;
GO
ALTER DATABASE [databasename] SET SINGLE_USER
 
Set Single User Mode to Multi User Mode 


USE MASTER;
GO
ALTER DATABASE [databasename] SET MULTI_USER
 
 

Saturday 8 November 2014

Bind Asp.net Dropdownlist from database in C#, VB.net

Introduction: Here I will explain how to bind dropdownlist from database.
Description: Today I will show you how to bind dropdownlist static and from database also I will
explain you how to find data in dropdownlist by text and by value.
Before implement this example we need database

Column NameDataTypeAllowNulls
UserId Int(set identity true) No
UserName VarChar(50) Yes
Location VarChar(50) Yes

Once table is designed write below code to your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>how to show data in dropdownlist from database in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Selected UserName:</b>
<asp:DropDownList ID="ddlUser" runat="server" />
</div>
</form>
</body>
</html


Now add the following namespace to code behind

C# code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

After add namespace write the following code to code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindUserdropdown();
}
}
/// <summary>
/// Bind Userdropdown
/// </summary>
protected voidBindUserdropdown ()
{
//conenction path for database
using (SqlConnection con = new SqlConnection("Data Source=Manoj;Integrated Security=true;Initial Catalog=MySchool"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserId,UserName FROM UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlUser.DataSource = ds;
ddlUser.DataTextField = "UserName";
ddlUser.DataValueField = "UserId";
ddlUser.DataBind();
ddlUser.Items.Insert(0, new ListItem("--Select--", "0"));
con.Close();
}
}
VB.Net Code 
 
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Partial Class VBSample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindUserdropdown()
End If
End Sub
''' <summary>
''' Bind UserDropdownlist
''' </summary>
Protected SubBindUserdropdown ()
'conenction path for database
Using con As New SqlConnection("Data Source=Manoj;Integrated Security=true;Initial Catalog=MySchool")
con.Open()
Dim cmd As New SqlCommand("Select UserId,UserName FROM UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
ddlUser.DataSource = ds
ddlUser.DataTextField = "UserName"
ddlUser.DataValueField = "UserId"
ddlUser.DataBind()
ddlUser.Items.Insert(0, New ListItem("--Select--", "0"))
con.Close()
End Using
End Sub
End Class
 

Wednesday 5 November 2014

Compress and Extract files to zip in Asp.net C#

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplicationZip
{
    class Program
    {
        static void Main(string[] args)
        {
            string startPath = @"c:\example\source";
            string zipPath = @"c:\example\source\result.zip";
            string extractPath = @"c:\example\destination";

            ZipFile.CreateFromDirectory(startPath, zipPath);

            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}

Sunday 19 October 2014

Dialog Boxes in JavaScript(Alert, Prompt, Confirm)

Alert Dialog Box:
Alert dialog box is used to give alert on validation or other condition.
<head>
<script type="text/javascript">
<!--
   alert("Please enter value");
//-->
</script>
</head>
 
Confirm Dialog box:
This box is used to confirm for any condition 
<head>
<script type="text/javascript">
<!--
   var result= confirm("Are you sure to delete?");
   if( result== true ){
      alert("User wants to delete!");
   return true;
   }else{
      alert("User does not want to delete!");
   return false;
   }
//-->
</script>
</head>
Prompt Dialog Box:
This prompt dialog box is used to get user input on text box.
<head>
<script type="text/javascript">
<!--
   var result= prompt("please enter your name : ", "enter your name here");
   alert("You have entered : " +  result);
//-->
</script>
</head>  
 

Page Redirection in JavaScript

How Page Redirection Works?
<head>
<script type="text/javascript">
<!--
   window.location="http://www.yourlocation.com";
//-->
</script>
</head> 
 
In this examples you can set the time after that you can redirect to your location 
<head>
<script type="text/javascript">
<!--
function RedirectToPage()
{
    window.location="http://www.yourlocation.com";
}

document.write("You will be redirected to yourlocation in 10 sec.");
setTimeout('RedirectToPage()', 10000);
//-->
</script>
</head> 

In this example you can get the browser and redirect to perticular url based on 
browser type
<head>
<script type="text/javascript">
<!--
var browser=navigator.appName; 
if( browser== "Netscape" )
{ 
   window.location="http://www.yourlocation.com/ns.htm";
}
else if ( browser=="Microsoft Internet Explorer")
{
   window.location="http://www.yourlocation.com/ie.htm";
}
else
{
  window.location="http://www.yourlocation.com/other.htm";
}
//-->
</script>
</head>

Saturday 18 October 2014

Call JavaScript Function on Button Click Event

Create a function Named HelloWorld and call that function on button click event
 <html>
<head>
<script type="text/javascript">
<!--
function HelloWorld() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="HelloWorld()" value="Click Here" />
</body>
</html>

JavaScript Functions

Function Example 
<script type="text/javascript">
<!--
function Hello()
{
   alert("Hello");
}
//-->
</script> 
Parameterized Function Examples 
<script type="text/javascript">
<!--
function FullName(FirstName,LastName)
{
   alert(FirstName + " " + LastName);
}
//-->
</script> 
Function Return 
<script type="text/javascript">
<!--
function FullName(FirstName,LastName)
{
   return (FirstName + " " + LastName);
}
//-->
</script>

Friday 17 October 2014

For loop in JavaScript

For Loop: 
<script type="text/javascript">
<!--
var counter;
document.write("Loop Starts" + "<br />");
for(counter= 0; counter< 10; counter++){
  document.write("Current counter: " + counter);
  document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>
 
This script will produce the below result 
Loop Starts
Current counter: 0
Current counter: 1
Current counter: 2
Current counter: 3
Current counter: 4
Current counter: 5
Current counter: 6
Current counter: 7
Current counter: 8
Current counter: 9
Loop stopped! 

While loop in JavaScript

While loop works until the condition is true 

<script type="text/javascript">
<!--
var counter = 0;
document.write("Loop Starts" + "<br />");
while (count < 5){
  document.write("Counter : " + counter + "<br />");
  count++;
}
document.write("Loop Ends!");
//-->
</script>

Thursday 16 October 2014

Switch Case in JavaScript

<script type="text/javascript">
<!--
var result='A';
document.write("I am entering in switch block<br />");
switch (grade)
{
  case 'A': document.write("Good<br />");
            break;
  case 'B': document.write("Pretty<br />");
            break;
  case 'C': document.write("Passed<br />");
            break;
  case 'D': document.write("Not so<br />");
            break;
  case 'F': document.write("Failed<br />");
            break;
  default:  document.write("NA<br />")
}
document.write("I am Exiting from switch block");
//-->
</script>
 
This will produce the following result:
 
I am entering in switch block
Good
I am Exiting from switch block
 
if you do not use Break 

<script type="text/javascript">
<!--
var result='A';
document.write("I am entering in switch block<br />");
switch (grade)
{
  case 'A': document.write("Good<br />");            
  case 'B': document.write("Pretty<br />");            
  case 'C': document.write("Passed<br />");            
  case 'D': document.write("Not so<br />");            
  case 'F': document.write("Failed<br />");            
  default:  document.write("NA<br />")
}
document.write("I am Exiting from switch block");
//-->
</script>
 
This will produce the following Result:
 
I am entering in switch block
Good 
Pretty
Passed 
Not so
Failed 
NA
I am Exiting from switch block 
 

JavaScript If ...... else Statements

Syntax for IF Statement 
<script type="text/javascript">
<!--
var result= 20;
if( result> 18 ){
   document.write("<b>Result is greater than 18</b>");
}
//-->
</script>
 
Syntax for IF Else Statement 
<script type="text/javascript">
var result= 20;
if( result> 18 ){
   document.write("<b>Result is greater than 18</b>");
}
else 
{ 
   document.write("<b>Result is less than 18</b>");
} 
</script>
 
Syntax for IF...Else..IF Statement 
<script type="text/javascript">
var result= 20;
if( result> 18 ){
   document.write("<b>Result is greater than 18</b>");
} 
else if(result==18)
{ 
  document.write("<b>Result is equal to 18</b>"); 
} 
else
{
  document.write("<b>Result is less than 18</b>");

</script>

Friday 10 October 2014

Comments in Java Script

 There are single line comment and multiline comment in JavaScript

 <script type="text/javascript">
    // This is a single line comment in Javascript.

    /*
     This is a multiline comment in JavaScript    
     */

        var result = 10;
        document.write(result)
    </script>

Declare Variables in Javascript

Here you can see that we have declare a variable result and assign value to that.
 
<script type="text/javascript">
        var result = 10;
        document.write(result)
    </script>

Your first javascript program

Our First Program is to Print Hello Word

 <script type="text/javascript">
        document.write("Hello World!");

    </script>

When you run this program the result will be:

Hello World

Thursday 9 October 2014

Datatypes in C#

There are three types of data types in c#.
  1. Value Type
  2. Reference Type
  3. Pointer Type
Value Type:

The value types directly contain data. eg. int, char, float, which stores numbers, alphabets, floating point numbers, respectively. When you declare an type, the system allocates memory to store the value.

 int i=10;

Reference Type:

Object Type

The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. So object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.
object obj;
obj = 100; // this is boxing

Dynamic Type

You can have any type of value in the dynamic data type. Type checking place at run-time for these type of variables.
Syntax :
dynamic <variable_name> = value;
For example,
dynamic d1 = 200;
 
In object type type checking take place at compile time and in dynamic type checking
take place at runtime. 

String Type

The String Type you can have any string value. The string type is an alias for the System.String class.
For example,
string str="Test String";


Pointer Type: 

Pointer type variables store the memory address of another type. These are like C or C++.
pointer type is:
type* identifier;
For example,
char* cptr1;
int* iptr1;