ramlicious Blogs by Tina & Prabhu

December 14, 2011

Using Code Blocks to resolve Master Page / Script / CSS issues

Filed under: .NET — Prabhuram @ 12:30 pm

Sometimes you may have to create a web application with multiple folders and the web pages within those folders sharing the same master page. In that case you would have encountered a problem to resolve the css/js files in the style/js folders. This can be overcome using the asp code blocks like this from the master page:

<style type=”text/css”>
@import ‘<%= ResolveUrl(“~/styles/default.css”) %>’;
</style>

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 19, 2011

Getting Started with WebMatrix and ASP.NET Web Pages

Filed under: .NET,Razor,WebMatrix — Prabhuram @ 4:51 pm

Today I put my hands on the new WebMatrix 2 Beta.

WebMatrix is a free web development tool from Microsoft that includes everything you need for website development. Start from open source web applications, built-in web templates or just start writing code yourself. It’s all-inclusive, simple and best of all free. Developing websites has never been easier.

It takes only minutes to install the tool, and you can quickly get started by reading the chapters here. WebMatrix brings in a new concept of developing Web Pages quickly. WebMatrix is the development tool to create web pages. In addition to the development tool itself, it comes with IIS Express, a light-weight version of IIS to run your applications (with its own port number), but with the power and flexibility of IIS (but the applications can be hosted in IIS later for production). Attached is also a compact SQL server database and is part of the application and the instance goes away if the application is shut down.

WebMatrix allows you to create three kinds of applications:

  • A new application starting from scratch
  • An application from an existing folder that you either downloaded or got it from a network folder
  • Creating from one of the existing open source applications like Joomla, WordPress, etc

Development in WebMatrix’s Web Pages are done using the new Razor syntax. it’s the server-size markup language that starts with @. The Razor code is embedded with the HTML pages (cshtml or vbhtml depending on the language used) like how we used to program in classic ASP pages.

I created an web site using an existing template called Photo Gallery. Web Matrix gives quite a few ready-made templates that you can play with.

As you can see the next image, the web matrix has everything in one single GUI editor like site administration, request log, database designer, site explorer, publishing tools, etc. When using the ASP.NET Web Pages Administration for the first time follow the steps and warning information (to rename the _Password.config).

This administration tool helps to install Helper Packages like Facebook, or Twitter. There are quite a handful of packages already. So if you want to put FB’s like button you simply install the package and write a one liner Razor code like this:

@FaceBook.LikeButton();

Guess this will be a good jump start for you guys.

 

Older Posts »

Powered by WordPress