google analytics

Wednesday, December 23, 2009

Dependency Injection with Ninject in .NET

Hello All

From last few months I was not working on .NET platform so haven’t get enough time to write something fruitful on .NET technology. But from last few few days I was thinking to do something with IoC . There are many DI tools to perform DI in .NET but I found Ninject useful as well as light waited and easily implementable. So lets start to make our hand dirty with the Ninject (there are many advanced level use of Ninject library but in this article I will simply show how to do DI with Ninject framework).

My project structure is as following .

In this example I’m taking 2 types of engine and 2 types of set and through Ninject DI I’ll inject one of each for a car. Fore the sake of simplicity I will place the code file accordingly and describe through code comment.

In my “DependencyInjection.Core” project I took 2 interfaces: 1.IEngine  2.ISeat

IEngine.cs is as following :

namespace DependencyInjection.Core
{
   public interface IEngine
    {
       string EngineType(string carName);
    }
}

I’m also taking 2 other classes 1.DieselEngine and 2.PetrolEngine  . Both of the classes implements IEngine interface.
DieselEngine.cs is as following :
namespace DependencyInjection.Core
{
   public  class DieselEngine : IEngine
    {
       public string EngineType(string carName)
       {
           return string.Format("This {0} runs on diesel.", carName);
       }
    }
}

PetrolEngine.cs is as following :
namespace DependencyInjection.Core
{
  public class PetrolEngine : IEngine
    {
        public string EngineType(string carName)
        {
            return string.Format("This {0} runs on petrol.", carName);
        }
    }
}

Now start for another type of interface implementation ISeat . This part also is as above.
ISeat.cs is as following :
namespace DependencyInjection.Core
{
   public interface ISeat
    {
       string SeatType(string carName);
    }
}

Two other classes 1.LeatherSeat and 2.PlasticSeat  . Both of the classes implements ISeat interface.
LeatherSeat.cs is as follwong:
namespace DependencyInjection.Core
{
   public class LeatherSeat : ISeat
    {
        #region ISeat Members

        public string SeatType(string carName)
        {
          return string.Format( "This {0}'s seats are of leather.",carName);
        }

        #endregion       
    }
}

PlasticSeat.cs is as following :
namespace DependencyInjection.Core
{
   public class PlasticSeat : ISeat
    {
        #region ISeat Members

        public string SeatType(string carName)
        {
            return string.Format("This {0}'s seats are of plastic.", carName);
        }

        #endregion
    }
}

In this point I’m adding reference of “Ninject.Core.dll” with my  “DependencyInjection.Core” project which I have downloaded from Ninject’s site. Now in my main class “Car” I’m going to inject one type of engine and another type of seat which I have mapped (DI mapping) through “IocMapper” class as bellow.
Car.cs is as bellow :
using Ninject.Core;

namespace DependencyInjection.Core
{
    public class Car
    {
        public IEngine CarEngine { get; set;}
        public ISeat   CarSeat   { get; set;}

        [Inject]
        public Car(IEngine engine , ISeat seat)
        {
            CarEngine   = engine;
            CarSeat     = seat;
        }

        
        public string GetEngineInformation(string carName)
        {
           return CarEngine.EngineType(carName);
        }


        public string GetSeatInformation(string carName)
        {
            return CarSeat.SeatType(carName);
        }
    }
}

In the above file  “ [Inject] “ attribute is place above the Car constructer to make it definable to Ninject so that Ninject can inject mapped object as described in “IocMapper” class.
I have taken another console application project named “DependencyInjection” in which I placed my “IocMapper” class.
IocMapper.cs is as following :
using Ninject.Core;

using DependencyInjection.Core;

namespace DependencyInjection
{
    public class IocMapper : StandardModule
    {
        public override void Load()
        {
            Bind<IEngine>().To<DieselEngine>();
         
            Bind<ISeat>().To<LeatherSeat>();
        }
    }
}

Now in program class I defined the kernel constructer and and initialize my car object.
Program.cs file is as bellow :
using System;
using Ninject.Core;
using DependencyInjection.Core;

namespace DependencyInjection
{
    class Program
    {
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel(new IocMapper());

            Car car = new Car(kernel.Get<IEngine>(), kernel.Get<ISeat>());

            Console.WriteLine(car.GetEngineInformation("Toyota"));
           
            Console.WriteLine(car.GetSeatInformation("BMW"));
            
            Console.ReadKey();

        }
    }
}

We can do more advance level of conditional binding with Ninject. Hope in near future I will throw a post on advance use of Ninject.
That’s all for today.
BYE

Friday, November 13, 2009

.NET application logging with Log4net in Console , File & Database

Hello All

Today I will go through logging with Log4net. Log4Net is a logging framework ( a rich library) for .NET. Log4Net is popular for its simplicity and robustness. We can write log in various way though we generally write log only in file we we can also mail log, show in console,save in datatbase as well as write in file in different ways.

First we have to download the Log4Net and add the log4net.dll in our implementation project. In the example I have take 2 projects named LogWriter and LogRunner accordingly, In one project I have implemented the logging and in another I execute that logging method.

My project structure is as image bellow :

In the LogWriter I have take two class as bellow :

LogLevel.cs: In this class I simply define a enum which basically helps to define my log level in my LogUtil class.

namespace LogWriter
{
    public enum LogLevel
    { 
        DEBUG,
        ERROR,
        FATAL,
        INFO,
        WARN    
    }
}

LogUtil.cs: In this class I have a static method named WriteLog which take 2 parameters one define log level and another take log message as string.

using log4net;
using log4net.Config;

namespace LogWriter
{
    public static class LogUtil
    {
        private static ILog logger = LogManager.GetLogger(typeof(LogUtil));

        static LogUtil()
        {
            XmlConfigurator.Configure();
        }

        public static void WriteLog(LogLevel logLevel,string log)
        {
            if (logLevel.Equals(LogLevel.DEBUG))
            {
                logger.Debug(log);
            }
            else if (logLevel.Equals(LogLevel.ERROR))
            {
                logger.Error(log);
            } 
            else if (logLevel.Equals(LogLevel.FATAL))
            {
                logger.Fatal(log);
            } 
            else if (logLevel.Equals(LogLevel.INFO))
            {
                logger.Info(log);
            } 
            else if (logLevel.Equals(LogLevel.WARN))
            {
                logger.Warn(log);
            }             
        
        }
    }
}

As I am writing a  console application so my mail runner file is Program.cs which is as bellow but you can follow the same procedure in different place as per you requirement.

using System;
using LogWriter;

namespace LogRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            try {
                throw new Exception();
            }

            catch (Exception exc)
            {
                    LogUtil.WriteLog(LogLevel.DEBUG, "Debug mode logging");
                    LogUtil.WriteLog(LogLevel.ERROR, "Error mode logging");
                    LogUtil.WriteLog(LogLevel.FATAL, "Fatal mode logging");
                    LogUtil.WriteLog(LogLevel.INFO, "Info mode logging");
                    LogUtil.WriteLog(LogLevel.WARN, "Warn mode logging");
    
                    Console.ReadKey();
            }
        }
    }
}

Now one of the most important thing I will focus is log4net configuration. We can configure it from web.config or app.config . In my example I have configured it app.config file in my LogRunner project. In the app.config file follow the commented section.

My configuration file is as bellow , please go through the commented line to get know in detail such as log file rolling, max log file number & size, Log level etc.
<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <configSections>

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

    </configSections>


    <log4net>

        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">

            <!-- Log file locaation -->
            
            <param name="File" value="C:\Users\sanzeeb\Documents\Visual Studio 2008\Projects\Solution1\LogWriter\Log\" />

            <param name="AppendToFile" value="true" />

            <!-- Maximum size of a log file -->
            <maximumFileSize value="2KB" />

            <!--Maximum number of log file -->
            <maxSizeRollBackups value="8" />

            <!--Set rolling style of log file -->
            <param name="RollingStyle" value="Composite" />

            <param name="StaticLogFileName" value="false" />

            <param name="DatePattern" value=".yyyy-MM-dd.lo\g" />

            <layout type="log4net.Layout.PatternLayout">

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

        <!-- Appender layout fix to view in console-->
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >

            <layout type="log4net.Layout.PatternLayout">

                <param name="Header" value="[Header]\r\n" />

                <param name="Footer" value="[Footer]\r\n" />

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

      
        <!-- Database appender -->

        <!--
        You need to create a table as bellow to insert log in database for MSSQL server.
        
        CREATE TABLE [dbo].[Log] (
        [Id] [int] IDENTITY (1, 1) NOT NULL,
        [Date] [datetime] NOT NULL,
        [Thread] [varchar] (255) NOT NULL,
        [Level] [varchar] (50) NOT NULL,
        [Logger] [varchar] (255) NOT NULL,
        [Message] [varchar] (4000) NOT NULL,
        [Exception] [varchar] (2000) NULL
        )
        -->

        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <bufferSize value="100" />
            <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <connectionString value="Data Source=SANZEEB-PC\SQLEXPRESS;Initial Catalog=AppTesterDB;Integrated Security=True" />
            <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
            <parameter>
                <parameterName value="@log_date" />
                <dbType value="DateTime" />
                <layout type="log4net.Layout.RawTimeStampLayout" />
            </parameter>
            <parameter>
                <parameterName value="@thread" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%thread" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@log_level" />
                <dbType value="String" />
                <size value="50" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%level" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@logger" />
                <dbType value="String" />
                <size value="255" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%logger" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@message" />
                <dbType value="String" />
                <size value="4000" />
                <layout type="log4net.Layout.PatternLayout">
                    <conversionPattern value="%message" />
                </layout>
            </parameter>
            <parameter>
                <parameterName value="@exception" />
                <dbType value="String" />
                <size value="2000" />
                <layout type="log4net.Layout.ExceptionLayout" />
            </parameter>
        </appender>

        <root>

            <level value="DEBUG" />

            <!--
            Log level priority in descending order:
            
            FATAL = 1 show  log -> FATAL 
            ERROR = 2 show  log -> FATAL ERROR 
            WARN =  3 show  log -> FATAL ERROR WARN 
            INFO =  4 show  log -> FATAL ERROR WARN INFO 
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->

            <!—To write log in file -->
            <appender-ref ref="LogFileAppender" />

            <!--To view log in console -->
            <appender-ref ref="ConsoleAppender" />
            
            <!--To write log in file batabase -->
            <appender-ref ref="AdoNetAppender" />

        </root>

    </log4net>

</configuration>

Hope this will help to improve your logging in your .NET application.

Thanks

That’s all for today.

BYE

Friday, August 21, 2009

ULM Class Diagram

Hello All

Today I will go through with UML class diagram. It’s like old wine in old bottle ;) . We all know that these are very basic but now a days people just stat to do coding without making any class or activity diagram, so eventually they fall in a design related issue if the system becomes huge.

Again UML is more impotent to understand any complex system which is properly documented in UML diagram.UML makes our life simple through notifying us the design fault.

So let’s start the old song again.

Class:

Generally there are 3 components in the class icon as following.

1. Class Name

2. Attributes

3. Functions / Methods

Visibility:

Visibility of class diagram represents the accessibility of the class members. Visibility notations are as bellow .

Notations

Access type

-

Private

+

Public

~

Protected

Association:

When two objects are connected with each other then it can be represent as association. For students and seminar we can use association notation where students are attending in seminar.

Multiplicity Indicators:

Multiplicity indicates the countable objects relation with other objects.

Indicator

Meaning

0..1

Zero or one

1

One only

0..*

Zero or more

1..*

One or more

n

Only n (where n > 1)

0..n

Zero to n (where n > 1)

1..n

One to n (where n > 1)

Composition:

Composition represents with a black diamond. It represents that a component strongly depends on another component. Suppose we have two objects one is circle and another is point. In that case a circle consists of many points.

Aggregation:

When an object form with another object(s) but not mandatory to form the main object then its denoted by a diamond. Suppose student and school object can represent with aggregation relationship.

Inheritance:

When one object inherits property from any parent object then the sign denoted with a triangle shape arrow.

Thanks

That's all for the day.
BYE

User ScrumPad for your Agile based projects.

Saturday, July 25, 2009

Agile Scrum and traditional software development ( SDLC ) terms.

Hello All

Few days back our boss focused on how to map the traditional software development term with Agile development term as a result I think it will be a good topic to discus and share our thoughts. We Agile practitioner always use some terms such as sprint, product backlog, burn-down chart etc. But people who are not used to Agile can hardly understand these terms where as these things are similar as traditional SDLC terms.

Today I will try to focus some of this Agile terms and try to make a equivalent SDLC terms, so that people can adopt the Agile practice easily.

In this post I will follow Scrum framework for the Agile development. There are some other Agile framework such as AUP,XP,FDD etc.

Agile Development Process:

In the following picture (it’s an Agile development process) we can see some agile terms such as Product backlog, Sprint Backlog, sprint and there are also some other terms like product owner, scrum master, daily scrum meeting, velocity, retrospective etc.

Roles:

