Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for the ‘WCF Services’ Category

Using BackgroundWorker with WPF

Posted by Viral Sarvaiya on March 26, 2012


When one process take so much long time and UI thread needs to stay responsive while process is running, the most common method to place a long running process on a separate thread.

In WPF there are mostly use technique is  Backgroundworker. Backgroundworker is mostly use in multithreading applications.

Here I show a small example of backgroundworker.

In WPF application I call WCF service function directly not asynchronies, so that function take time get response and at that time user can’t see what happen. so we have to integrate busyindicater while service call.

Busyindicater comes with WPF extended toolkit.

private void OKButton_Click(object sender, RoutedEventArgs e)
{
MyService myservice = new MyService();
MyServiceResponse Myserviceresponce = new MyServiceResponse();
Myserviceresponce = myservice.CallMyFunction(int Para1, string para2);
}

here when user click to OK Button, CallMyFunction() take so much long time and end user confuse what to do at that time and he/she click more than one time to that button and application will crashed.

so we put busy indicator in our code and calling this function asynchronies with backgroundworker.

<extToolkit:BusyIndicator x:Name="_busyIndicator" >
<Grid>
....
</Grid>
</extToolkit:BusyIndicator>

and in CS page

private void OKButton_Click(object sender, RoutedEventArgs e)
{
_busyIndicator.IsBusy = true;

MyServiceResponse Myserviceresponce = new MyServiceResponse();

BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerAsync();

//this is where the long running process should go
worker.DoWork += (o, ea) =>
{
MyService myservice = new MyService();
Myserviceresponce = myservice.CallMyFunction(int Para1, string para2);
};

worker.RunWorkerCompleted += (o, ea) =>
{
_busyIndicator.IsBusy = false;

//Continue other statment of this function...
};
}

So this will display busyindicator while service call complete.
Hope this will helps you.
Thanks.

Advertisements

Posted in .Net, Visual Studio, WCF Services, WPF | Tagged: , , , , , , , , | 2 Comments »

The “CreateRiaClientFilesTask” task failed unexpectedly

Posted by Viral Sarvaiya on February 14, 2012


Some day ago, when i build my project i get unexpected error.

Error 3 The “CreateRiaClientFilesTask” task failed unexpectedly.
System.Web.HttpException (0x80004005): Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.Configuration.ConfigurationErrorsException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied. —> System.IO.FileLoadException: Could not load file or assembly ‘FileHelpers.DataLink’ or one of its dependencies. Access is denied……….

Sometime that happen when Visual studio cannot access files. so have to remove Temporary file.

I get simple solution from goggling, just close visual studio and reopen, and if Visual studio has no administrator rights then please right click to visual studio icon and choose “Run as a Administrator”.

Then re-build project and problem solved.

Thanks.

Posted in .Net, ASP.NET, RIA WCF, Silverlight, Visual Studio, WCF Services, WPF | Tagged: , , , , , | 4 Comments »

Calling a WCF service from Javascript

Posted by Viral Sarvaiya on May 16, 2011


Hi

we know how to use WCF service in silverlight and asp.net that shows in my some previous posts

https://viralsarvaiya.wordpress.com/2010/09/17/bind-silverlight-grid-view-with-wcf-service/

https://viralsarvaiya.wordpress.com/2010/08/26/use-of-wcf-service-in-silverlight/

but i face another problem in it, it can possible to call WCF service from javascipt?

Answer is yes  and i find interesting post.

for more detail click here.

thanks and enjoy…

Posted in .Net, ASP.NET, RIA WCF, Silverlight, WCF Services | Tagged: , , , , , , , | Leave a Comment »

Bind Silverlight Grid view with WCF Service

Posted by Viral Sarvaiya on September 17, 2010


Hello friends….

Here I demonstrate how to bind the grid view of the Silverlight with WCF Service.

