Search

Showing posts with label Imran Bhadelia. Show all posts
Showing posts with label Imran Bhadelia. Show all posts

Nov 27, 2013

Exposing property as OperationContract in WCF

Hello All,

I would like to share thing which I just learn today J

In WCF usually we work with operation contract i.e. methods. I was trying to expose property not a method. I found solution and here is the way it should be

Simple Service Contract

clip_image001

Contract Implementation

clip_image002

Nothing fancy, and here is client to call this service and its output

clip_image003

So before we go further, I would like to make you clear about what we are going to do.. So requirement is I don’t want to change DoWork signature, but still want to add some additional information which DoWork should use if available, means a kind of optional parameter I would like to add.

For that I need to add property and get it exposed into client. So my new service contract will something similar as bellow

clip_image004

You can see, one new property Message added with only set, as I want to be as one-way. To Expose property you have to write OperationContract attribute ot get or set not on top of member just we do with method.

Now change little bit in logic to use Message if it’s there if not then behave normally.

clip_image005

After updating reference, I can see WCF internally convert my Message property into method by adding set_ prefix.

clip_image006

Let’s set message and will call my work method again.

clip_image007

Demm it, doesn’t work! It’s fairly simple and straightforward!!! Where is the issue? @#$%$@@#$

In debug I can see message is set property to my private variable…

clip_image008

but when I call DoWork I don’t see value is persist!

clip_image009

Its WCF setting that we are missing, WCF by default does not keep context for ever… we have to tell them to keep it alive per session, per call (default) or single. Per session requires some more extra efforts to get it working… let’s keep simple by using Single, it’s part of service behavior, lets add and see if that works…

Add attribute…

clip_image010

And let’s make call from client again..

clip_image011

Yes… we got it working J now as we make context mode to single, subsequent call of DoWork will return same result. That means its consider as a kind of Static

clip_image012

If we switch context mode to session then following code will behaves as expected

clip_image013

Hope this helps.

Sep 20, 2012

Operation is not valid due to the current state of the object

Hello All,

While working with web application, there may be case we got ‘Operation is not valid due to the current state of the object error’ or ‘The URL-encoded form data is not valid’ while doing postback

There may be other reason but one of the reason is form collection reaches its limit of maximum number of keys that it can hold a time. Means you have huge amount of data and you are trying to postback that data to server which end up with this error

Operation is not valid due to the current state of the object error’ or ‘The URL-encoded form data is not valid

Microsoft has added this as security for Form can have 1000 items at a time, however thanks Microsoft also provides way to change this Smile

To change this add following setting into your configuration file

<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="10000" />
</appSettings>

In case you have issue with Jason data then you have to add following settings

<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="10000" /></appSettings>

Hope this helps

Jun 27, 2012

Deleting Parent and its child record without setting ON CASCADE DELETE

Hello All,

Very recent I found requirement for removing parent record which is having tons of relation as they have foreign key constrains; you can’t delete them unless you have ON CASCADE DELETE

I found solution on Stack Overflow and base main article from sqlteam. I have modified procedure to fix some minor issue and here is the procedure which take table name and a query to filter row which we need to delete from table along with its reference.

-- ================================================
-- Expects the name of a table, and a conditional for selecting rows
-- within that table that you want deleted.
-- Produces SQL that, when run, deletes all table rows referencing the ones
-- you initially selected, cascading into any number of tables,
-- without the need for "ON DELETE CASCADE".
-- Does not appear to work with self-referencing tables, but it will
-- delete everything beneath them.
-- To make it easy on the server, put a "GO" statement between each line.
-- ================================================
CREATE PROCEDURE DeleteCascade (
@BaseTableName VARCHAR(200)
,@BaseCriteria VARCHAR(1000)
)
AS BEGIN

DECLARE @ToDelete TABLE
(
Id INT IDENTITY(1, 1) PRIMARY KEY NOT NULL,
Criteria VARCHAR(5000) NOT NULL,
TableName VARCHAR(200) NOT NULL,
Processed BIT NOT NULL,
DeleteSql VARCHAR(5000)
)

SET NOCOUNT ON

INSERT INTO @ToDelete (Criteria,TableName , Processed)
VALUES (@BaseCriteria, @BaseTableName, 0)

