How to Catch Exceptions thrown by a WCF service In Client

You can easily get the server side Unhandled exceptions thrown by a WCF service in Client by using FaultException

Set includeExceptionDetailInFaults to true in your service behaviours

<serviceBehaviors>
<behavior name=””>
<serviceMetadata httpGetEnabled=”false” />
<serviceDebug includeExceptionDetailInFaults=”true” />
</behavior>
</serviceBehaviors>

and then in client side you can catch exceptions like below
try
{
//your service call
}
catch (FaultException ex)
{
string msg = "FaultException: " + ex.Message;
MessageFault fault = ex.CreateMessageFault();
if (fault.HasDetail)
{
System.Xml.XmlReader reader = fault.GetReaderAtDetailContents();
if (reader.Name == "ExceptionDetail")
{
var detail = fault.GetDetail<Exception>();
msg += "\n\nStack Trace: " + detail.StackTrace;
}
}
//TraceService.Trace(msg);
}

Enjoy Programming…

JavaScript date serialization error in WCF POST Request

I have try to send an Ajax Post request from my client. So i am trying to send the DateTime format from client is like ’12/29/2014′ but my server accepts C# datetime. So i got an error like

There was an error deserializing the object of type ‘type’. DateTime content ’12/29/2014′ does not start with ‘\/Date(‘ and end with ‘)\/’ as required for JSON

How to resolve this error?

Write a javascript function like below
function ConvertToJsonDate(date) {
var convertedDate = new Date(date);
var str = Date.UTC(convertedDate.getFullYear(), convertedDate.getMonth(), convertedDate.getDate(), convertedDate.getHours(), convertedDate.getMinutes(), convertedDate.getSeconds(), 0);
var formattedDate = "\/Date(" + str + ")\/";
return formattedDate;
}

Convert your current date before sending request
var params = {
EndDate: ConvertToJsonDate(endDate),
};

Enjoy coding…

Dispose Returned stream in WCF

In this below method I have returned a file stream for downloading it in client or browser. Before returning that stream i have keep that file in a temporary location.After return that stream i have to dispose it and delete that directory.

public Stream DownloadAttachment()
{
Stream stream = null;
var directoryInformation = CommonServices.Utility.DirectoryHelper.GetTempFolderRootLocation();
string newFolderPath = "C:\\Attachments\\" + Guid.NewGuid();
try
{

string fullPath = newFolderPath + "\\" + fileName;
stream = File.OpenRead(fullPath);

}
catch (Exception exception)
{

return null;
}
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted += (sender, args) =>
{
if (stream != null)
stream.Dispose();
Directory.Delete(newFolderPath, true);
};
return stream;
}

Enjoy Coding…

Call Restful Service using HttpWebRequest and Post data

Introduction

This article helps  you call Restful service using HttpWebRequest and Post Data to a particular service.The below demonstrate a sample restful service in WCF and call as HttpWebRequest.

WCF Restful Service Source Code

Contract

[ServiceContract]
public interface IRestService
{
[WebInvoke(Method = “POST”, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = “/MyServiceMethod”)]
[OperationContract]
void MyServiceMethod(PostedInformation postedInformations);
}

Implementation

public void MyServiceMethod(PostedInformation postedInformations)
{
//do implemention code here
}

DataContract
[DataContract]
public class PostedInformation
{
[DataMember]
public List<string> To { get; set; }
[DataMember]
public string SenderEmail { get; set; }
[DataMember]
public string Subject { get; set; }
[DataMember]
public string SenderFullName { get; set; }

}

Calling the service using HttpWebRequest

PostedInformation postedInformations = new PostedInformation()
{
SenderEmail = “aaa@bbb.com”,
SenderFullName = “test”,
To = new List<string>() { “ccc@eee.com” }
};

var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postedInformations ));
//Passyour service url to the create method
var req =
HttpWebRequest.Create(“http://localhost/MyServer/YourServiceName.svc/MyServiceMethod&#8221;);
req.ContentType = “application/json”;
req.ContentLength = dataToSend.Length;
req.Method = “POST”;
req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response = req.GetResponse();

Enjoy coding…