Wednesday, September 22, 2010

Call Web services From Javascript in ASP.NET

There is two ways to call web services in your web site using java-script(j Query).

I am writing an example for both:--

This is First Method :Need to include j Query Library file
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function()
{
/*First Method to retriving data*/
$.ajax({
type: "POST",
url: "EmployeeService.asmx/GetEmployeeList",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(list) {
$("#Something").append("<ul id='bullets'></ul>");
for (i = 0; i < list.d.length; i++) {
$("#bullets").append("<li>" + list.d[i].Title + " : " + list.d[i].FirstName + " : " + list.d[i].LastName + " : " + list.d[i].BirthDate + "</li>");
}
},
error: function(e) {
$("#Something").html("There is an error retriving records 1");
}
});
</script>

This is Second Method :-
Need to include j Query Library file
And jmsajax.js File
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"/>
<script src="Scripts/jquery.jmsajax.js" type="text/javascript"/>


<script type="text/javascript">
/*Second Method to retriving data*/
$.jmsajax({
url: "EmployeeService.asmx",
method: "GetEmployeeList",
dataType: "msjson",
success: function(list) {
$("#Something").append("<ul id='bullets'></ul>");
for (i = 0; i < list.length; i++) {
$("#bullets").append("<li>" + list[i].FirstName + " : " + list[i].LastName + " : " + list[i].BirthDate + "</li>");
}
},
error: function(e) {
$("#Something").html("There was an error retreiving records 2");
}
});


});
</script>

Common Content For Both Methods
This is common body content Need to place in your body section

<body>
<form id="form1" runat="server">
<div id="Something">
</div>
</form>
</body>

This is Web service must be in your project..

This is Webservice page (EmployeeService.asmx)

<%@ WebService Language="C#" CodeBehind="~/App_Code/EmployeeService.cs" Class="EmployeeService" %>

And in the Code file you need to create your own code for ex:-

I am coping the entire code file here

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;

///
/// Summary description for EmployeeService
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class EmployeeService : System.Web.Services.WebService {

public EmployeeService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}


[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
[System.Web.Services.WebMethod]
public List GetEmployeeList()
{
string Con = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
var empList = new List();
using (SqlConnection Sqlcon = new SqlConnection(Con))
{
Sqlcon.Open();

string Sql = "Select top 5 Title,FirstName,LastName,BirthDate from tblEmployee";
using (SqlCommand Sqlcmd = new SqlCommand(Sql, Sqlcon))
{
SqlDataReader Sqldr = Sqlcmd.ExecuteReader(CommandBehavior.CloseConnection);
if (Sqldr != null)
{
while (Sqldr.Read())
{
var emp = new Employee
{
Title = Sqldr.GetString(0),
FirstName = Sqldr.GetString(1),
LastName = Sqldr[2].ToString(),
BirthDate = Sqldr.GetDateTime(3)
};
empList.Add(emp);
}
}
return empList;
}
}
}

public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public DateTime BirthDate { get; set; }
}
}

Get the Control ID that Raised PostBack in CodeBehind file of ASP.Net

Control c = GetPostBackControl(Page);
if ((c != null))
{
if (c.ID.ToString() == "grdTemplate" || c.ID.ToString() == "btnAddTemplate")
{
// Do code whatever you want to action while clicked this button.
}
}

////////////////////////Method to get the Postback button Id///////////////
private Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;

string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if ((ctrlname != null) & ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break; // TODO: might not be correct. Was : Exit For
}
}
}
return control;
}


For More Information Click Me

Tuesday, September 14, 2010

Show client side alert message from server side code even when update panel is used

Developers might want to display client side message with information from server side to their users when they have completed some execution at server side. People may try in different way for this purpose.

For example:
Response.Write() method with JavaScript code inside the method:

string mes = "Hello Dhaka";
Response.Write("< script language=”javascript” type=”text/javascript”>alert(’” + mes + “‘);</script>");

or ClientScript.RegisterStartupScript() method:

string message = "";
if (!ClientScript.IsStartupScriptRegistered("mes"))
{
ClientScript.RegisterStartupScript(this.GetType(), "mes", message);
}

