ramlicious Blogs by Tina & Prabhu

December 5, 2011

Creating your first Workflow Foundation project

Filed under: .NET,C#,Programming,WF — Prabhuram @ 4:48 pm

First my thanks goes to Christophe Geers for making me put my first Workflow Foundation project. I am currently working on a project that requires WF for creating Business Rules. So here it goes. I have put a very simple solution that will help the reader understand about how to create a WF project.
First let us see what we are going to do. My new rule object will interpret an object called Person and will generate a message to address a person like:

Good afternoon Mr.Prabhuram Venkatesan

To start, let’s first create a business object called Person.

public enum GenderType { Male, Female };
public class Person
{
	public bool IsMarried { get; set; }
	public bool IsMinor { get; set; }
	public GenderType Gender { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
}

Our business rule is going to be embedded in a Workflow Console Application called Rules, within a Activity design called Addresser.xaml. I have implemented the business rules using the Flowchart, FlowDecision, and Assign toolbox controls using the Workflow designer, though you can apply your creativeness to do the same in a different ways. Additionally I created Flowchart variables called Salutation and Greetings, an In argument called ThePerson which is of type Person and an Out argument called the Message which is of type String. The usage of the variables can be seen in this figure below.

So to apply the rule, the input arguments has to be passed through the invoker and the output arguments can be received from the returned object.

Dictionary input = new Dictionary();
input.Add("ThePerson", new Person(){ FirstName="Prabhuram", LastName = "Venkatesan", Gender = GenderType.Male, IsMarried =true});

Dictionary output = (Dictionary)WorkflowInvoker.Invoke(new Addresser(), input);
Console.WriteLine(output["Message"].ToString());
Console.ReadLine();

I haven’t provided the complete code sample because I want the reader to put some effort to perform some findings by their own to figure out the components necessary.

December 2, 2011

Exception handling in WCF Services using SOAP Faults

Filed under: .NET,C#,Programming,WCF — Prabhuram @ 3:07 pm

One way I handle exceptions between WCF services and the service client proxy class is using the SOAP Faults. All you do is:

  1. Introduce <serviceDebug> attribute in the serviceBehavior\behavior element with includeExceptionDetailInFaults=”Boolean”
  2. Introduce a DataContract class that can take the properties that you wanted to pass to the proxy client.
  3. Decorate the OperationContract method with another attribute called FaultContract.
  4. Throw the FaultException from with the OperationContract.
The change in the service’s web.config will be
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"  />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

and the exception carrier will be something like this.

    [DataContract]
    public class MyException
    {
        [DataMember]
        public string ErrorMessage { get; set; }

        public MyException()
        {

        }

        public JsfException(string message)
        {
            this.ErrorMessage = message;
        }
    }

and service’s operation contract is decorated with FaultContract.

    [ServiceContract]
    public partial class MyServices
    {

        [OperationContract]
        [FaultContract(typeof(MyException))]
        public int Exec(int something)
        {
            // Do something
        }
    }

and now you will throw the exception like this.

    [ServiceContract]
    public partial class MyServices
    {

        [OperationContract]
        [FaultContract(typeof(MyException))]
        public int Exec(int something)
        {
            try
            {
                // Do something
            }
            catch (Exception ex)
            {
                MyException errMsg = new MyException(ex.Message) { Source = ex.Source };
                throw new FaultException<MyException>(errMsg, new FaultReason(errMsg.ErrorMessage), new FaultCode("MyCode"));
            }
        }
    }

and you can simply use this from the client like this.

        try
        {
            // Do something
        }
        catch (FaultException<MyException> ex)
        {
        }

November 30, 2011

Problem with the “Specified” property when generating WCF proxy classes

Filed under: .NET,C#,Programming,WCF — Prabhuram @ 6:59 pm

I was creating WCF services today and I encountered a weird problem when generating proxy clients for the services. When creating proxy classes using SvcUtil.exe for my presentation tier, the utility creates a xxxIsSpecified property for all the value type decorated with DataMembers attributes(like int, bool, etc)

[DataContract()]
public class MyClass
{
	[DataMember()]
	public int IntMember { get; set; }
}

So in this case, the property IntMember exposes an another property called IntMemberSpecified in the proxy class. After referring at many pointers and blogs (not from MSDN), I was able to overcome this by simply setting IsRequired = true property to the DataMember() attribute. So the class should look like this after the change.

[DataContract()]
public class MyClass
{
	[DataMember(IsRequired=true)]
	public int IntMember { get; set; }
}

You will note that this problem doesn’t happen when you use the Add Service Reference from Visual Studio.

November 23, 2011

Creating Custom Code Snippets in Visual Studio

Filed under: .NET,C#,Programming,Visual Studio,XML — Prabhuram @ 7:12 pm

Definitely Visual Studio Code Snippets save a lot of development time. It makes magic by replacing a small code snippet with a code block. Say for example, by simply typing ctor and pressing tab generates a default constructor code for you. In this article I will show how easy it is to add a custom code snippet. Before creating one, we will study an existing code snippet that you already have. You can view the list of code snippets by opening Visual Studio and opening Code Snippet Manager… in the Tools menu. You can see the code snippet called ctor listed under Visual C#. Simply copy the location of the .snippet file from the window and open the XML snippet file in Notepad.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>ctor</Title>
			<Shortcut>ctor</Shortcut>
			<Description>Code snippet for constructor</Description>
			<Author>Microsoft Corporation</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal Editable="false">
					<ID>classname</ID>
					<ToolTip>Class name</ToolTip>
					<Function>ClassName()</Function>
					<Default>ClassNamePlaceholder</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[public $classname$ ()
	{
		$end$
	}]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

The three parts that the learner should be interested in are:

  • Header, that informs about the shortcut key and the author
  • Literal Declarations, list of literals that are part of the snippet. You can think of the literals that appear when you use the prop (property) code snippet that requests for changes to the property name or simply as seen in this example it executes a Function to get the value.
  • Code, which is the information about the language and the code that the snippet will be expanded to (also note the SnippetType in Header)
Now you can create endless number of snippets with your imagination. I have created one for the sake of the reader. This code snippet creates a typed DataTable that is created from scratch. So this DataTable can be created by the developer without the use of Schema. All that the developer has to do is to add changes to the TODO part of the code.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">

    <Header>
      <Title>Typed DataTable</Title>
      <Shortcut>tdt</Shortcut>
      <Description>Code snippet for generating Typed DataTable</Description>
      <Author>Prabhuram Venkatesan</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>ObjectName</ID>
          <ToolTip>Prefix to the Class Name</ToolTip>
          <Default>Class</Default>
        </Literal>
        <Literal>
          <ID>DBColumn1</ID>
          <ToolTip>Column Name in the Database/T-SQL Query</ToolTip>
          <Default>db_column_1</Default>
        </Literal>
        <Literal>
          <ID>RowColumn1</ID>
          <ToolTip>DataRow property name for db_column_1</ToolTip>
          <Default>RowColumn1</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
using System.Data;

//Auto-generated code for Typed DataTable
public class $ObjectName$Table : DataTable
{
  public $ObjectName$Table()
    :base()
  {
    //TODO: Add all the remaining DB columns names
    Columns.Add(new DataColumn("$DBColumn1$", typeof(string)));
  }
  protected override Type GetRowType()
  {
    return typeof($ObjectName$Row);
  }

  protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
  {
    return new $ObjectName$Row(builder);
  }
  public $ObjectName$Row this[int idx]
  {
    get { return ($ObjectName$Row)Rows[idx]; }
  }

  public void Add($ObjectName$Row row)
  {
    Rows.Add(row);
  }
  public new $ObjectName$Row NewRow()
  {
    $ObjectName$Row row = ($ObjectName$Row)NewRow();
    return row;
  }
}
public class $ObjectName$Row : DataRow
{
  internal $ObjectName$Row(DataRowBuilder builder)
    : base(builder)
  {
    //TODO: Assign default values to all the properties
    $RowColumn1$=String.Empty;
  }

  //TODO: Add all the columns you want as part of a Row
  //      Map the DB column name to a property
  public string $RowColumn1${
    get {return (string)base["$DBColumn1$"];}
    set {base["$DBColumn1$"]=value;}
  }
}
        ]]>
      </Code>
    </Snippet>

  </CodeSnippet>
</CodeSnippets>

And now with this, typing tdt and Tab will generate the following code for you.


using System.Data;

//Auto-generated code for Typed DataTable
public class RoleTable : DataTable
{
    public RoleTable()
        : base()
    {
        //TODO: Add all the remaining DB columns names
        Columns.Add(new DataColumn("db_column_1", typeof(string)));
    }
    protected override Type GetRowType()
    {
        return typeof(RoleRow);
    }

    protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
    {
        return new RoleRow(builder);
    }
    public RoleRow this[int idx]
    {
        get { return (RoleRow)Rows[idx]; }
    }

    public void Add(RoleRow row)
    {
        Rows.Add(row);
    }
    public new RoleRow NewRow()
    {
        RoleRow row = (RoleRow)NewRow();
        return row;
    }
}
public class RoleRow : DataRow
{
    internal RoleRow(DataRowBuilder builder)
        : base(builder)
    {
        //TODO: Assign default values to all the properties
        RowColumn1 = String.Empty;
    }

    //TODO: Add all the columns you want as part of a Row
    //      Map the DB column name to a property
    public string RowColumn1
    {
        get { return (string)base["db_column_1"]; }
        set { base["db_column_1"] = value; }
    }
}

November 15, 2011

Uploading file to server from a web application using C#

Filed under: .NET,C#,Programming — Prabhuram @ 2:29 pm

I’ve put a small code block to save a file to the server from a web application using C#’s FileUpload Server control.

    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />

Here is how you do it.


        protected void Button1_Click(object sender, EventArgs e)
        {
            HttpPostedFile pf = FileUpload1.PostedFile;
            if ((pf != null) && (pf.ContentLength > 0))
            {
                try
                {
                    pf.SaveAs(string.Format("{0}\\{1}", Server.MapPath("."), System.IO.Path.GetFileName(pf.FileName)));
                    Response.Write("The file has been uploaded.");
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                Response.Write("Please select a file to upload.");
            }
        }

November 11, 2011

Notifying and Renewing Web sessions without AJAX

Filed under: .NET,C#,Programming,Uncategorized — Prabhuram @ 5:24 pm

Someone who tried to implement Notifying and Renewing Web sessions using AJAX using the Master pages would have learn’t that master pages doesn’t PageMethods and javascript will throw an error something like this

PageMethods is undefined

To overcome this, an easier way to retain the session is to simply use the server resource like calling an image in the server. So instead of using

PageMethods.RefreshSession(); //make the server call

we can simple do this

function triggerRefresh() {
var myImg = document.getElementById("imgDummy");
if (myImg) myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());
}

which is to simply have an <img> tag. And assign a source to the image in my loadform() function like this:

            var myImg = document.getElementById("imgDummy")
            myImg.src = document.url + "?";

and so my complete script in the .aspx page will become like this:


            <!-- script added to implement session timeout logic
    Logic:  1.  If no keys were pressed by the user for (session time out period - 1) minutes, an alert will be
                shown one minute before the session time out, if the user responds to the message, the session
                refreshes, else the session expires eventually
            2.  If keys were pressed by the user before (session time out period - 1) minutes, then the session
                automatically refreshes.
        -->
    <script type="text/javascript" >
        var actionFlag; //flag to monitor user key actions
        var timeoutPeriod; //holder for the server session timeout period (in minutes)
        var int; //variable for Interval
        var seconds = 60 //constant
        var nanoseconds = 1000 //constant

        //Uses the PageMethods to get the session timeout from the server
        function GetSessionTimeout() {
            //PageMethods.GetTimeoutPeriod(function (result) { timeoutPeriod = result; }); //todo: make it synchronous instead of async
            timeoutPeriod = parseInt(document.forms[0].inttop.value);  //session time out is available in a hidden field

        }

        //Calculates the retrigger time
        function getRetriggerTime() {
            if (timeoutPeriod == 1) return timeoutPeriod;
            return timeoutPeriod - 1;
        }

        //function handler for form's load event
        function loadForm(oEvent) {
            actionFlag = false; //reset the flag
            GetSessionTimeout(); //get the session timeout
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds); //renew the interval
            var myImg = document.getElementById("imgDummy")
            myImg.src = document.url + "?";
        }

        //function that resets the actionFlag
        function keyDown(oEvent) {
            if (actionFlag) return; //skip if the flag is already true
            switch (oEvent.keyCode) {
                case 17: //skip if key is ctrl
                case 18: //skip if key is alt
                    return;
                    break;
            }
            //else
            actionFlag = true;
        }

        //function that refreshes the session without an alert
        function autoRefreshSession() {
            triggerRefresh();
            int = clearInterval(int); //clear the interval, todo: check if this line is required
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds);  //renew the interval
            alert('auto refresh');
        }

        //function that executes when the user triggers to refresh the session
        function manualRefreshSession() {
            triggerRefresh();
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds); //renew the interval
        }

        function triggerRefresh() {
            var myImg = document.getElementById("imgDummy");
            if (myImg) myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());
        }
        //function thats executed at the scheduled time interval
        function notifyTimeOut() {
            int = clearInterval(int); //clear the interval, todo: check if this line is required
            if (actionFlag == true) autoRefreshSession(); //if action was taken, perform auto refresh
            else {
                alert('Your Session is about to expire! Click OK to refresh your session!'); //show alert to the user
                manualRefreshSession(); //if control returns refresh session, if the session has already expired a new session will start
            }
            actionFlag = false; //reset the flag
        }

    </script>

and I don’t have a single line of server code and most importantly no use for the ajax <scriptmanager>. Thanks to the author of Keep session alive with Javascript

November 10, 2011

Notifying and Renewing Web sessions using AJAX

Filed under: .NET,C#,Programming — Prabhuram @ 4:07 pm

This article demonstrates a simple technique to notify a session expiry and renew session.

  1.   Session is renewed when the user responds to the alert message before the session expiry time
  2.   Session is renewed when the user type in the web form before the session expiry time
  3.   Session expires when user does not respond to the alert message before the session expiry time

My .aspx page’s <body> tag will be something like this:

<body onload="loadForm(event)" onkeydown="keyDown(event)">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>

    <!-- script added to implement session timeout logic
    Logic:  1.  If no keys were pressed by the user for (session time out period - 1) minutes, an alert will be
                shown one minute before the session time out, if the user responds to the message, the session
                refreshes, else the session expires eventually
            2.  If keys were pressed by the user before (session time out period - 1) minutes, then the session
                automatically refreshes.
        -->
    <script type="text/javascript" >
        var actionFlag; //flag to monitor user key actions
        var timeoutPeriod; //holder for the server session timeout period (in minutes)
        var int; //variable for Interval
        var seconds = 60 //constant
        var nanoseconds = 1000 //constant

        //Uses the PageMethods to get the session timeout from the server
        function GetSessionTimeout() {
            //PageMethods.GetTimeoutPeriod(function (result) { timeoutPeriod = result; }); //todo: make it synchronous instead of async
            timeoutPeriod = parseInt(document.forms[0].inttop.value);  //session time out is available in a hidden field

        }

        //Calculates the retrigger time
        function getRetriggerTime() {
            if (timeoutPeriod == 1) return timeoutPeriod;
            return timeoutPeriod - 1;
        }

        //function handler for form's load event
        function loadForm(oEvent) {
            actionFlag = false; //reset the flag
            GetSessionTimeout(); //get the session timeout
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds); //renew the interval
        }

        //function that resets the actionFlag
        function keyDown(oEvent) {
            if (actionFlag) return; //skip if the flag is already true
            switch (oEvent.keyCode) {
                case 17: //skip if key is ctrl
                case 18: //skip if key is alt
                    return;
                    break;
            }
            //else
            actionFlag = true;
        }

        //function that refreshes the session without an alert
        function autoRefreshSession() {
            PageMethods.RefreshSession(); //make the server call
            int = clearInterval(int); //clear the interval, todo: check if this line is required
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds);  //renew the interval
        }

        //function that executes when the user triggers to refresh the session
        function manualRefreshSession() {
            PageMethods.RefreshSession(); //make the server call
            int = setInterval("notifyTimeOut()", getRetriggerTime() * seconds * nanoseconds); //renew the interval
        }

        //function thats executed at the scheduled time interval
        function notifyTimeOut() {
            int = clearInterval(int); //clear the interval, todo: check if this line is required
            if (actionFlag == true) autoRefreshSession(); //if action was taken, perform auto refresh
            else {
                alert('Your Session is about to expire! Click OK to refresh your session!'); //show alert to the user
                manualRefreshSession(); //if control returns refresh session, if the session has already expired a new session will start
            }
            actionFlag = false; //reset the flag
        }

    </script>
    </form>
</body>

and the code behind .aspx.cs’ class will be something like this:

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "sessiontimeout", string.Format(@"<input type=""hidden"" id=""inttop"" value=""{0}"" />", Session.Timeout));
        }
        [WebMethod]
        public static void RefreshSession() { System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() +  "Session refreshed"); }

September 26, 2011

Implementation of Factory Pattern

Filed under: .NET,C#,Design Patterns,Programming — Prabhuram @ 1:33 pm

I bundled together from my older examples to show the Factory design pattern here. This is an  implementation of one of the object library I created to search for a given text within files of different type  namely a text, xml or excel file. The library uses factory pattern to create an instance of the object required based on the request.


Here the Product is Seeker, Concrete Products are TextSeeker, XmlSeeker and ExcelSeeker. The Factory class is the SeekerFactory.

