Friday, December 16, 2011

Workaround to Button using MVVM ICommand and IsEnabled issue

When you are using the Command Button in MVVM pattern with ICommand, you will not be able to use the IsEnabled property to enable/disable the command button. As a workaround to enable/disable the command button, you can put the Command Button inside the group control like StackPanel and set the IsEnabled property of StackPanel to TRUE/FALSE.

Monday, November 7, 2011

i++ kind of functionality in F#

As F# is immutable language, we will not be able to use i++ kind of functionality directly. You will have to combine the "mutable" and "module" feature of F# to achieve the i++ kind of functionality. Below here is the simple demonstration of this;

module Foo
       let mutable m_field = 0
       let next () =
             m_field <- m_field + 1; m_field

Just use Foo.next () whereever you need i++ kind of functionality.

Wednesday, October 19, 2011

Consume WCF REST service in F#

Today I successfully implemented the code for consuming WCF REST service in F#. Funny part here is that, this is my first program in F#.. LOL

Ok.. Here is the code for consuming WCF REST in F#.

module FSModule

#light

open System
open System.Text
open System.Net
open System.IO
open System.Web

// F# uses indenting to define scope. So ensure that you indent properly to get it working
let GetDataFromRest =
     let buffer = Encoding.ASCII.GetBytes("<HelloService_SayHello><input>Hello from F#</input></HelloService_SayHello>") //This is needed if its a POST call
     let req = WebRequest.Create(new Uri("http://localhost/HelloService.svc/SayHello")) :?> HttpWebRequest
     req.Method <- "POST"
     req.ContentType <- "application/xml" //Use accordingly XML or JSON
     req.ContentLength <- int64 buffer.Length
     let reqSt = req.GetRequestStream()
     reqSt.Write(buffer,0,buffer.Length)
     reqSt.Flush()
     req.Close()

     let res = req.GetResponse () :?> HttpWebResponse
     let resSt = res.GetResponseStream()
     let sr = new StreamReader(resSt)
     let x = sr.ReadToEnd()
     sr.Close()
     x.ToString()

Done... To invoke this, you can either use F# or C# or even VB.NET :)

F#

let result = GetDataFromRest()
printfn result

C#

string result = FSModule.GetDataFromRest()

Friday, October 14, 2011

Smartphone App for Mainframe systems - A thought

Recently I submitted this idea for one of the competition. The competition was for design approaches for smartphone app for mainframe systems.
Mainframe application provides functionality for uploading the JCL jobs via FTP and executing them. And iPhone SDK supports FTP functionality. Hence we can leverage these functionalities for running the Mainframe jobs from the iPhone or iPad Apps (even we can extend further to Android as well).



Here is the simple demonstration how this can be achieved



1) User keys in the instructions to be run in the mainframe application

2) Clicks Submit button

3) Using the iPhone SDK create the Commands.jcl file

4) Open the FTP connection to the IBM mainframe (FTP details will be pre-configured using the Settings screen)

5) Run the following commands

        a. quote site filetype=jes

        b. quote site jeslrecl=80

        c. put commands.jcl

This will kicks of the job and execute the instructions in the commands.jcl file.

6) Once the instructions are executed, the response will be available in the spooled output file “JOB#####.n” where ‘n’ is the dataset number. (The challenge here will be when to read this response file)

I am yet to hear the result from the competition. Hope this idea wins me an iPad2.. LOL

Tuesday, September 6, 2011

Silverlight and SEO

Recently I came across a very good article on Silverlight and SEO techniques for public facing Silverlight based websites. Check the link below for more;

Silverlight and SEO

Thursday, September 1, 2011

WCF RIA and custom methods

There may be times where-in you will have to add some custom coded methods along with the auto generated EF wrapper methods. You may be wondering how to do. Don't worry.. RIA provides support for that and is very simple. Follow these steps to get this work;

Server-side

In the Domain service class, decorate the custom methods with the [Invoke] attribute. Job done!!