But these code doesn't work when you use update panel in your page. So better solution is to use ScriptManager.RegisterStartupScript() method. This works whether update panel is used or not. So let's see the code snippet below:

string message = string.IsNullOrEmpty(TextBox1.Text) ? "Please give a text to textbox." : "You have given: " + TextBox1.Text.Trim();
string script = "";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "AlertMessage", script, false);


OR


System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append(@"<script language='javascript'>");

sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");

sb.Append(@"lbl.style.color='red';");

sb.Append(@"</script>");


if (!ClientScript.IsStartupScriptRegistered("JSScript"))

{

ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());

}





With this code snippet you can display a modal message that their data was saved or updated successfully or not.

Monday, July 26, 2010

Find all The User Defined Procedures in Sql

There is two ways to get the result:-
1. Using Comination of System define Procedure table and Schema table

Select * From sys.procedures As P
Inner Join sys.schemas As S On S.schema_id = P.schema_id
Where P.type = 'P' And is_ms_shipped = 0 And P.name Not Like 'Sp[_]%diagram%'

2. Using System define Object table
Select * From sys.objects
Where type = 'P' And is_ms_shipped=0 And name Not Like 'Sp_%diagram%'


Note:- is_ms_shipped Equals Zreo Means Show all the User defined events

Tuesday, July 20, 2010

Validate number in textbox using Javascript

function fnSubmit(){
var str = "ab126";
var ValidStr = "0123456789.";
var flag;
for(var i=0;i if(ValidStr.indexOf(str.charAt(i)) > 0)
flag = true;
else
flag = false;
}
}

Tuesday, June 22, 2010

Copy Entire Folder from one location to another in .Net

Copying the entire file under the folder there is two ways
1. Using component
2. Using Programatically

=======================================================================================
1) Add this line of code and pass your source folder path and destination folder path, then this component will copying all the files from source to desc.

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);


2. Via Programatically

first you need to add namesapce System.IO on the top of the page


protected void Page_Load(object sender, EventArgs e)
{
DirectoryInfo SourceLoc = new DirectoryInfo(@"D:\Projects\SitePages\common");
DirectoryInfo TargetLoc = new DirectoryInfo(@"D:\Projects\Production\common");

CopyAllFiles(SourceLoc, TargetLoc);
}

///
/// Copy All files from the source directory into the target directory
///

///
///
public void CopyAllFiles(DirectoryInfo Source, DirectoryInfo target)
{
//Validate the existance of the target dir, if fail then create the dir
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}

//Copy individual file into the new directory
foreach (FileInfo file in Source.GetFiles())
{
file.CopyTo(Path.Combine(target.ToString(), file.Name), true);
}

//Recursion loop to copy each sub directory
foreach (DirectoryInfo diSource in Source.GetDirectories())
{
DirectoryInfo nexttarget = target.CreateSubdirectory(diSource.Name);
CopyAllFiles(diSource, nexttarget);
}
}

Sunday, June 20, 2010

Create Constraints/Delete Foreign Key linked record

Suppose you want to delete the one record that is associate/linked to some other table with foreign key reference then we need to set/alter cascade command on the table then it will delete/update the record which is associated to the same table/column


For Reference:-

1. Create One Table Called tblFirst With Primary Key
2. Create another table called tblSecond with foreign key.make sure your column key column doesn't contain any identity
3. While creating the foreign key you need to set the cascade. This cascade word delete/update the all records that linked to the same row.


Create table tblFirst(Id Int Identity(1,1) Primary Key, Name varchar(50))


Create table tblSecond(Id Int Primary Key, Phone varchar(50), Foreign Key (ID) References tblFirst(Id) On Delete Cascade On Update Cascade)

INsert into tblFirst(Name) values('Murli')
INsert into tblFirst(Name) values('Anup')

INsert into tblSecond(Id,Phone) values(1,'9323399705')
INsert into tblSecond(Id,Phone) values(2,'9000000000')

Delete From tblFirst Where Id = 1