Monday, December 30, 2013

How call wcf service by jquery and ajax?

step 1: first make the interface...

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.ServiceModel.Web;

[ServiceContract]

public interface IService

{

[OperationContract]

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]

string GetCustomers(string prefix);

[OperationContract]

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]

string GetCustomers1();

[OperationContract]

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]

string GetData();

}

step 2: second Make the Service...

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.Script.Serialization;

using System.ServiceModel.Activation;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class Service : IService

{

public string GetCustomers(string prefix)

{
List<object> customers = new List<object>();



using (SqlConnection conn = new SqlConnection())

{

conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlCommand cmd = new SqlCommand())

{

cmd.CommandText = "select FirstName+ ''+ CASE when LastName IS null then '' end as ContactName,CustomerId from tblcustomer Where " +

" email like @prefix + '%'";

cmd.Parameters.AddWithValue("@prefix", prefix);

cmd.Connection = conn;

conn.Open();

using (SqlDataReader sdr = cmd.ExecuteReader())

{

while (sdr.Read())

{

customers.Add(new

{

Id = sdr["CustomerId"],

Name = sdr["ContactName"]

});

}

}

conn.Close();

}

return (new JavaScriptSerializer().Serialize(customers));

}

}

public string GetData()

{

return "pppp";

}

public string GetCustomers1()

{
List<object> customers = new List<object>();



using (SqlConnection conn = new SqlConnection())

{

string prefix = "g";

conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlCommand cmd = new SqlCommand())

{

cmd.CommandText = "select FirstName+ ''+ CASE when LastName IS null then '' end as ContactName,CustomerId from tblcustomer Where " +

" email like @prefix + '%'";

cmd.Parameters.AddWithValue("@prefix", prefix);

cmd.Connection = conn;

conn.Open();

using (SqlDataReader sdr = cmd.ExecuteReader())

{

while (sdr.Read())

{

customers.Add(new

{

Id = sdr["CustomerId"],

Name = sdr["ContactName"]

});

}

}

conn.Close();

}

return (new JavaScriptSerializer().Serialize(customers));

}

}

}

step 3: change web.config
<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior name="ServiceBehavior1">

<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="true" />

</behavior>

</serviceBehaviors>

<endpointBehaviors>

<behavior name="ServiceAspNetAjaxBehavior1">

<enableWebScript />

</behavior>

</endpointBehaviors>

</behaviors>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

<services>

<service behaviorConfiguration="ServiceBehavior1" name="Service">

<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior1">

<identity>

<dns value="localhost" />

</identity>

</endpoint>

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

</service>

</services>

</system.serviceModel>


step 4:
Note: make the service and then deployment in iis and get url like http://localhost/webs
 

step 5: cal any where by ajax....



function LoadStatixText() {

var sId = 0;

$.ajax({

type: "GET",

contentType: "application/json; charset=utf-8",

url: "http://localhost/webs/services/service.svc/GetCustomers1",

data: '{}',

processData: false,

success: function (response){alert(response.d);},

failure: function (response) {

alert(2);

},

error: function (response) {

alert(response.d)

}

});

}

 


how to call webservice by javascript and scriptmanager?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="getservice.aspx.cs" Inherits="getservice" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<script language="javascript" type="text/javascript">

function SendRequest() {



Repw.LoadStatixText1(1, OnComplete, OnError,

OnTimeOut);

}

function OnComplete(arg) {



alert(arg);

}

function OnTimeOut(arg) {

alert("timeOut has occured");



}

function OnError(arg) {

alert("error has occured: " + arg._message);



}

</script>

</head>

<body onload="SendRequest();">

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server">

<Services>

<asp:ServiceReference Path="~/repw.asmx" />

</Services>

</asp:ScriptManager>







</form>

</body>

</html>

Sunday, December 29, 2013

webservice

[System.Web.Script.Services.ScriptService]
 add in webservice

In web.config

<webServices>
   <protocols>
    <add name="HttpGet" />
    <add name="HttpPost" />
   </protocols>
  </webServices>


=========
     <system.webServer>
    <handlers>
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        </handlers>
    </system.webServer>

Friday, December 20, 2013

dfdfdgfdgf

