Friday, February 4, 2011

Create WCF Service Library ,Host and Consume in Silverlight Application

Step 1 ). First Create Blank Solution in VS.Net 2008

Step 2). Then right click on solution WcfLinq in Solution Explorer ,in context menu select
Add -> New Project , New Project window will open in that select WCF as project type and
In template Wcf Service Library ,Name it MyWcfServiceLibrary

Step 3). It will create two .cs , one for interface IService.cs and second is Service.cs.
Rename both files “(IServiceTest.cs and ServiceTest.cs respectively) “or leave as it is.
In IServiceTest.cs file code replace with below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace MyWcfServiceLibrary
{
// NOTE: If you change the interface name "ITestService" here, you must also update the reference to "ITestService" in App.config.
[ServiceContract]
public interface ITestService
{
[OperationContract]
string GetData();

// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations
}
In ServiceTest.cs file code replace with below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace MyWcfServiceLibrary
{
// NOTE: If you change the class name "TestService" here, you must also update the reference to "TestService" in App.config.
public class TestService : ITestService
{
public string GetData()
{
return string.Format("You entered: {0}", "Helloworld");
}
}
}
Step 4 ). In App.config file replace wsHttBinding with basicHttpBinding
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service behaviorConfiguration="MyWcfServiceLibrary.TestServiceBehavior"
name="MyWcfServiceLibrary.TestService">
<endpoint address="" binding="basicHttpBinding" contract="MyWcfServiceLibrary.ITestService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8731/Design_Time_Addresses/MyWcfServiceLibrary/TestService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyWcfServiceLibrary.TestServiceBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Now Press F5 for Test Wcf service with Wcf Test Client

Note : For testing wcf service with wcf test client, you have to run vs.net as administrator.
Step 5). Now add New silverlight Application in WcfLinq Solutin. Name it SilverlighTestApp.

You can see in solution explorer , it created two project one is SilverlightTestApp with Mainpage.Xaml and second is SilverlightTestApp.web with two test page .
SilverlightTestApp.Web is hosting our Wcf Service.
Step 6). Add reference of MyWcfServiceLibrary to SilvertlightApp.web

Step 7). Step 8). For create .svc file in silverlightTestApp.web ,right click on it select Add->New Item .
Select Text file template and replace its Name with MyService.svc.

Add this code to MyService.Svc without double quot
“<%@ServiceHost Language="C#" Debug="true" Service="MyWcfServiceLibrary.TestService" %>"
Add below code to Web.config file
<system.serviceModel>
<services>
<service name ="MyWcfServiceLibrary.TestService"
behaviorConfiguration="MyWcfServiceLibrary.TestServiceBehavior">
<endpoint address =""
binding ="basicHttpBinding"
contract ="MyWcfServiceLibrary.ITestService" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyWcfServiceLibrary.TestServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Now set SilverlightTestAPP.web as startup project and MyService.Svc as Startp page then press F5 for testing service run or not. Service is runing then you can see the output page as below


Step 8). Add service referance in SilverlightTestApp project by right click on SilverlightTestApp , select add service referance. Add referance of MyService.svc .

It will create ServiceReferences.ClientConfig file ,it looks like
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITestService" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647">
<security mode="None">
<transport>
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:49403/MyService.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ITestService" contract="ServiceRef.ITestService"
name="BasicHttpBinding_ITestService" />
</client>
</system.serviceModel>
</configuration>


Step 9). Add one textbox to Mainpage.xaml.

<Grid x:Name="LayoutRoot">
<TextBox x:Name="txtDisplay" Height="25" Width="200"></TextBox>
</Grid>

Write below code in Mainpage.xmal.cs for receive data from Service.
using SilverlightTestApp.ServiceRef;
namespace SilverlightTestApp
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
TestServiceClient tc = new TestServiceClient();
tc.GetDataCompleted +=new EventHandler(tc_GetDataCompleted);
tc.GetDataAsync();
}
void tc_GetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
txtDisplay.Text = e.Result;
}
}
}
Set SilverlightTestAppTestPage.aspx as startup page and press F5.





Tuesday, July 21, 2009

Compact and Repair Access database

Compact and Repair Access database

step 1 : Add reference of dll

"\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\dao.dll"

Step 2 : In Button Click event write following code

Try
Dim File_Path, compact_file As String
'Original file path that u want to compact
Dim str As String = ConfigurationSettings.AppSettings("dbname")
Dim _connection_string As String = System.Windows.Forms.Application.StartupPath() & "" & str

File_Path = _connection_string
'compact file path, a temp file
compact_file = AppDomain.CurrentDomain.BaseDirectory & "db1.mdb"
'First check the file u want to compact exists or not
If File.Exists(File_Path) Then
Dim db As New dao.DBEngine()
'CompactDatabase has two parameters, creates a copy of
'compact DB at the Destination path
db.CompactDatabase(File_Path, compact_file)
End If
'restore the original file from the compacted file
If File.Exists(compact_file) Then
File.Delete(File_Path)
File.Move(compact_file, File_Path)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try



File_path = " Main Database path"

Compact_file="Temp Database path for compact"

Wednesday, July 8, 2009

How to display combobox item or Join all combobox item with comma separate in single variable
With combobox1.Items
.Add("T1")
.Add("T2")
.Add("T3")
.Add("T4")
.Add("T5")
End With
Dim str As String
str = ""
For Each obj As Object In combobox1.Items
MsgBox(obj(0).ToString)
str = str & obj(0) & ","
Next
str = Mid(str, 1, str.Length - 1)