You already know what is the Silverlight and WCF. My one post that demonstrate the use of the WCF Service with Silverlight, for more info about that check https://viralsarvaiya.wordpress.com/2010/08/26/use-of-wcf-service-in-silverlight/

Setp 1 : Create New Silverlight Project( here I give name of the project is “SilverlightGridTest”)

In the Visual Studio 2008 or 2010, file menu -> New -> project.

Select Silverlight application, give name as SilverlightGridTest and open the project.

Then check the checkbox true of the host the Silverlight application in web site.

Now you have 2 project in the solution.

Step 2: Database information

CREATE TABLE person (

Name VARCHAR(256),

Phone VARCHAR(50),

City VARCHAR(50)

)

make one procedure named “GetAllPersonInfo” and write the following Statement in the procedure

Select *from person order by name;

Step 3: Create WCF Service

Right click to SilverlightGridTest.web project, select add -> new item.

Choose Silverlight in left panel and choose Silverlight-enable WCF Service. Then give name “DataService.svc”

So Service has been added to project.

Here we have interface IDataService.cs and DataService will implements that so in our IDataService.cs code is as below.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace SilverlightGridTest.Web

{

[ServiceContract]

public interface IDataService

{

[OperationContract]

PersonDetails GetPersonDetails();

}

[DataContract]

public class PersonDetails

{

List<Personinfo> _PersonList = new List<Personinfo>();

[DataMember]

public List<Personinfo> PersonIndex

{

get { return _PersonList; }

set { _PersonList = value; }

}

}

[DataContract]

public class Personinfo

{

[DataMember]

public string Name { get; set; }

[DataMember]

public string Phone { get; set; }

[DataMember]

public string City { get; set; }

}

}

In the “DataService.svc.cs” file write the following.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.Data;

namespace SilverlightGridTest.Web

{

public class DataService : IDataService

{

public PersonDetails GetPersonDetails()

{

DatabaseHandler dbObj = new DatabaseHandler();

DataTable dataTablePersonInfo = dbObj.GetPersonInfo();

PersonDetails PersonDataMessage = new PersonDetails();

for (int iTagCounter = 0; iTagCounter < dataTablePersonInfo.Rows.Count; iTagCounter++)

{

Personinfo PersonInfo = new Personinfo();

PersonInfo.Name = dataTablePersonInfo.Rows[iTagCounter]["Name"].ToString();

PersonInfo.Phone = dataTablePersonInfo.Rows[iTagCounter]["Phone"].ToString();

PersonInfo.City = dataTablePersonInfo.Rows[iTagCounter]["City"].ToString();

PersonDataMessage.PersonIndex.Add(PersonInfo);

}

return PersonDataMessage;

}

}

}

Now add the new class name “DatabaseHandler.cs” for the operation on the database. Means this function will get the data from the database.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Collections.ObjectModel;

namespace SilverlightGridTest.Web

{

public class DatabaseHandler

{

private string _gConnectionString = ConfigurationManager.ConnectionStrings["Database"].ToString();

public DataTable GetPersonInfo()

{

SqlConnection sqlConnect = new SqlConnection(_gConnectionString);

sqlConnect.Open();

DataTable dbTbl = new DataTable();

//Get data

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "GetAllPersonInfo";

cmd.Connection = sqlConnect;

cmd.CommandType = CommandType.StoredProcedure;

SqlDataAdapter oAdapter = new SqlDataAdapter(cmd);

oAdapter.Fill(dbTbl);

sqlConnect.Close();

return dbTbl;

}

}

}

Step 4: Web.Config Settings

Database Connection string


<connectionStrings>

<add connectionString="packet size=4096;server=ServerName;persist security info=False;database=DatabaseName;uid=UserName;pwd=Password;" />

</connectionStrings>

Service Settings


<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior>

<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="false" />

</behavior>

</serviceBehaviors>

</behaviors>

<bindings>

<customBinding>

<binding>