using System;

using System.Data;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Web.Services;

using System.Configuration;

using Business;

public partial class admin_vproduct : System.Web.UI.Page



{

private static int PageSize = 10;

protected void Page_Load(object sender, EventArgs e)



{

if (!IsPostBack)



{

BindDummyRow();

}

}

private void BindDummyRow()



{

DataTable dummy = new DataTable();

dummy.Columns.Add("ProductID");

dummy.Columns.Add("ProductCode");

dummy.Columns.Add("Isactive");

dummy.Columns.Add("del");

dummy.Columns.Add("Edt");



dummy.Rows.Add();

gvProducts.DataSource = dummy;

gvProducts.DataBind();

}

[WebMethod]

public static int ActiveProduct(int ProductId)



{

Product objproduct = new Product();

objproduct.ActiveInActiveProduct(Convert.ToInt32(ProductId));

return 1;



}

[WebMethod]

public static int DelProduct(int ProductId)



{

Product objproduct = new Product();

objproduct.DeleteProduct(Convert.ToInt32(ProductId));

return 1;



}

[WebMethod]

public static string GetProduct(int pageIndex)



{

string query = "[GetProducts_Pager]";

SqlCommand cmd = new SqlCommand(query);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@PageIndex", pageIndex);

cmd.Parameters.AddWithValue("@PageSize", PageSize);

cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;

return GetData(cmd, pageIndex).GetXml();



}

[WebMethod]

public static string GetProduct1(int pageIndex, string strSearch)



{

// string strSearch = "STV151";

string query = "[GetProducts_Pager_search]";

SqlCommand cmd = new SqlCommand(query);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@strSearch", strSearch);

cmd.Parameters.AddWithValue("@PageIndex", pageIndex);

cmd.Parameters.AddWithValue("@PageSize", PageSize);

cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;

return GetData(cmd, pageIndex).GetXml();



}

private static DataSet GetData(SqlCommand cmd, int pageIndex)



{

string strConnString = ConfigurationManager.ConnectionStrings["STVConnectionString"].ConnectionString;

using (SqlConnection con = new SqlConnection(strConnString))



{

using (SqlDataAdapter sda = new SqlDataAdapter())



{

cmd.Connection = con;

sda.SelectCommand = cmd;

using (DataSet ds = new DataSet())



{

sda.Fill(ds, "Products");

DataTable dt = new DataTable("Pager");

dt.Columns.Add("PageIndex");

dt.Columns.Add("PageSize");

dt.Columns.Add("RecordCount");



dt.Rows.Add();

dt.Rows[0]["PageIndex"] = pageIndex;

dt.Rows[0]["PageSize"] = PageSize;

dt.Rows[0]["RecordCount"] = cmd.Parameters["@RecordCount"].Value;



ds.Tables.Add(dt);

return ds;



 

}

}

}

}

public List<CountryInfo> CountryInformation { get; set; }

[WebMethod]

public List<CountryInfo> LoadCountry()



{

CountryInfo ci = new CountryInfo();

List<CountryInfo> CountryInformation = new List<CountryInfo>();

DataSet ds;

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["STVConnectionString"].ConnectionString))



{

using (SqlCommand cmd = new SqlCommand("select CategoryId ,CategoryName from tblCategoryDetail where CategoryId in (select categoryid from tblCategory where SubCategoryId=0)", con))



{

con.Open();

cmd.Connection = con;

cmd.CommandType = CommandType.Text;

using (SqlDataAdapter da = new SqlDataAdapter(cmd))



{

ds = new DataSet();



da.Fill(ds);

}

}

}

try



{

if (ds != null)



{

if (ds.Tables.Count > 0)



{

if (ds.Tables[0].Rows.Count > 0)



{

foreach (DataRow dr in ds.Tables[0].Rows)



{

CountryInformation.Add(new CountryInfo()



{

CategoryId = Convert.ToInt32(dr["CategoryId"]),

CategoryName = dr["CategoryName"].ToString()



});

}

}

}

}

}

catch (Exception ex)



{

throw ex;



}

return CountryInformation;



}

}

public class CountryInfo



{

public int CategoryId { get; set; }

public string CategoryName { get; set; }



}