DECLARE @Id INT
DECLARE @Criteria VARCHAR(5000)
DECLARE @TableName VARCHAR(5000)

WHILE EXISTS(SELECT 1 FROM @ToDelete WHERE Processed = 0)
BEGIN

SELECT TOP 1
@Id = Id
,@Criteria = Criteria
,@TableName = TableName
FROM @ToDelete
WHERE Processed = 0
ORDER BY Id DESC

INSERT INTO @ToDelete (Criteria, TableName, Processed)
SELECT
ReferencingColumn.name + ' IN (SELECT [' + ReferencedColumn.name + '] FROM ['
+ @TableName +'] WHERE ' + @Criteria + ')',
ReferencingTable.name,0
FROM sys.foreign_key_columns fk
INNER JOIN sys.columns ReferencingColumn
ON fk.parent_object_id = ReferencingColumn.object_id
AND fk.parent_column_id = ReferencingColumn.column_id
INNER JOIN sys.columns ReferencedColumn
ON fk.referenced_object_id = ReferencedColumn.object_id
AND fk.referenced_column_id = ReferencedColumn.column_id
INNER JOIN sys.objects ReferencingTable
ON fk.parent_object_id = ReferencingTable.object_id
INNER JOIN sys.objects ReferencedTable
ON fk.referenced_object_id = ReferencedTable.object_id
INNER JOIN sys.objects constraint_object
ON fk.constraint_object_id = constraint_object.object_id
WHERE ReferencedTable.name = @TableName
AND ReferencingTable.name != ReferencedTable.name

UPDATE @ToDelete
SET Processed = 1
WHERE Id = @Id

END

SELECT
'PRINT ''Deleting from ' + TableName + '...''; DELETE FROM [' + TableName + '] WHERE '
+ Criteria
FROM @ToDelete
ORDER BY Id DESC

END



When you execute this, you will see list of DELETE statement, which you need to run.

May 15, 2012

Enumeration Types as Bit Flags

An enum is best practice to give internal constants to readable string format, example

image

It’s very handy to use string rather to remember int value and it also helps to maintain code if down the road we need to change integer value it wont be difficult. I am sure developer knows very well about how to use enum in their code.

The post is all about answering few question comes while development or requirement, How you pass multiple value by using enum? or How to assign multiple enum values to variable? or How can I store combination of enum values using single enum variable?

All question have single answer, to use enum as bit flags. In order to achieve this, you have to add new attribute Flags to your enum declaration. As these values are bit you can use bitwise operation which are AND, OR, XOR and NOT.

Let’s see useful example of Flag enum using normal coding and then we will see same thing using Flags.

In normal coding if I want to calculate discount for four country and more then one at same time, I rather create for methods and call four individual functions

image

OR I can add bool into signature for calculating particular discount.

image

Drawback of first method is you have to keep adding new functions if you introduce new country and in second you have to pass false to country which you don’t want to do calculation, so signature will get increase in case we have more countries

Now lets use Flag enumeration to avoid mention drawbacks.

This will how your new enum will look like

image

A new attribute called Flags is added and we have assigned constants in power or TWO, that is 1,2,4,8 and so on, so when we use in combination no one get overlap.

Lets go ahead and create CalculateDiscount function and use into our program.

image

So single function CalculateDiscount is responsible to calculate discount for four different country at a time. If I want to calculate discount for German and Canada, you can do that by passing both in single argument using ‘|’ operator, its bitwise OR operator. You can use ‘&’ bitwise AND operator to determine whether a specific flag is set or not.

Jul 17, 2010

How to get multiple result set of procedure using LINQ to SQL

There always be case where one procedure returns more then one result set. Getting those data in DataSet is lazy way of coding, best way to do that is using DataReader. DataReader having method call NextResult which allows us to read next result set if any.

Read more from here.

Jun 24, 2010

OperationFormatter could not serialize error with WCF

I was working with calling WCF from iPhone, I have posted one post on “how can you call WCF from iPhone” you can find here. While I was working with this, I faced this issue and after doing some research I found solution! Here is what I did.

Following operation contract works fine.

[OperationContract]
public Dictionary<string, string> GetDictionary()