<binaryMessageEncoding />

<httpTransport />

</binding>

</customBinding>

</bindings>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

<services>

<service behaviorConfiguration="SilverlightGridTest.Web.TestServiceBehavior" name="SilverlightGridTest.Web.DataService">

<endpoint address="" binding="basicHttpBinding" contract="SilverlightGridTest.Web.IDataService" />

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

</service>

</services>

</system.serviceModel>

Step 5: Add clientaccesspolicy.xml and crossDomain.xml file.

This will complete the coding in the SilverlightGridTest.Web .

Build the application.

Now move to SilverlightGridTest.

Add the service reference and add the service which we develop above.

Step 6: Mainpage.xaml file.

Now in the Mainpage.xaml file put the grid control.


<UserControl x:Class="SilverlightGridTest.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"

xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Left" VerticalAlignment="Top">

<sdk:DataGrid x:Name="AllPerson" GridLinesVisibility="All" AutoGenerateColumns="False" >

<sdk:DataGrid.Columns>

<sdk:DataGridTextColumn Binding="{Binding Name}" CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="Name" />

<sdk:DataGridTextColumn  Binding="{Binding Phone}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="Phone"/>

<sdk:DataGridTextColumn  Binding="{Binding City}" CanUserReorder="True" CanUserResize="True" CanUserSort="True"  Header="City"/>

</sdk:DataGrid.Columns>

</sdk:DataGrid>

</Grid>

</UserControl>

Step 7 : Mainpage.xaml.cs file

Make the object of the service client, coding as follow.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using SilverlightGridTest.DataService;

namespace SilverlightGridTest

{

public partial class MainPage : UserControl

{

public DataServiceClient objDataService;

public MainPage()

{

InitializeComponent();

objDataService = new DataServiceClient();

objDataService.GetPersonDetailsCompleted += new EventHandler<GetPersonDetailsCompletedEventArgs>(objDataService_GetPersonDetailsCompleted);

objDataService.GetPersonDetailsAsync();

}

void objDataService_GetPersonDetailsCompleted(object sender, GetPersonDetailsCompletedEventArgs e)

{

AllPerson.ItemsSource = e.Result.PersonIndex;

}

}

}

Step 8: Run the application.

You will get the data will display in the grid as below

Enjoy coding…..

Posted in ASP.NET, RIA WCF, Silverlight, WCF Services | Tagged: , , , , , , , , , , , , | 14 Comments »

Use of WCF Service in Silverlight

Posted by Viral Sarvaiya on August 26, 2010


hello friends….

what is WCF? see the link – https://viralsarvaiya.wordpress.com/2009/11/18/windows-communication-foundation/

Here i demonstrate the use of the WCF Service in silverlight.

what is WCF so refer this

please confirm that silverlight 3 or 4 and silverlight tool kit is installed in your PC.

Step 1: Create New Silverlight Project.

In Visual Studio2008 or 2010, file menu -> New -> project.

Select Silverlight application, give name of project as “SilverlightTesingService” and open the project.

then check the checkbox true of the host the silverlight application in web site.

Now you have 2 projects in your soluion.

Step 2 : Create Wcf Service

Right click to SilverlightTesingService.web project, select add -> new item

choose silverlight in left panel and choose Silverlight-enable WCF Service. then give name “TestService.svc”.

so Service has been added to project

in the TestService.svc.cs file write the following


using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;

namespace SilverlightTesingService.Web
{
 [ServiceContract(Namespace = "")]
 interface IService1
 {
 [OperationContract]
 Users GetUsers(int id);
 }

 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 public class TestService : IService1
 {
 #region IService1 Members

 Users IService1.GetUsers(int id)
 {
 if (id == 1)
 return new Users() { IsMember = true, Name = "Viral", age = 27 };
 else if (id == 2)
 return new Users() { IsMember = true, Name = "Malhar", age = 24 };
 else
 return new Users() { IsMember = false, Name = "There is no user there", age = 0 };
 }

 #endregion
 }

