Showing posts with label Coding Tips. Show all posts
Showing posts with label Coding Tips. Show all posts

Saturday, September 25, 2010

Set Styles on Gaia Window Control

Recently I had to use one of the coolest controls of Gaia, the Window control which mimics the behavior of a normal desktop Window within the web page. I had some issues with that, when it came to set styles on the layout of the window. They haven’t properly documented about that.

Using Firebug I analyzed the html markup, that rendered by the window control and got to know that you need to maintain separate CSS classes with predefined suffixes (defined by Gaia team) for each main content areas in the window.

For an example if you set the Window CssClass property to “update-line”, then you need to create below CSS classes with predefined suffixes to style the Window layout (only the main content areas described here)


Area

Suffix

CSS Class Example

Whole window

"-window"

update-line-window

Content area

"-window-content"

update-line-window-content

Caption area

"-window-top"

update-line-window-top

Thursday, September 2, 2010

Decorator Pattern

Current project we are working on, they heavily used design patterns in their codebase and when it comes to do the modifications and new enhancements, we must have a good understanding on how the design patterns behave and how we can apply in a real world situation to make it more maintainable and optimizable codebase.

Therefore recently I started to do some research on this and got a clear understanding on the Decorator design pattern initially.This pattern is quite useful when you need to extend an object’s behavior dynamically. This ability to dynamically attach new behavior to objects is done by a Decorator class that wraps itself around the original class.

Following example illustrates the usage of the Decorator pattern and the way I illustrated the example was bit funny and it was an incident recently I experienced.

Let’s take a real world entity called Girl for this example. Every girl has a unique feature Smile. So we can create an interface for the Girl, that specifying we need to implement the Smile:


Now we can create an Office girl (concrete class) using the Girl interface and implement the Smile for the Office girl.


Following creates an instance from OfficeGirl and check the Smile:


The output would be:


Now let’s say there is another office girl who wanted Smile and at the same time she needs to do something else too. Let's say for an example flirting. How she can achieve this?

Now the Decorator pattern is coming to the picture. By using it, we can decorate this office girl to do the flirting thingy at the run time!

Following is how we can achieve this using a Decorator class:


Following creates an instance from OfficeGirl and decorate it via OfficeGirlDecorator and check the Smile:


The output would be:


In this example if you look at the Decorator class, it can invoke just like the original class. In most cases, method calls are delegated to the original class and then the results are acted upon, or decorated, with additional functionality.

Still not got it? For more information visit Gang of Four, Wikipedia

Tuesday, August 24, 2010

Circular Positioning in ASP .Net

In Puzzlepart projects several occasions I had to find a good solution for the circular positioning on html markup. There are many ways to do this and the team wanted to tryout using pure css styles that support in cross browsers.

Below sample code illustrates how to achieve this using css positing styles and the bit of mathematics. It’ll rotate the image based on selected angle.


Page View

Code:
using System;
using System.Drawing;
using System.Web.UI;

namespace RotationTest
{
    public partial class Rotation : Page
    {
        private const double Radius = 155;
        private readonly Point Origin = new Point(190, 195);

        protected string PositionStyle
        {
            get
            {
                var style = "visibility:hidden;";
                if (!string.IsNullOrEmpty(dropDownAngle.SelectedValue))
                {
                    var angle = Convert.ToDouble(dropDownAngle.SelectedValue);
                    var position = GetPointOnCircle(Origin, Radius, angle);
                    style = string.Format(
                            "left: {0}px; top: {1}px;",
                            position.X, position.Y);
                }
                return style;
            }
        }

        private static Point GetPointOnCircle(Point origin, double radius, double angleInDegrees)
        {
            // Convert from degrees to radians via multiplication by PI/180        
            var x = (int)Math.Round(radius * Math.Cos(angleInDegrees * Math.PI / 180.0), 
                                    MidpointRounding.ToEven) + origin.X;
            
            var y = (int)Math.Round(radius * Math.Sin(angleInDegrees * Math.PI / 180.0), 
                                    MidpointRounding.ToEven) + origin.Y;

            return new Point(x, y);
        }
    }
}
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Rotation.aspx.cs" 
    Inherits="RotationTest.Rotation" %>