Product Owner: Product owner is the client. According to their order the software will develop and they will clarify the requirement for the developers so that developers can develop the exact efficient software for the customer.

Scrum Master: Scrum master plays a similar type of role as project manager. But as the Agile team is self organized so scrum master doesn’t involve deeply in a project as traditional project manager. Scrum master takes initiative on the impediments and managing the process working perfectly so that the goal meets in the desired time frame (sprint).

Teams: In general a team means group of self organized developers who will develop the software.

Projects Terms:

Product backlog: Product backlog is the collection of requirements of a system. This requirements are placed according to the development priority, so that the high priority requirements are develop in the early phases.

Sprint: Sprint is like the time frame of an incremental development process. In a sprint the team fixes what to do in this cycle and deployment. Developers develop a deliverable product in a sprint and deploy it in client end. Once the tasks are fixed for a sprint the developer should not be interrupt with additional requirement and mass requirement change. If it’s necessary, the tasks will add in product backlog with high priority so that they can add in next sprint’s planning.

Sprint backlog: Sprint backlog is the set of high priority tasks taken from the set of product backlog which will develop in the current sprint and deploy in client end.

Scrum meeting: Scrum meeting is a daily short standing meeting where each team member will express what problem(s) s/he has faced last day and what s/he will do today. This meeting is extremely focused.

Retrospective: At the last day the team will discussed what went good what went band and what are the opportunity so that in the next sprint they can take initiative according to the retrospective.

Burndown chart: There are different types of burndown charts. Which represents the development process through graph, so that an Agile team member can get to know what project’s condition in a simple view.

Velocity: An agile team can estimate how much effort they can put in product backlog for one sprint. This velocity is determined from previous sprint’s average data. This velocity can be used to predict the project effort planning and team's productivity .

Thanks

That's all for the day.
BYE

User ScrumPad for your Agile based projects.

Saturday, June 13, 2009

LinkButton ,Label inside Repeater - ASP.NET

Hello All

Today I will show you how to fire  Link Button's event with argument and initialize a label inside of a repeater. To do that first we have to take LinkButton and a Label control inside the ItemTemplate of the repeater. Then we have to initialize the the Label from OnItemDataBound event of the repeater. In the following code blocks its shown how to perform the job.

Following is my Default.aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestProject._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Selected ID:<asp:Label ID="lblSelectedID" runat="server" Text=""></asp:Label>
        <br />
        <asp:Repeater ID="rptContent" runat="server" OnItemDataBound="rptContent_ItemDataBound">
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server">
                </asp:Label>
                <asp:LinkButton ID="lnkShowData" runat="server" OnCommand="LinkButton_Command" CommandArgument='<%# Eval("key") %>'
                    Text="[Show]" CommandName="Show"></asp:LinkButton>
                <br />
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

In the above code I have bind the "key" as CommandArgument in LinkButton which will be initialize form the code behind file.

My code behind is as following:

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestProject
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            rptContent.DataSource = this.userInformation();
            rptContent.DataBind();
        }

       // Fire the link button event from inside repeater.
       protected void LinkButton_Command(object sender, CommandEventArgs e)
        {
           lblSelectedID.Text = e.CommandArgument.ToString();
        }

        protected void rptContent_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            // find the label control by id
            Label lblDynaLabel = (Label)(e.Item.FindControl("lblName"));


            // bind the data from repeater data source (value from the dictionary)with the label control.
            lblDynaLabel.Text = DataBinder.Eval(e.Item.DataItem,"value").ToString();
        }

        #region Private method

        private Dictionary<int, string> userInformation()
        {
            Dictionary<int, string> userData = new Dictionary<int, string>();

            userData.Add(1, "Max");
            userData.Add(2, "Top");
            userData.Add(3, "Avg");

            return userData;
        }
        #endregion
    }
}

The output will be as bellow:

Selected ID:1
Max [Show]
Top [Show]
Avg [Show]

In the private method section I have created a simple mathod named userInformation, which contains dictionary data collection to bind it with repeater.Hope that above code blocks will help.

Thanks

That's all for the day.
BYE

User ScrumPad for your Agile based projects.

Thursday, May 28, 2009

Print C# properties in aspx,ascx page from code behind file.

Hello all

Today I will show you how to print something in aspx or ascx page from code behind file.In this example I have taken a “Web User Control” named “WebUserControl.ascx”. What I wanted to do was, print a value of a variable in “.ascx” page where the variable has been initialize from “.ascx.cs” better to say code behind file.