Note that I have only put operation contract not decoration which needed to work WCF with iPhone and Json.
But if we change this that operation contract to following...

[OperationContract]
public string GetDictionary()

After doing this I started getting follwoing error.

The OperationFormatter could not serialize any information from the Message because the Message is empty

I was wondering as it was issue with primitive type string! where it was working find with complex type. I searched a lot but did not get any solution for this. The service was retuning Serialized Json data; but not sure what was wrong there. I was searching for workaround to this but didn’t find any then I wrap that string into concert class and and return that class object, and you don’t believe it works fine! Error is gone I fixed The OperationFormatter could not serialize any information from the Message because the Message is empty error, wow!!!!!

I have modified operation and now it looks like following.

[DataContract]
public class Response
{
[DataMember]
public string Data { get; set; }
}

[OperationContract]
public Response GetDictionary()
{
return new Response() { Data = "success" };
}

It still open question why it was not working in only string, however it was working with Dictionary object and then with Abstract type! I assume that at the time of serializing request its not able to create object of string as its primitive type! Not sure its true but it works fine with wrapper.

Jun 22, 2010

wsdl-service-soap-address location having machine name not domain name

After fixing “Domain name replaced with machine name in WCF Service”, you can find solution in my previous post.

I found same issue but somewhere else, when you look into wsdl at the end where all services are listed there still machine name exists.

image

And hence any of the client will have following error.

There was no endpoint listening at http://domainname/ServiceName.svc that could accept the message. This is often caused by an incorrect address or SOAP action.

That is because it still uses computer name in soap address not domain name. Lets fix this issue too. We have to simply change endpoint address nothing more.

<services>
<service behaviorConfiguration="serviceBehaviour" name="Demo.Service.MultiEndPointsService">
<endpoint address="http://192.168.1.2/Demo.Service/MultiEndPointsService.svc/basic" binding="basicHttpBinding" bindingConfiguration="basicBinding"
contract="Demo.Service.MultiEndPointsService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.1.2/Demo.Service/MultiEndPointsService.svc/basic"/>
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>

Now let’s how wsdl looks like.

image

We are good to go!

Domain name replaced with Machine Name in WCF Service

I personally came across this issue WCF was taking machine name not IP address or domain name and also I got questions from forums about “how to replaced Machine Name with Domain name in WCF Service wsdl link?”. This occurs when we host WCF service on IIS then the links to wsdl is uses local machine name not the domain name or IP address.

image

You can see in browser [here I used IP address of my machine] in wsdl link its adding my computer name, this is same issue when I publish this service on production; the wsdl link is taking name of production machine not domain.

I found some solutions which changes the bindings on server but again that is not helpful for me on production server however it works well on local machine.

Then I was checking the configurations and found solution for how Domain name replaced with Machine Name in WCF Service without playing with IIS bindings. In service behavior we can change the behavior of serviceMetadata which will FIX our problem. We need to specify on what location metadata will resides httpGetUrl or httpsGetUrl. We can add url having domain rather machine name. So final configuration should look like following which is our solution.

<system.serviceModel>
<services>
<service name="Demo.Service.MultiEndPointsService" behaviorConfiguration="serviceBehaviour">
<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="Demo.Service.MultiEndPointsService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.3.61/Demo.Service/MultiEndPointsService.svc/basic" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None"></security>
<readerQuotas maxStringContentLength="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>

You can see value of httpGetUrl; I have specified IP address

image

Now let’s see again in browser.

image

There you goo!!!

Jun 21, 2010

Calling WCF service from iPhone

WCF changes way of communication between application-to-application and intra-application. This post will help you to call WCF from iPhone application. First we will see what we have to do on WCF to let iPhone application call service. And the sample code which call WCF from iPhone.

First let’s create simple WCF service.

[ServiceContract(Namespace = "")]
[DataContractFormat]
public class MultiEndPointsService
{
[OperationContract]
public string GetDictionary()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("IB", "Imran Bhadelia");
dict.Add("DO", "David Oliver");
dict.Add("NA", "Nick Althoff");
dict.Add("JJ", "Jay Joshi");
dict.Add("DL", "Dave Larson");
dict.Add("BA", "Brenda Ayong-Chee");
dict.Add("JP", "Jay Parikh");

StringBuilder sbJson = new StringBuilder();
new JavaScriptSerializer().Serialize(dict, sbJson);
return sbJson.ToString();

}
}