<head runat="server">
    <title>Rotation Test</title>
head>
<body>
    <form id="form" runat="server">
    <div>
        <div style="width: 400px; height: 402px; background-image: url(circular-image.png);
            background-repeat: no-repeat;">            
            <img src="position-image.png" alt="position image" 
                 style="position: absolute; <%= PositionStyle %>" />                 
        </div>
        Select Angle -
        <asp:DropDownList ID="dropDownAngle" runat="server" AutoPostBack="True">
            <asp:ListItem Selected="True">0asp:ListItem>
            <asp:ListItem>60</asp:ListItem>
            <asp:ListItem>90</asp:ListItem>
            <asp:ListItem>150</asp:ListItem>
            <asp:ListItem>240</asp:ListItem>
            <asp:ListItem>320</asp:ListItem>
        asp:DropDownList>
    div>
    </form>
body>
html> 

Circular Image

Position Image

Saturday, July 3, 2010

Enum to Description

Recently we had an issue with maintaining enum descriptions in our project. The problem was descriptions duplicated several places in codebase and when it came to modify descriptions we had to modify the description everywhere. From the maintainability perspective this not a good practice and we came up with a solution by using the coolest feature Extensions methods that comes with the .NET 3.5. Following is the sample code of the solution.
using System;
using System.ComponentModel;
using System.Reflection;

namespace EnumToDescriptionTest
{
    public static class EnumExtensions
    {
        // Extension method to get the enum description.
        public static string ToDescription(this Enum val)
        {
            Type type = val.GetType();

            string name = Enum.GetName(type, val);
            FieldInfo field = type.GetField(name);

            // Check for the Description Attribute.
            DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(
                                                typeof(DescriptionAttribute), false);

            return attributes.Length > 0 ? attributes[0].Description : name;
        }
    }

    class Program
    {
        // Define the enum with description.
        public enum UserMode
        {
            [Description("Add User")]
            Add = 0,
            [Description("Update User")]
            Update = 1,
            [Description("Delete User")]
            Delete = 2
        }

        static void Main(string[] args)
        {
            // Get the enum description.
            Console.WriteLine(UserMode.Add.ToDescription());
            Console.ReadLine();
        }
    }
}

Saturday, October 18, 2008

Maintain Session Variables in ASP .Net Projects

Most of the ASP .net web projects maintain their session variables in an inconsistent way. Sometimes it’s harder to read and maintain. Here is a best way to maintain session variables in your web project. This will increase the maintainability and readability. 

Approach: Add a new class to the web project and expose session objects as static properties.

1: using System;
2: using System.Web;
3:  
4: namespace SessionTest
5: {
6:     /// 
7:     /// Hold all session variables
8:     /// 
9:     public static class ApplicationSession
10:     {
11:         /// 
12:         /// Hold the search key
13:         /// 
14:         public static string SearchKey
15:         {
16:             get
17:             {
18:                 return Convert.ToString(HttpContext.Current.Session["SearchKey"]);
19:             }
20:             set
21:             {
22:                 HttpContext.Current.Session["SearchKey"] = value;
23:             }
24:         }
25:     }
26: }
 
Web Page
 
1: using System;
2: using System.Web.UI;
3:  
4: namespace SessionTest
5: {
6:     /// 
7:     /// Code behind for the page
8:     /// 
9:     public partial class SessionTest : Page
10:     {
11:         protected void Page_Load(object sender, EventArgs e)
12:         {
13:             if (!IsPostBack)
14:             {
15:                 // Access the session
16:                 string currentSearchKey = ApplicationSession.SearchKey;
17:  
18:                 // Set new value
19:                 ApplicationSession.SearchKey = "Customer";
20:             }
21:         }
22:     }
23: }