Saturday, February 28, 2009

CascadingDropDown Method error 500 Solution

I got same error for fill DropDownlist using CascadingDropDown ajax control and web service.

I tried to solve this problem and i got the solution which i share with my friends.


I got the error because of two things

First I did not add attribute.

Second I wrote wrong logic.



Solution

• Add attribute
[System.Web.Script.Services.ScriptService]
. Check your logic in web method

Fill Dropdown list using CascadingDropDown Ajax Control and Web Service


I am taking example of fill dropdown list for state using CascadingDropDown and Web service.

  1. Web Service

When we create web service its code file which is located in App_Code folder looks like.

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

‘WebService(Namespace:="http://tempuri.org/")’_

‘WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)’ _

‘Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()’ _

Public Class stateServices

Inherits System.Web.Services.WebService

‘WebMethod()’ _

Public Function HelloWorld() As String

Return "Hello World"

End Function

End Class

Import some other namespace listed below

Imports AjaxControlToolkit

Imports System.Data

Imports System.Collections

Imports System.Collections.Generic

Imports System.Collections.Specialized

After this add one more attribute abow to Class stateServices

System.Web.Script.Services.ScriptService()

Now I am going to create webmothod which return array of type CascadingDropDownNameValue() for fill up drop down list with state name.

‘WebMethod()’ _

Public Function GetState(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()

Dim tempTableAs New DataTable

With tempTable

.Columns.Add("id", GetType(String))

.Columns.Add("state_name", GetType(String))

End With

Dim drow As DataRow

drow = tempTable.NewRow()

drow("id") = "1"

drow("state_name") = "Gujarat"

tempTable.Rows.Add(drow)

drow = tempTable.NewRow()

drow("id") = "2"

drow("state_name") = "Maharastra"

tempTable.Rows.Add(drow)

drow = tempTable.NewRow()

drow("id") = "3"

drow("state_name") = "Rajastan"

tempTable.Rows.Add(drow)

Dim values As New List(Of CascadingDropDownNameValue)

For Each dr As DataRow In tempTable.Rows

values.Add(New CascadingDropDownNameValue(dr("state_name"), dr("id")))

Next

Return values.ToArray()

End Function

After finished all work our webservice file look like

For Vb.net

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports AjaxControlToolkit

Imports System.Data

Imports System.Collections

Imports System.Collections.Generic

Imports System.Collections.Specialized

‘WebService(Namespace:="http://tempuri.org/")’ _

‘WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)’ _

‘Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()’ _

‘System.Web.Script.Services.ScriptService()’ _

Public Class stateServices

Inherits System.Web.Services.WebService

‘WebMethod()’ _

Public Function GetState(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()

Dim tempTableAs New DataTable

With tempTable

.Columns.Add("id", GetType(String))

.Columns.Add("state_name", GetType(String))

End With

Dim drow As DataRow

drow = tempTable.NewRow()

drow("id") = "1"

drow("state_name") = "Gujarat"

tempTable.Rows.Add(drow)

drow = tempTable.NewRow()

drow("id") = "2"

drow("state_name") = "Maharastra"

tempTable.Rows.Add(drow)

drow = tempTable.NewRow()

drow("id") = "3"

drow("state_name") = "Rajastan"

tempTable.Rows.Add(drow)

Dim values As New List(Of CascadingDropDownNameValue)

For Each dr As DataRow In tempTable.Rows

values.Add(New CascadingDropDownNameValue(dr("state_name"), dr("id")))

Next

Return values.ToArray()

End Function

End Class

For C#

using System;

using System.Web;

using System.Collections;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Web.Services;

using System.Web.Services.Protocols;

using AjaxControlToolkit;

using System.Data;

using System.Data.SqlClient;

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

public class stateServices : System.Web.Services.WebService {

public stateServices () {

//Uncomment the following line if using designed components

//InitializeComponent();

}

[WebMethod]

public CascadingDropDownNameValue[] GetState(string knownCategoryValues, string category)

{

DataTable tempTable=new DataTable();

tempTable.Columns.Add("id", typeof(string));

tempTable.Columns.Add("state_name", typeof(string));

DataRow drow;

drow = tempTable.NewRow();

drow["id"] = "1";

drow["state_name"] = "Gujarat";

tempTable.Rows.Add(drow);

drow = tempTable.NewRow();

drow["id"] = "1";

drow["state_name"] = " Maharastra";

tempTable.Rows.Add(drow);

drow = tempTable.NewRow();

drow["id"] = "1";

drow["state_name"] = " Rajastan";

tempTable.Rows.Add(drow);

List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();

foreach (DataRow dr in tempTable.Rows)

{

values.Add(new CascadingDropDownNameValue (string)dr["state_name"], (string)dr["id"]));

}

return values.ToArray();

}

  1. web Form

Add ScriptManager.

Add Dropdownlist rename it with ddstate.

Add CascadingDropDown Ajax Control rename it with cddstate.

Set TargetControlID Property of cddstate to ddstate

Set cddstate(CascadingDropDownproperty) properties for ddstate in its property window

BehaviorID property to cddstate

Category property to State

LoadingText property to Please wait ...........

PromptText property to Select State ............

ServiceMethod property to GetState

ServicePath property to stateServices.asmx

Start debugging application.

I use ‘ quote for attribute which is highlighted to use code replace starting quote with

'Greate then sign' and ending quote with 'Less then sign'