This is simple WCF Service. We need to add some decoration for enabling web script and handle POST method. We are going to send http post form iPhone application and send Json string as response. Doing so we also need to decorate our operation contract to set request and response format.

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehaviorAttribute(IncludeExceptionDetailInFaults = true)]
[DataContractFormat(Style = OperationFormatStyle.Document)]
public class MultiEndPointsService
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
public string GetDictionary()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("IB", "Imran Bhadelia");
dict.Add("DO", "David Oliver");
dict.Add("NA", "Nick Althoff");
dict.Add("JJ", "Jay Joshi");
dict.Add("DL", "Dave Larson");
dict.Add("BA", "Brenda Ayong-Chee");
dict.Add("JP", "Jay Parikh");

StringBuilder sbJson = new StringBuilder();
new JavaScriptSerializer().Serialize(dict, sbJson);
return sbJson.ToString();
}
}

And following are the configuration settings

<system.serviceModel>
<services>
<service name="Demo.Service.MultiEndPointsService" behaviorConfiguration="serviceBehaviour">
<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="Demo.Service.MultiEndPointsService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="basicBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="None"></security>
<readerQuotas maxStringContentLength="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>

We need to create basicHttpBinding so it get called form iPhone application, we haven’t sent security to call this method; and following is the Objective-C code which call WCF from iPhone.