[Invoke]
public string SayHello ()
{
        return "Hello";
}

Client-side

This is how you can access the RIA custom methods;

HelloDomainServiceContext ds = new HelloDomainServiceContext();
ds.SayHello( (p) => {var result = p.Value;}, null);

Wednesday, August 24, 2011

Dreaded NotFound and Object reference not set to an instance of object exceptions in WCF RIA Services

Recently while developing an WCF RIA Services and SL4 client, I was facing these dreaded "NotFound" and "Object reference not set to an instance of object". After a bit of googling figured out the problem and its root cause.

NotFound exception

To view the actual error, you will have to use Fiddler. In the Fiddler, you can find out the actual error as "HTTP 404, Page Not Found error". This is because, WCF RIA service sits in the same virtual directory of you SL4 application. But the necessary config entries were not getting copied to the SL4 application config file.

For instance, When you create an RIA service and SL4 client; you will get the following projects in your solution;

xxxRIASerices.Host
xxxRIAServices.Host.Web

xxxSLRIAClient
xxxSLRIAClient.Web

The necessary config entries for enabling RIA service will be available in the App.Config file in xxxRIAServices.Host.Web (Basically the connectionStrings, System.Web, System.webServer sections). Copy those sections to xxxSLRIAClient.Web Web.Config file.

Bingo, we have get rid of the NotFound exception.

Object reference not set to an instance of object exception

I am sure, you will be getting this error. :) To solve this error, copy paste the System.ServiceModel section from xxxRIAServices.Host.Web App.Config to xxxSLRIAClient.Web Web.Config file.

Yes, now you should have get rid of these 2 exceptions and your WCF RIA service and SL client App will be working like charm.

Tuesday, August 23, 2011

EntityFramework and WCF

Recently while developing the WCF wrapper service for Entity Framework figured out that, the entities from EF cannot be used over the Channel. The reason was "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection". [You can capture this error if you enable WCF diagnostic logging].

There is a work around for this. You will have to use Data Transfer objects which mirror the entities from EF. So you can use those DTOs for tranmitting over the channel. It is not necessary that you will have to do this process manually, there are small add-ins available for doing this job. I used the EntitiesToDTO codeplex VS2010 add-in for this. So whenever we update the EF entities, just re-run this add-in which will update the DTOs based on the entities from EF.

PS - The transformation from entities to DTOs still need to be done by ourselves in the WCF operations.

Getting OperationContract name in WCF MessageDispatcher

There may be times where you need to identify the OperationContract name in WCF MessageDispatcher and do some processing based on that. Here is how you can do that;

In case of WCF Endpoint

In the AfterReceiveRequest method, do the following to get the Operation name;

MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
Message originalMessage = buffer.CreateMessage();
XmlDictionaryReader xmlDict = orginialMessage.GetReaderAtBodyContents();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlDict.ReadOuterXml());

string action = doc.DocumentElement.Name; //here you will get the OperationContract name

In case of WCF REST Endpoint

In the AfterReceiveRequest method, do the following to get the Operation name;



MessageProperties props = request.Properties;
string action = props["HttpOperationName"].ToString(); //here you will get the OperationContract name

Dreaded System.Security.SecurityException: Security Error... Silverlight and WCF REST

Recently I faced the dreaded System.Security.SecurityException: Security Error.. while developing the SL4 application consuming the WCF REST service. After a lot of trials fixed this dreaded issue. So thought of sharing my experince on SL4 consuming WCF REST service.

1) Ensure that crossdomain.xml and clientaccesspolicy.xml files are available in C:\Inetpub\wwwroot folder.
2) If you are using HTTPS, ensure the following;
  • Ensure clientaccesspolicy.xml contains explicit <domain uri="https://*"></domain>
  • Ensure only SSL access is enabled. The SL app and WCF REST service should not be accessible in HTTP mode.
  • Ensure crossdomain.xml contains <site-control permitted-cross-domain-policies="master-only"/> <allow-access-from domain="*" />