And you can simply use it from a client like this (you can use any XML file and change the properties accordingly):

    class Program
    {
        static void Main(string[] args)
        {
            SearchEntity a = new
                XmlFileSearchEntity() { RecurringElement = "url", LookupElement = "loc", SourceName = @"C:\OnWeb\sitemap.xml", SearchString = "prabhuram" };
            Seeker helper = new SeekerFactory().CreateXmlSeeker();

            foreach (Match match in helper.Search(a))
                Console.WriteLine(match.SearchString + "-" + match.MatchType.ToString() + "-" + match.PositionX + "," + match.PositionY + "-" + match.MatchingText);
            Console.ReadKey();
        }
    }

You can download the complete project from here: SearchLibrary.zip

This is simply how a Factory works. Other creational patterns like Factory Method and Abstract Factory  demonstrate a slight variation to the Factory pattern.

September 14, 2011

Using OData Services

Filed under: C#,OData,Visual Studio,WCF — Prabhuram @ 7:26 am

After writing WCF Data Services with an example (OData Sample), I realized that I could have showed the service that we just created with an example by calling the Data Service from a console application, so I created a console application and then added a service reference to the .svc source and then simply able to call the data service.

    class Program
    {
        static void Main(string[] args)
        {
            foreach (var p in new MusicAlbumService(new Uri("http://localhost/ODataSampler.Web/MusicAlbum.svc/")).Albums)
                System.Console.WriteLine(p.Name);
            System.Console.ReadKey();
        }
    }

How easy is that!!

WCF Data Services with an example (OData Sample)

Filed under: C#,OData,Visual Studio,WCF — Prabhuram @ 3:42 am

I did this example with VS2008. Have this pre-requisites in place for working with OData services

  • Visual Studio 2008 with SP1 (required for ADO.NET Entity Model)
  • .NET 3.5 with SP1
  • IIS 7.0 (I was using a Win7 station)
  • Run this command from VS command prompt if you don’t have a HTTP handler for .SVC in IIS.
    %WinDir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\servicemodelreg –i
  • Always have this super tool LINQPad.exe. You guys will need this all the time.

This article is for the novice users to jumpstart, experiment and learn about the ADO.NET Data Services (formerly code named Astoria and called WCF Data Services in .NET 4.0). First create a Web application and add two simple classes.

namespace MyServices
{
    [DataServiceKey("Name")] //To avoid Request Error, introduce a Primary Key
    public class MusicAlbum
    {
        public string Name { get; set; }
        public string Artist { get; set; }
        public int Year { get; set; }
        public MusicAlbum(string Name, string Artist, int Year)
        {
            this.Name = Name;
            this.Artist = Artist;
            this.Year = Year;
        }
    }
    public class MusicAlbumService
    {
        List list = new List(){
            new MusicAlbum("Eagles", "Eagles", 1972),
            new MusicAlbum("Queen", "Queen", 1973)};
        public IQueryable Albums
        {
            get
            {
                return list.AsQueryable();
            }
        }
    }
}

And introduce your Data Service Page by adding ADO.NET Data Service from Add New Item. Make the following changes by introducing the MusicAlbumService as the Data Service.

public class WebDataService : DataService< MusicAlbumService >
{
    public static void InitializeService(IDataServiceConfiguration config)
    {
         config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    }
}

Compile this project and host MusicAlbum.svc. Now we will test this data source in LINQPad, and so we will add a connection to the .svc file.


And note that you can query the database like:

from p in Albums select p

To give a better understanding WCF Data Service is basically an implementation of OData (Open Data Protocol). Also you can make changes to the query like this and execute:

from p in Albums where p.Name == "Eagles" select p

and the reason why I used LINQPad is to show the SQL tab that shows you the SQL equivalent

http://localhost/ODataSampler.Web/MusicAlbum.svc/Albums('Eagles')

As you can see, you can copy the URI and paste it in a browser to see the results over the web.

So you learnt:

  • With in short time you are able to expose a datasource (without a database) to outside world
  • And you are able to achieve this over the web on HTTP as a URI
  • The metadata of the data service is available to the client (that way LINQPad was able to understand about MusicAlbum)
  • Ofcourse it is interoperable
  • A relational data model approach
  • Moreover it allows to apply business logic from the client by including custom filter criterias
  • There are multiple implementation of OData across multiple platforms and for the .NET developers it is part of .NET3.5+

Download the complete VS solution from here: ODataSampler.Web.zip (3.51 mb)

Query against those OData sources that are availableover the internet like eBay, and Netflix.

Older Posts »

Powered by WordPress