To do that we have taken a property in “WebUserControl.ascx.cs” code behind file named “PrintValue” and make it a public property and assign a string value on PageLoad event as bellow :

using System;

public partial class WebUserControl : System.Web.UI.UserControl
{
    public string PrintValue { get; set; }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            PrintValue = "Postback";
        else
            PrintValue = "Not postback";
    }
}

Now I have printed the value of the property in my “WebUserControl.ascx” page as bellow.One thing we have to remember that the script tag should be like : <%= %> to print something in it.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

The page has - <%= PrintValue %>

Now we can use the control in our page to show the state of the page.
Thats all for today.
Bye
User ScrumPad for your Agile based projects.

Monday, May 4, 2009

File streaming in .NET

Hello All

Today i will focus on simple file steaming in .NET which I have to implement it in one of my project.Though it’s not optimize but its OK for serve small purpose.

In the project I have to read a PDF file from the server and with FileStream and Flash it with Response to the client side.

the code is as bellow.

private void generateRequestedPDF()
{
    try
    {
        string file = Path.GetFileName(Request.QueryString["RefID"]);// get file name from query string.use your custom method." 

        FileStream fileStream = new FileStream(Server.MapPath(@"~\uploadedFiles\" + file), FileMode.Open);
        long fileSize = fileStream.Length;

        byte[] buffer = new byte[(int)fileSize];
        fileStream.Read(buffer, 0, (int)fileSize);
        fileStream.Close();

        Response.Clear();

        Response.ContentType = "Application/pdf";// use your custom type"
        Response.AddHeader("Content-Disposition", "inline; filename=" + file);

        Response.OutputStream.Write(buffer, 0, (int)fileSize);
        Response.Flush();
        Response.Close();
    }
    catch (Exception exc)
    {
    //  throw exc;
        this.writeLogWarn(exc);
        Response.Redirect("~/Pages/Content/TechCorner.aspx");
    }
   
}
thats all for today.
BYE

User ScrumPad for your Agile based projects.

Saturday, April 11, 2009

Consume WCF Service

Hello all

Today I will show how to consume a WCF service. To go through this before, I have created a WCF service [ Creating WCF Service ] , which I will consume for my project in this article. Consuming WCF Service is as simple as consuming a simple webservice through Visual Studio 2008.

First I am taking an empty Web project named ConsumedWCF.

Now I will add a service reference which I have created before [ Creating WCF Service ] in this ConsumedWCF project as bellow:

In my previously created WCF service I have got a URL for my service "http://localhost:49530/DataService.svc?wsdl", I have pasted the URL in the Address box. One thing we should have to remember that,to consume the service we have to run that service during development.

Now I will consume the service from my Default.aspx  . My Default.aspx.cs content is as bellow:

using System;
using ConsumeWCF.ServiceReference1;

namespace ConsumeWCF
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           DataServiceClient cl = new DataServiceClient();
           Response.Write( cl.GetUserDataFromService().UserName);
           Response.Write("<br />");
           Response.Write(cl.GetUserDataFromService().UserLocation);
           Response.Write("<br />");
           Response.Write(  cl.GetUserRestrictionFromService("1"));
           Response.Write("<br />");
           Response.Write(cl.GetUserRestrictionFromService("23"));
           
        }
    }
}

The above code will print the values which we have consumed form the WCF service.

Thanks

That's all for the day.
BYE

User ScrumPad for your Agile based projects.

Tuesday, March 31, 2009

Creating WCF Service

Hello all

Today I will try to demonstrate how to create simple web service through WCF. To get into WCF first we have to know some basic principal of WCF and its "ABC".

Address : the location of the service.

Bind: how to get service.

Contract: service action.

In this tutorial I will not describe details about WCF.My basic focus will be on creating a WCF service through Visual Studio 2008

First open a new WCF project:

In my sample project I have named "TestWCFService" for creating the service.

In the solution explorer you will found IService1.cs interface , Service1.svc file and a code behind file Service1.svc.cs

In my project I have renamed those as IDataService.cs, DataService.svc and DataService.svc.cs accordingly. To change the markup file of DataService.svc right click on the DataService.svc file in solution explorer and press "View Markup" as bellow

and change the Service according to you code as bellow.

<%@ ServiceHost Language="C#" Debug="true" Service="TestWCFService.DataService" CodeBehind="DataService.svc.cs" %>

In the solution my IDataSevice.cs is as bellow:

using System.Runtime.Serialization;
using System.ServiceModel;