Do IISRESET. Then you should be able to get rid of this dreaded error.

Thursday, August 18, 2011

WCF REST - Two things made me wondering 2 or 3 days (stream.Position = 0 and WebMessageBodyStyle.Bare

Recently I developed one WCF REST service which has to be consumed in Silverlight 4.0. Since it is a WCF REST service, we will be dealing with JSON or XML format. But my customer wanted the support for object/contract as well [Don't ask me why not use simple WCF :) ]. So I did implement Datacontract Serialization. I was facing these 2 issues and looking throught web for answers. Finally after 2 days, the solution just struck in my mind.

Issue 1:
Root element is missing

I had the following code for deserialization.

XDocument doc = XDocument.Load(result);
MemoryStream str = new MemoryStream();
doc.Save(str);

DataContractSerializer serializer = new DataContractSerializer(typeof(EntityTypesCollection));
EntityTypesCollection typeColls = (EntityTypesCollection)serializer.ReadObject(str); //I was receiving the error "Root element is missing" here

I kept checking, what am I doing wrong... Finally after some brain crunches, finally figured out that we need to position the stream to 0.
str.Position = 0;

Voila, Issue 1 solved. Now the second issue.

Issue 2:
Response XML was wrapped like this;
<operation_response><operation_result>[Actual Result]</operation_result></operation_response>

I found a lot of complicated approaches to the simple 2 lines of deserialization code. Like filtering out the XElements from the response and through LINQ building back the contract.

Suddenly I noticed that, I mentioned the BodyStyle as WebMessageBodyStyle.Wrapped. This when I changed to WebMessageBodyStyle.Bare, Voila the response XML just came out like I wanted. Finally, the simple 2 lines of deserialization code worked..

So folks, be aware these 2 issues when you work witn WCF REST and serialization/deserialization.

Wednesday, July 20, 2011

WCF REST and Silverlight Synchronous calls within same domain

In my previous blog Silverlight and WCF REST near synchronous calling we saw how to achieve near synchronous behavior in the cross domain scenario. But if you have the advantage of hosting the WCF REST in the same domain of Silverlight; it is possible to achieve synchronous behavior using Wilco's HTTP requests for Silverlight

Below is the sample code which I used;
var result = Request.To("/services1.svc/DoWork")
.WithHeader("Content-Type","application/xml")
.Send().ReadAllText();

ASP.NET Validators inside AJAX UpdatePanels

Got a requirement to use ASP.NET Validators inside AJAX UpdatePanels? Don't worry, here is the solution. Just follow the steps provided in the link below;
http://blogs.msdn.com/b/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx

Silverlight and WCF REST, near synchronous calling

It may be very annoying since Silverlight doesn't provide synchronous calls with WCF. Loads and loads of debate happened around this but no concrete solution yet out in the market. I tried to solve this problem to an extend (not exactly synchronous) using Microsoft Rx (Reactive Extensions) framework and Wilco Bauwer's Http Request in Silverlight approach. See below how I did;


Microsoft Rx Extensions


1) Download the Microsoft Reactive Extensions framework
2) Add the System.Reactive.dll assembly reference to your Silverlight app
3) Add the following property and private variables;


private string _result;
protected bool _pageRefreshed;

public string Result1
{
get
{

return _result;
}
set
{
_result = value;
_pageRefreshed = true;
MainPage_Loaded(null, null);
}
}


Here what I am trying to do is that, instead of having the separate delegate function to handle the callback, I am pushing the callback to Silverlight Page_Loaded event. This is very similar to the way we deal with Postbacks in Page_Load in ASP.NET


4) Use this code to invoke your WCF REST service


WebClient client1 = new WebClient();
Uri url = new Uri(
https://www.WCFRESTService.Demo/BLServiceImplementation.svc/TraceError);
string input = "<LoggingServices_TraceError xmlns='http://tempuri.org/'><message>Hello!! I am from Silverlight!!!</message></LoggingServices_TraceError>";



var o = Observable.FromEventPattern(client1, "UploadStringCompleted").Select(newstring => newstring.EventArgs.Result);

o.Subscribe(s => Result1 = s);


client1.Headers["Content-Type"] = "application/xml";
client1.UploadStringAsync(url, input);


This is how it works, the result from asynchronous WCF REST call will be assigned to the Result1 property. In the Set section, after assigning to the local variable; I am also firing the Page_Loaded event of silverlight.
And in the Page_Loaded event, I am handling the result like shown below;


void MainPage_Loaded(object sender, RoutedEventArgs e)

{
if (_pageRefreshed == true)
{
_pageRefreshed = false;
result.Text = _result;
return;
}
}

Wilco Bauwer's Http Request in Silverlight approach

1) Download the code from Wilco HTTP Request and Silverlight
2) Before actually using this in you application, you need to get the code build.
3) Also, you need to make some modifications to be able to use XML and JSON WCF REST calls. Locate the Request.cs file and modify the SetRequestProperties as shown below;

private void SetRequestProperties(HttpWebRequest request) {

request.Method = _method;
foreach (var entry in _headers) {
if (entry.Key.ToLower() == "content-type")
{
request.ContentType = entry.Value;
}
else
request.Headers[entry.Key] = entry.Value;
}
}
4) Follow Step 3 in the above approach
5) Use the code below to call the WCF REST service;
Request.To(https://www.WCFREST.Demo/BLServiceImplementation.svc/TraceError)

.WithHeader("Content-Type", "application/xml")
.WithMethod("POST")
.WithBody("Hello!! I am from Silverlight!!!")
.SendAsync(response => Result1 = response.ReadAllText());

The approach is same as above except that Wilco provides Fluent Interface which is the user friendly LINQ.
The Page_Load code also same except for one small modification as below;

Dispatcher.BeginInvoke(()=> {

result.Text = _result;
});

You will make to wrap any assignment to UI controls with Dispatcher.BeginInvoke otherwise you will get cross thread access issue.

Happy coding!!! Let me know if you face any issues.

Wednesday, April 6, 2011

ScreenUpdating property and Excel/Word/Outlook Add-In

Recently while developing an Excel Add-In we faced a peculiar problem of Excel worksheet hanging after completing the processing. No problem in functionality, no memory leaks, no exceptions and nothing... We were breaking our heads where else it could fail...

After a couple of trials, we figured out that Workbook.ActiveWorksheet.ScreenUpdating was set to FALSE and was not turned back to TRUE. We usually set ScreenUpdating to FALSE to speed up the macro processing, but if we forget to turn back to TRUE; thats it; you will think Excel is hanging or something happened.. So please watch out while using ScreenUpdating in your code :)

Tuesday, March 22, 2011

Silverlight Integration in DNN

Here are the simple steps to integrate Silverlight in DotNetNuke.
1) Publish the silverlight application


2) Host the published silverlight application in IIS
3) Goto the DNN website. Create a web page for hosting the silverlight application
4) 4) Add the “HTML” module to the newly created page. And then, go to the HTML view in the Rich Text Editor. Place the <IFRAME> tag with the src to the silverlight HTML page hosted in IIS in the above steps
5) Voila!!! Now you can see that silverlight functionality working in the DNN site

Monday, March 14, 2011

Changing WCF service reference in silverlight at runtime

Since Silverlight App is packaged as XAP file, you may be wondering how to change the service reference after building the package. It is pretty simple. XAP file is nothing but a ZIP archive file.
So,
  • Unzip the file using any ZIP archiving software
  • Locate the ServiceReferences.ClientConfig
  • Change the end point in the file, save changes
  • Zip it again and change the extension to XAP

Voila!!!

Thursday, March 10, 2011

WCF DataContract serialization and deserialization in Silverlight

Here is how you can do serialization and deserialization of WCF DataContracts in Silverlight. This is needed when you use MessageContracts in WCF by wrapping DataContracts as XmlElement.

Serialization code:

DataContractSerializer serialize = new DataContractSerializer(request.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream,request);
string res = Encoding.UTF8.GetString(stream.ToArray(),0,stream.ToArray().GetLength(0));
TextReader reader = new StringReader(res);
XDocument doc = XDocument.Load(reader);
XElement elt = (XElement)doc.FirstNode;

you can pass the elt in your MessageContract and send to the WCF service.

Deserialization code:

Once you receive the response from WCF service as XElement, this is how you can deserialize that to object.

XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(elt.CreateReader());
DataContractSerializer serialize = new DataContractSerializer(reader);
result - serialize.ReadObject(reader);

Wednesday, March 9, 2011

Einstein's Fish Puzzle

Recently, my wife got impressed with the Einstein's quote of "Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid" and asked me to solve his famous "Fish Puzzle". I managed to solve that puzzle in 25 minutes.

The puzzle goes like this;

1. In a street there are five houses, painted five different colours
2. In each house lives a person of different nationality
3. These five homeowners each drink a different kind of beverage, smoke different brand of cigar and keep a different pets


THE QUESTION: WHO OWNS THE FISH?

HINTS
1. The Brit lives in a red house.
2. The Swede keeps dogs as pets.
3. The Dane drinks tea.
4. The Green house is next to, and on the left of the White house.
5. The owner of the Green house drinks coffee.
6. The person who smokes Pall Mall rears birds.
7. The owner of the Yellow house smokes Dunhill.
8. The man living in the centre house drinks milk.
9. The Norwegian lives in the first house.
10. The man who smokes Blends lives next to the one who keeps cats.
11. The man who keeps horses lives next to the man who smokes Dunhill.
12. The man who smokes Blue Master drinks beer.
13. The German smokes Prince.
14. The Norwegian lives next to the blue house.
15. The man who smokes Blends has a neighbour who drinks water.

Answer is: German


Anyone can solve this puzzle. Imagine this is the zig zag puzzle which we used to solve. Replicate the hint scenarios similar to that. Then it will be easy to solve this puzzle. How I did, I used Excel 2003/2007 to solve this puzzle. (Some brainiac can do in their mind itself like my wife.. :) ). I jot down the hints in the excels and painted them in some colors to identify. So that, while re-shuffling we can ensure that we are not breaking the rules of the hints!!!

Voila!! Try out at your home and you can also become next Einstein!!! LOL :P

Some simple steps to convert ASP.NET application to Silverlight application

Sometime you may be asked to look at the possiblity of converting the ASP.NET application to Silverlight application. Trust me, there are no hard and fast rules to migrating ASP.NET to Silverlight due to various reasons;
  1. Silverlight runs in client-side; ASP.NET runs in the server-side. This means, you will not be able to use as much as functionalities available from server-side.
  2. Application Life Cycle is entirely different for Silverlight and ASP.NET. You need to familiarize yourselves first before starting to work on silverlight.

But, somehow I managed to find some steps which will ease the ASP.NET to Silverlight migration;
  1. Find the equivalent controls for ASP.NET controls in Silverlight
  2. Convert the .aspx pages to .xaml files
  3. Define the Page navigation in App.xaml.cs file (bit difficult to do)
  4. Silverlight support very few assembly references. Migrate the .aspx.cs code .xaml.cs code accordingly.
  5. If you encounter some assembly references breaking, convert those functionalities to WCF service. Good thing about silverlight is that, it supports communication with WCF service with some limitations (no WS-Security)
  6. Silverlight follows MVVM pattern, if you application built around MVVM or can be easily upgraded to MVVM pattern, you can migrate your ASP.NET application to Silverlight application at ease...

I will update this post, If I manage to find some other tweaks and tricks in converting ASP.NET to Siliverlight.

Tuesday, February 22, 2011

Code to capture the Message arrived event in Outlook

There may be times when we want to do some operation upon arrival of the message in the Outlook Inbox. Here is the simple piece of code which will help to capture the message arrived event in Outlook.

//Initialization code
protected override bool DoInitialise()
{
outlook = new ApplicationClass();
outlook.Session.Logon(null, null, false, false);
inbox = outlook.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Items;
inbox.ItemAdd += new ItemsEvents_ItemAddEventHandler(inbox_ItemAdd);
outlook.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(outlook_NewMailEx);
return true;
}


void outlook_NewMailEx(string EntryIDCollection)
{
//This event will be fired whenever a mail arrives in Inbox
}

Passing Default Credentials from Silverlight to WCF

While developing Silverlight and WCF apps you will have to share the default credentials from Silverlight to WCF service sometime.



This is how you can do;


1) Create the <basicHttpBinding> with the following information under the <bindings> section;

<basicHttpBinding>
<binding name="BasicBinding0">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</basicHttpBinding>

2) Add the below piece of section under the <System.ServiceModel> section
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
</serviceHostingEnvironment>

3) Add the below piece of code above the OperationContract behavior;
[System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode=System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]
public class StaticDataProcessing : ProcessTaskWCFBase

Please note that steps 2 and 3 are needed to avoid the HttpContext.Current coming as NULL issue.

This way you can pass the default credentials from Silverlight to WCF.

ProjectLinker extension for Visual Studio

Recently we were developing an application in silverlight which will consume WCF for doing some business operations and data access. WCF was designed using MessageContracts and DataContracts concept. Each operation will translate to input and output DataContracts. This WCF is not an tranditional one in which when you add reference you will get all the data contracts. So we will have to share all these DataContracts to Silverlight app. There arised the problem, since the Desktop/Web class library project cannot shared in silverlight app. So we thought of creating a separate silverlight class library replicating all the classes. This will be a serious maintenance nightmare!!!!
That time, I came across the concept of ProjectLinker synchronization tool. This is specially designed to address such scenarios. Basically Multi-targeting framework.
Bingo!!! Problem solved. Using this we can share the same class files between different platforms nothing but between the Desktop/Web class library and Silverlight class library.

You can find more about how to use this tool in the below link;
http://msdn.microsoft.com/en-us/library/ff921108(v=pandp.20).aspx

Download Project Linker for VS2008 here;
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=387c7a59-b217-4318-ad1b-cbc2ea453f40&displaylang=en

Download Project Linker for VS2010 here;
http://visualstudiogallery.msdn.microsoft.com/5e730577-d11c-4f2e-8e2b-cbb87f76c044/

Thursday, January 6, 2011

Issues With Programmatically Attaching Multiple Files To A List Item

Recently one of my team member was facing issue while adding multiple files to a list item programmatically. The issue was, about 10% files added programmatically were corrupt while uploading. So whenever the user tries to download the file, they were getting "HTTP 500 Internal Server". Below is the piece of code he was using;

HttpFileCollection uploads = HttpContext.Current.Request.Files;


for (int i = 0; i < uploads.Count; i++)

{


HttpPostedFile upload = uploads[i];


if (upload.ContentLength == 0)


continue;


Stream inputStream = upload.InputStream;


byte[] buffer = new byte[inputStream.Length];


inputStream.Read(buffer, 0, (int)inputStream.Length);


inputStream.Close();


eItem.Attachments.Add(upload.FileName, buffer);


}


eItem.Update();
 
On analysing we found out that, the issue was with Attachments.Add method. It was causing some corruptions in the bytes uploaded. So we tried with Attachments.AddNow..
Bingo!!! It started to work without any issues.
 
The only difference between "Attachments.Add" and "Attachments.AddNow" was, "Attachments.AddNow"; it will create new version whenever you attach.
Also, "Attachments.AddNow" internally calls the "Update" method of the List Item. Though its very weird, it is solving the problem of bytes corruption while uploading multiple attachments to the list item.