NSString *soapMessage = [NSString stringWithFormat:@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><GetDictionary></GetDictionary></SOAP-ENV:Body></SOAP-ENV:Envelope>"];

NSURL *url = [NSURL URLWithString:@http://localhost/Demo.Service/MultiEndPointsService.svc/basic];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"urn:MultiEndPointsService/GetDictionary" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

Once you parse the response it will look like following.

wsdl

You can also call operation contract having parameters, for that need to create proper message and then add it in SOAP-BODY that will work.

Jun 20, 2010

WCF Service with webHttpBinding-basicHttpBinding-wsHttpBinding

WCF Services are designed to support distributed services where consumed client. Services are typically have WSDL interface which any of client can consumed regardless of platform on which WCF is hosted on.

WCF Services having three portions, Class having methods, host environment to host service, and one or more endpoints. Endpoints is place where WCF Client connects to WCF Service. In order to accommodate different communication scenario you just need to create more then one endpoints, for each endpoint you specify the address, a binding and a contract. Address is simple listener; contract specify the format of message which will arrive on specified address and binding is let you configure transport protocol, encoding and security. There are few built-in bindings represented by System.ServiceModel.Channels.Binding class to support HTTP, TCP and MSMQ protocols.

That was brief about WCF, now lets come to our business. We need to use wsHttpBinding + basicHttpBinding + webHttpBinding all together. That means we need to have multiple ends points to our service for different-different scenario. Here are the Service contract and operation contracts which we are going to use.

image

We will add one by one binding and check into WCF Test Client. First we will add basicHttpBinding which is designed for interoperability utmost important, its using SOAP 1.1.

image

You can see single endpoints having address and bindings, we have added binding configuration name basicBinding, which have property like security mode to None, readerQuotas having setting for client who is reading data from channel, also maxBufferSize which is parameter defined size which can be passed thru channel. We can see bindings in WCF Test Client it will show basic http bindings having one method. The value of maxBufferSize and maxReceivedMessgaeSize should be same for transfer mode is buffered. We have added behavior configuration for our service; serviceMetadata httpGetEnabled="true" allows simple HTTP Get request to succeed for metadata retrieval, by default WCF does not exposed metadata.

We can use WCF Test Client to check whether our setting are correct or not. So open WCF Test Client and add service url into service project.

image

It shows that we have exposed our service using basicHttpBinding. Now lets add wsHttpBinding binding, which is design for security, reliable messaging and transactions and its using SOAP 1.2 along with WS-Addressing 1.0 for message version which will carry additional protocol headers.

image

We have added binding configuration to set security and session reliability. The reliable session WCF provides ensures that messages sent between endpoints are transferred across SOAP or transport intermediaries and are delivered only once and, optionally, in the same order in which they were sent

Now let’s check on our WCF Test Client.

image

So, we can see two endpoints has been exposed, one is for basic binding and other is web script bindings. We already add basic and ws bindings lets add now web bindings.

image

One more endpoint, it’s now easy to expose more then one endpoint for single operation contract. If you need any security or additional settings then you can add binding configuration for this endpoint, but for now we don’t need any configurations. Let’s check our WCF Test Client.

image

We can see all these three binding for single operation contract! You can see wsdl file which will expose all these three bindings.

image

So we have exposed webHttpBinding + basicHttpBinding + wsHttpBinding endpoints in WCF service using same operation contract. We can use webHttpBinding for Silverlight application and also Json call.

Jun 14, 2010

RadComboBox dropdown issue in IE

Hello All, I was facing issue with RadComboBox dropdown, its adding scrollbar in IE if an item is longer then default size.

image

This is normal behavior, as we have item which get fits into dropdown, now consider following case where we items which are little longer then before.

image

Here you can see horizontal scrollbar is appear as our text is little bit longer then min-width property. Min-width property allow you to set minimum width of dropdown. But this looks weird.

Solution: You need to override following default style of RadComboBox.

<style>
.rcbSlide div
{
width: auto !important;
min-width: 150px !important;
max-width: 400px !important;
}
.rcbList
{
position: relative !important;
}
</style>

We can see after applying this style into page, RadComboBox will look like following.

image

Apr 17, 2010

HTTP Error 404.17 - Not Found with IIS7 and WCF

Hello All,

I was running to same issue when I have installed VS2010 on Windows 7 after installing .NET on IIS 7.5. My WCF service was retuning me the following error when I try to hit my wcf service it will giving me following error.

HTTP Error 404.17 - Not Found

I tried to change application pool and switch form 2.0 classic to 4.0 class, and then it gives me one more error!

HTTP Error 500.19 – Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Error Code 0×800700b7
Config Error There is a duplicate ’system.web.extensions/scripting/scriptResourceHandler’ section defined

After doing some search I found out the fix of this, we just need to register service model using following command, you should run command prompt in administrator mode and then go to following directory.

$WindowsDir$\Microsoft.NET\Framework\v3.0\Windows Communication Foundation

And run this command in favor to register service model.

servicemodelreg –i

It will install machine configuration sections, handlers, assemblies, modules, protocols and lots of other thing to work things properly.

Mar 16, 2010

Two WCF Sharing same a Data Contract - Ambiguous Error

[Problem: Ambiguous reference]

Hello All,

I came across one common issue while working with WCF services, Two WCF exposing same data contract with different namespace. Here are my two service contract with operation contracts.

namespace SVCDataContractTest.WCF
{
[ServiceContract]
public interface IService1
{
[OperationContract]
void DoWork(UserInfo userInfo);

[OperationContract]
void SaveContact(ContactInfo contactInfo);

}

public class Service1 : IService1
{
public void DoWork(UserInfo userInfo)
{
//Do some work
}

public void SaveContact(ContactInfo contactInfo)
{
//Do some work
}
}

[ServiceContract]
public interface IService2
{
[OperationContract]
UserInfo DoWork();
}

public class Service2 : IService2
{
public UserInfo DoWork()
{
//Do some work
return new UserInfo();
}
}
}

While adding them as reference it will generate two separate class having different namespace, we are good here as there won't be any compilation error if a requester don't import both namespace.



You can see there two UserInfo classes. Now problem comes when you imported both of the namespace, what happen to your class? it will start giving you following error.



It says that UserInfo is an ambiguous, as there are two set of classes resides in reference. The problem is when you add Service reference it's not treating UserInfo class as Shared class. Solution for this is to create Proxy with Type Sharing. We can use wsdl.exe to create proxy with shareType switch

wsdl.exe /out:ServiceProxies.cs /shareTypes http://localhost/SVCDataContractTest.WCF/Service1.svc?wsdl http://localhost/SVCDataContractTest.WCF/Service2.svc?wsdl

This will result in one class file called ServiceProxies, which contains the proxy implementation of both service but the implementation of UserInfo will be single.

ProxyCD1

Dec 10, 2009

Schema and Data Compare Scripts in MS SQL

Hello All,

I was searching for a tool which gives me the Schema and or data comparison for SQL Server, its really needed while we are updating staging or updating our live site. There may be lots of tool available on net but I found one tool which is part of Microsoft® Visual Studio Team System 2008 Database Edition GDR R2.

Team Edition provides lots of functionality, mainly we are using to write Test Case which is very useful for Test Driven Development.

On top of this if you have Database edition then you can do lots of things with it. One of the feature is Schema and Data Compare. This blog post will walk you thru steps to compare data and schema.

Schema Comparison

1. Go to New Schema Comparison form Data menu

2. Next select the two database, one is source and other is target

 

3. When press OK will give you the Schema Compare of all the objects including Tables, Views, Stored Procedures and many more.

Here you can see the list of Objects and the Object Definitions windows

4. In following image Table is expanded so you can see the changes in details on what table what action is held.

 

5. To see more in details select one of the updated row and you can see the definition in Object Definitions window; it will generate Create script and highlight the difference. There is also Schema Update Script which will have alter script of all the changes that is detected during Schema Compare.

6. You can either copy the script or export to file or editor by using Export To Edition command on tool box.

This was all about how to detect schema change, its very handy with lots of options.

Data Comparison

Now same way we have Data Comparison, which is use to compare data, it provides tons of details and script for insert/update and delete. The steps are pretty much starlight forward. I have listed the steps here.

1. Click on New Data Comparison from Data menu

2. It will ask for Source and Target tables

3. On click of Finish, it will provide you all the information that is differ in between two database tables

You can see here it shows 2 rows are only in source, means two rows are added to SB_mst_Group table. It also provides the what exact rows are added in middle section along with other options.

In third last section which is Data Update Script; provides you the script for the action, here we have addition, so its provide the insert statements which we can run in UAT to get the date.

I found it very useful and easy to generate required script in few mouse click!

Nov 25, 2009

Consuming WCF service out of box

Hello All,

I found one issue while consuming WCF service from out of box, There are lots of threads I found for 'The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.' error, CommunicationObjectFaultedException exception thrown and 'The caller was not authenticated by the service.'

I spent lots of time in search, got bunch of solutions, some worked some does not, after doing lots of troubleshooting I got solution for my problem.

My case was, a web application running on different box is trying to consume WCF service which is hosted on different box, but some how on production it was not working. It always throws 'CommunicationObjectFaultedException'. Usually we are putting such calls in using blog, as its taking care of disposing object. But in case of WCF it may not work as per expected, the reason is; A CommunicationObjectFaultedException has been throws so you, the object is not yet initialized and you are using is trying to dispose method which again throw exception.

 

This is because using implicitly call Dispose at the closing brace, which may throw an exception because your object is not yet initialized as its in the Faulted state. To over come this a simple solution, use try catch and call Abort. More reading on this click Avoiding Problems with the Using Statement, good article form Microsoft including Sample application. During my search I found one good code delegate make you fell like you are using clause, but internally its handling such exception.

private class Util
{
public static void UsingWcf<T>(T client, Action<T> action)
where T : System.ServiceModel.ICommunicationObject
{

try
{
action(client);
client.Close();
}
catch (Exception)
{
client.Abort();
throw;
}
}
}
class Program
{
static void Main(string[] args)
{

Util.UsingWcf(new WcfClient(), c =>
{

});

/*using (WcfClient wcfClient = new WcfClient())
{
....
}// This will throw an error
*/
}
}

So we have caught CommunicationObjectFaultedException, but still we are not able to make call to service method. Now you can see one new error 'The caller was not authenticated by the service'. Cool we reach the service but its missing some credentials, as we are consuming service out of box.

Typical configuration section looks like following



Form error 'The caller was not authenticated by the service' we can guess that we need some credentials to call method. You can see the configuration; it says clientCredentialsType="Windows" and security mode is Message, generally with wsHttpBinding these are the typical settings.



As we are using Windows as credential type, we need to provide credentials to use WCF serverice out of box. Once this done you just need to pass user and password in ClientCredentials just like bellow