namespace TestWCFService
{
    
    [ServiceContract]
    public interface IDataService
    {

        [OperationContract]
        UserInformation GetUserDataFromService();

        [OperationContract]
        string GetUserRestrictionFromService(string userID);
        
        // TODO: Add your service operations here
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class UserInformation
    {

        [DataMember]
        public string UserName { get; set; }

        [DataMember]
        public string UserLocation { get; set; }

      
        public string UserRestriction(int userID)
        {
            if (userID.Equals(1))
                return "approve";
            else
                return "rejected";
        }
       
    }
}

My DataService.svc.cs file is as bellow :

using System;

namespace TestWCFService
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class DataService : IDataService
    {
        #region IDataService Members

        public UserInformation GetUserDataFromService()
        {
            return new UserInformation() { UserName = "Tanvir", UserLocation = "Dhaka" };
        }

        public string GetUserRestrictionFromService(string userID)
        {

            UserInformation userInformation = new UserInformation();

            if (userInformation.UserRestriction(Int32.Parse(userID)).Equals("approve"))
                return String.Format("your user id is {0} and you are approved", userID);
            else
                return String.Format("your user id is {0} and you are not approved", userID);

        }

        #endregion
    }
}

And the most important thing is to change in system.servieModel section in Web.config file as bellow :

<system.serviceModel>
        <services>
            <service name="TestWCFService.DataService" behaviorConfiguration="TestWCFService.Service1Behavior">
                <!-- Service Endpoints -->
                <endpoint address="" binding="wsHttpBinding" contract="TestWCFService.IDataService">
                    <!-- 
              Upon deployment, the following identity element should be removed or replaced to reflect the 
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 
              automatically.
          -->
                    <identity>
                        <dns value="localhost"/>
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="TestWCFService.Service1Behavior">
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>

We have to change the underline and bold section up above according to you code and naming in our solution.

Thanks

That's all for the day.
BYE

User ScrumPad for your Agile based projects.

Wednesday, February 25, 2009

Custom Event in .NET

Hello All,

Today I will try to deliberate my experience on custom event creation in .NET , Actually I was trying to find something like hands on for event creation in .NET application, suddenly I got a quick help from one of my brother Sadique, who helped me out to resolve the thirst.

We are going to create a custom control where we will define our event class and event handler.To do that first take a  user control named InputControl.ascx  . The ascx page is as bellow.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="InputControl.ascx.cs" Inherits="InputControl" %>
<asp:Label ID="lblLabel" runat="server" Text=""></asp:Label>
    <br />
<asp:TextBox ID="txtTextBox" runat="server"></asp:TextBox>
    <br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" 
    onclick="btnSubmit_Click" />

In that page I put a textbox control to take input , a button control to fire our custom event handler and a label to show our input result through our custom event.

The InputControl.ascx.cs code behind file is as bellow :
using System;

public partial class InputControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public string EventInputBox
    {
        get {
                return this.txtTextBox.Text;
            }
        set {
                this.txtTextBox.Text = value;
            }
    }

    public string EventLabel {
        get {
                 return this.lblLabel.Text;
            }
        set {
                 this.lblLabel.Text = value;
            }
    }

    public event EventHandler<CustomEventArgs> CustomEventSubmit;
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (this.CustomEventSubmit != null)
            this.CustomEventSubmit(this, new CustomEventArgs("your text is:" + EventInputBox));
    }

}

public class CustomEventArgs : EventArgs
{
    public string EventText { set; get; }

    public CustomEventArgs(string eventTextData)
    {
        EventText = eventTextData;

       
        /*
         Perform other event tasks.
         
         */
    }
}

Now I register the control in my Default.aspx page as bellow .

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register src="InputControl.ascx" tagname="InputControl" tagprefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:InputControl ID="icEventBox" runat="server" OnCustomEventSubmit="icEventBox_CustomEventSubmit"  />
    </div>
    </form>
</body>
</html>

In the file above we have to focus on OnCustomEventSubmit="icEventBox_CustomEventSubmit" which is pointing our custom event.

The code behind file Default.aspx.cs is as bellow.

using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void icEventBox_CustomEventSubmit(object sender, CustomEventArgs e)
    {
        icEventBox.EventLabel = e.EventText;
    }
}

In the above article I didn't go for much brief discussion , I think the code is sufficient to describe a custom event itself.

That's all for the day.
BYE

User ScrumPad for your Agile based projects.