 public class Users
 {
 public bool IsMember { get; set; }
 public string Name { get; set; }
 public int age { get; set; }
 }
}

Step 3 : clientaccesspolicy.xml File

Now for the allowing cross domain access we have to put the clientaccesspolicy.xml file to the SilverlightTesingService.web folder.

For more information of this file click to http://msdn.microsoft.com/en-us/library/cc197955%28VS.95%29.aspx

clientaccesspolicy.xml as below


<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
 <cross-domain-access>
 <policy>
 <allow-from http-request-headers="*">
 <domain uri="*"/>
 </allow-from>
 <grant-to>
 <resource path="/" include-subpaths="true"/>
 </grant-to>
 </policy>
 </cross-domain-access>
</access-policy>

Step 4: Web.config file change

Now we have to consider that web.config file have defined end point

put this in between  configuration tag


<system.serviceModel>
 <behaviors>
 <serviceBehaviors>
 <behavior name="SilverlightTesingService.Web.TestServiceBehavior">
 <serviceMetadata httpGetEnabled="true" />
 <serviceDebug includeExceptionDetailInFaults="false" />
 </behavior>
 </serviceBehaviors>
 </behaviors>
 <bindings>
 <customBinding>
 <binding name="customBinding0">
 <binaryMessageEncoding />
 <httpTransport />
 </binding>
 </customBinding>
 </bindings>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
 <services>
 <service behaviorConfiguration="SilverlightTesingService.Web.TestServiceBehavior" name="SilverlightTesingService.Web.TestService">
 <endpoint address="" binding="basicHttpBinding" contract="SilverlightTesingService.Web.IService1" />
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
 </service>
 </services>
 </system.serviceModel>

Step 5 : Add Service to Silverlight Application

To add the service you require first build the SilverlightTesingService.web project.

Now in the SilverlightTesingService project

right click to project -> add the Service References

New dialog box open . click to discover button. and select the TestService.svc

and give name of the service and click ok.

Service Reference folder has been added and the service has been added to this folder.

Step 6: Use of the WCF Service

in the mainpage.xaml take 2 textbox and 1 button as follow


<UserControl x:Class="SilverlightTesingService.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
 <Grid x:Name="LayoutRoot">
 <TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
 <TextBox Height="23" HorizontalAlignment="Left" Margin="12,86,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
 <Button Content="Button" Height="23" HorizontalAlignment="Left" Click="button1_Click" Margin="12,49,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
 </Grid>
</UserControl>

now in mainpage.xaml.cs file make the object of the service client.

after that make the completed event when that service call that function will call

and last when this service call is written

see the mainpage.xaml.cs file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightTesingService
{
 public partial class MainPage : UserControl
 {
 TestService.Service1Client ObjClient; //make the object of the service
 public MainPage()
 {
 InitializeComponent();
 ObjClient = new SilverlightTesingService.TestService.Service1Client();  //mamory allocation of the service object
 ObjClient.GetUsersCompleted += new EventHandler<SilverlightTesingService.TestService.GetUsersCompletedEventArgs>(ObjClient_GetUsersCompleted);  //make the completed event of the service
 }

 void ObjClient_GetUsersCompleted(object sender, SilverlightTesingService.TestService.GetUsersCompletedEventArgs e)
 {
 textBox2.Text = e.Result.Name.ToString();
 }

 protected void button1_Click(object sender, EventArgs e)
 {
 ObjClient.GetUsersAsync(Convert.ToInt32(textBox1.Text)); // calling the service's function with the parameter
 }
 }
}

Step 7 : Run the application

when you add integer 1 in the first textbox and click to button the service will call……

Enjoy the WCF service……

Posted in ASP.NET, RIA WCF, WCF Services | Tagged: , , , , , , , , | 4 Comments »

 
%d bloggers like this: