A fun with CheckBoxList, Lambda Expression and SelectedItem

Friend of mine wanted to select the items of CheckBoxList based on the value from a Enum List. Then I thought I should try. This article is about that. So what I did I created a simple website with a default page and CheckBoxList in the page. On the page load event the list will be populated based on the value in the List.

The code I wrote is as below,

Default.aspx page

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication2._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:CheckBoxList ID="cboList" runat="server">
        <asp:ListItem Text="One" Value="One"></asp:ListItem>
        <asp:ListItem Text="Two" Value="Two"></asp:ListItem>
        <asp:ListItem Text="Three" Value="Three"></asp:ListItem>
    </asp:CheckBoxList>
</asp:Content>


and the code behind for the Default.aspx is as below,

namespace WebApplication2
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
 
    public partial class _Default : Page
    {
        public enum MyEnum
        {
            One,
            Two,
            Three
        };
 
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            IList<MyEnum> myEnums = new List<MyEnum>();
            myEnums.Add(MyEnum.One);
            myEnums.Add(MyEnum.Three);
 
            UsingQueryExpression(myEnums);
            UsingGenericLambdaExpression(myEnums);
            UsingLambdaExpression(myEnums);
        }
 
        private void UsingQueryExpression(IList<MyEnum> myEnums)
        {
            var temp = (from listItem in cboList.Items.Cast<ListItem>()
                       join myEnum in myEnums on listItem.Value equals myEnum.ToString()
                       select (listItem.Selected = true)).ToList();
        }
 
        private void UsingGenericLambdaExpression(IList<MyEnum> myEnums)
        {
            var temp = cboList.Items.Cast<ListItem>()
                .Join(
                myEnums,
                listItem => listItem.Value,
                myEnum => myEnum.ToString(),
                ((listItem, myEnum) => listItem.Selected = true)
                ).ToList();
        }
 
        private void UsingLambdaExpression(IList<MyEnum> myEnums)
        {
            var temp = cboList.Items.Cast<ListItem>()
                .Join<ListItemMyEnumstringListItem>(
                myEnums,
                listItem => listItem.Value,
                myEnum => myEnum.ToString(),
                ((myEnum, listItem) => myEnum))
                .Select(selectedListItem => selectedListItem.Selected = true).ToList();
        }
    }
}


happy to learn from others.

Thanks
mohammad

Multi items Return from a Method

Tonight I was watching a TV show on YouTube. Suddenly one thing just come up my mind. I can accept multiple items as input parameter in a method, how can I get multiple items back from a Method as return.
So after a little bit thinking I found few ways, for example define a type with return items or define a anonymous type with return items and then return this anonymous type from that Method.

The code I wrote for this is as below,

namespace MultiItemsReturn
{
    using System;
    using System.Runtime.InteropServices;
    class Program
    {
        static void Main(string[] args)
        {
            ReturnTester returnTester = new ReturnTester();
            var areaUsingDynamic = returnTester.AreaModifierUsingDynamic(10, 12);
            var areaUsingType = returnTester.AreaModifierUsingType(10, 12);
            Console.WriteLine("{0} - {1}, {2}, {3}", areaUsingDynamic.description, areaUsingDynamic.height, areaUsingDynamic.width, areaUsingDynamic.area);
            Console.WriteLine("{0} - {1}, {2}, {3}", areaUsingType.Description, areaUsingType.Height, areaUsingType.Width, areaUsingType.TotalArea);
        }
    }
 
    public class ReturnTester
    {
        public const string ReturnTesterDescription = "Mutltiple items returns";
        private const int proportion = 100;
 
        public ReturnTester() { }
 
        public dynamic AreaModifierUsingDynamic(int width, int height, string description = ReturnTester.ReturnTesterDescription)
        {
            return new
            {
                width = width * proportion,
                height = height * proportion,
                area = width * height,
                description = description
            };
        }
 
        public Area AreaModifierUsingType(int width, int height, string description = ReturnTester.ReturnTesterDescription)
        {
            return new Area
            {
                Width = width * proportion,
                Height = height * proportion,
                TotalArea = width * height,
                Description = description
            };
        }
    }
 
    public class Area
    {
        public int Width { getset; }
        public int Height { getset; }
        public int TotalArea { getset; }
        public string Description { getset; }
    }
}

The output of the code is as below,


Mutltiple items returns - 1200, 1000, 120
Mutltiple items returns - 1200, 1000, 120
Press any key to continue . . . .


happy to learn from others.

Thanks
mohammad

Windows Communication Foundation - How to create a WCF Service contracts, Service, Service Proxy and consume a service from client application.

I was trying to write something about WCF service, How to create a service, service contract, service proxy and consume that service a client application.
The situation is I  am going to implement is , service will implement a GeometryService. This service will implement How to calculate Area. So from client user will send height and width to the service and service will calculate the area and send back the result to the client.

The architecture of this article's example will be as below,

Fig: Architecture diagram of the example.

So in this example I going to implement following components,

  1. GeometryContracts.dll (implemented as class library)
  2. GeometryServices.dll (implemented as class library)
  3. GeometryServicesHost (implemented as WCF application)
  4. GeometryServiceProxy.dll (implemented as class library)
and a test program named TestHarness.exe. 

GeometryContracts.dll will define all the contracts which will be used by the GeometryServices.dll. GeometryServices.dll will be host on IIS using GeometryServicesHost WCF application.  GeometryServicProxy.dll will be implemented using GeometryContracts.dll and ClientBase class of System.ServiceModel and will be used by Client application in this example TestHarness.exe application. So the following sequence diagram shows how the client application TestHarness.exe will use GeometryContracts.dll and GeometryServiceProxy.dll to consume the GeometryServices via IIS.




Fig: The sequence diagram, How client consume services via Proxy and Contracts.

Before we further just  have a quick look the structure of the solution,

GeometryContracts.dll class library will implement following types,

  • Data contract named Area.cs
  • Service contract ISurfaceArea.cs

GeometryServices.dll class library will implement following types as service which will implement the service definition ISurfaceArea.cs,

  • SurfaceAreaService.cs

GeometryServicesHost Wcf Application will have following files

  • SurfaceAreaService.svc
  • Web.config

GeometryServiceProxy.dll  will implmented following files,

  • SurfaceAreaServiceProxy.cs

TestHarness console application will be implemented  following files,

  • Program.cs
  • App.config

All the code is now I am going to include below,

GeometryContracts  created as class library project with following source code, when created this library I have add references following assembly,

System.Runtime.Serialization and
System.ServiceModel
Area.cs
namespace GeometryContracts
{
    using System.Runtime.Serialization;
    [DataContract]
    public class Area
    {
        [DataMember]
        public decimal Height { getset; }
        [DataMember]
        public decimal Width { getset; }
 
    }
}
ISurfaceArea.cs

namespace GeometryContracts
{
    using System.ServiceModel;
    [ServiceContract]
    public interface ISurfaceArea
    {
        [OperationContract]
        decimal CalculateArea(Area area);
    }
}


GeometryServices.dll created as a class library with following assembly references
System.ServiceModel and project references GeometryContracts the one I just created above. This library will have following source code,
SurfaceAreaService.cs
namespace GeometryServices
{
    using System;
    using GeometryContracts;
    public class SurfaceAreaService : ISurfaceArea
    {
        #region ISurfaceArea Members
 
        public decimal CalculateArea(Area area)
        {
            return area.Width * area.Height;
        }
        #endregion
    }
}



GeometryServicesHost Wcf application hosted on the local (the one comes with OS by default) IIS  and it will implement following source code,
SurfaceAreaService.svc


<%@ ServiceHost Language="C#" Debug="true" Service="GeometryServices.SurfaceAreaService" %>
There wont be any C# class file for the above file.
Web.Config
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="GeometryServices.SurfaceAreaService">
        <endpoint address="" binding="basicHttpBinding" contract="GeometryContracts.ISurfaceArea">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>



GeometryServiceProxy.dll will implemet the proxy for the client. This class library will have System.ServieModel as assembly reference and GeometryContracts.dll as project reference. This library will implement following files,


GeometryServiceProxy.cs
namespace GeometryServiceProxy
{
    using System.ServiceModel;
    using GeometryContracts;
 
    public class SurfaceAreaServiceProxy : ClientBase<ISurfaceArea>, ISurfaceArea
    {
        #region ISurfaceArea Members
        public decimal CalculateArea(Area area)
        {
            return base.Channel.CalculateArea(area);
        }
        #endregion
    }
}

So the service has been created and hosted on IIS. I will consume the service from the client application TestHarness.exe. This TestHarness is console application. This application will have GeometryContracts.dll and GeometryServiceProxy.dll as projects reference and with following source code,

Program.cs

namespace TestHarness
{
    using System;
    using GeometryServiceProxy;
    using GeometryContracts;
    class Program
    {
        static void Main(string[] args)
        {
            Area area = new Area();
            area.Height = 2;
            area.Width = 3;
            SurfaceAreaServiceProxy proxy = new SurfaceAreaServiceProxy();
            Console.WriteLine(proxy.CalculateArea(area));
        }
    }
}

and the App.config file with following contents
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <client>
      <endpoint address="http://localhost/GeometryServicesHost/SurfaceAreaService.svc"
       binding="basicHttpBinding" bindingConfiguration=""
       contract="GeometryContracts.ISurfaceArea" name="basicEndPoint" />
    </client>
  </system.serviceModel>
</configuration>

I have completed the Service and Client side. When I run the application it will give output as below,

6.
This is just a simple application where I tried to show how to create and consume a WCF service. Happy to learn ideas from others.

Thanks
mohammad

Generic Enum Parser.

The situation was something like, I have a CheckBoxList and it contains 10 List item with Item Text and Item Value. So when the user will select the Items I need to pass those value to the service layer. There is a corresponding Enum which contains all the CheckBoxList's items Value as Enum member. So when I will pass the selected to value to the service layer I need to pass as List of Enums.

To get the Enums which will represent the selected items of CheckBoxList, it requires a switch statement to state compiler if CheckBoxList's SelectedItem.Value is aaaa then return Enum.aaaa for example.

As a result if my CheckBoxList has items 20 then Enum has to have 20 items and switch statement has to implement 20 case statements.

Then I realize why don't I use a Generic Enum Parser, following code is just a example of what I did for that,

The Code is below,


namespace TestHarness
{
    using System;
    class Program
    {
        static void Main(string[] args)
        {
            GenericEnumParser genericEnumParser = new GenericEnumParser();
            genericEnumParser.Test();
        }
    }
 
    public class GenericEnumParser
    {
        public enum ListEnumOne
        {
            None,
            One,
            Two,
            Three
        }
        public enum ListEnumTwo
        {
            None,
            One,
            Two,
            Three
        }
 
        public void Test()
        {
            Console.WriteLine("{0}", ParseEnum("One").ToString());
 
            Console.WriteLine("{0}", ParseEnum<ListEnumOnestring>("Two").ToString());
            Console.WriteLine("{0}", ParseEnum<ListEnumTwostring>("Two").ToString());
        }
 
        public ListEnumOne ParseEnum(string item)
        {
            switch (item)
            {
                case "One":
                    return ListEnumOne.One;
                case "Two":
                    return ListEnumOne.Two;
                case "Three":
                    return ListEnumOne.Three;
            }
            return ListEnumOne.None;
        }
 
        public T1 ParseEnum<T1, T2>(T2 item)
        {
            if (string.IsNullOrEmpty(item.ToString()))
                return default(T1);
            else
            {
                return (T1)Enum.Parse(typeof(T1), Convert.ToString(item.ToString()), false);
            }
        }
    }
}

the output of the above example is as below,

One
Two
Two
Press any key to continue . .
.


Happy to get ideas from others.

Thanks mohammad

String Concatenation - few ways which most of us already knew.

There are many discussion about String Concatenation. In this article I am trying to address some known way to concat .Net string.

  • using Concat() method of String class
  • using Join() method of String class
  • using StringBuilder class
  • using Concatenation Operator (+)

I wrote a class(StringJoin) which is implemented all of the above points,

public class StringJoin
{
        public StringJoin() { }
 
        public string JoinUsingConcat(string firstItem, string secondItem)
        {
            return string.Concat(values: new[] { firstItem, secondItem });
        }
        public string JoinUsingConcat(string[] items)
        {
            return string.Concat(values: items);
        }
 
        public string JoinUsingJoin(string firstItem, string secondItem)
        {
            return string.Join(separator: string.Empty, value: new[] { firstItem, secondItem });
        }
        public string JoinUsingJoin(string[] items)
        {
            return string.Join(separator: string.Empty, value: items);
        }
 
 
        public string JoinUsingBuilder(string firstItem, string secondItem)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(value: firstItem).Append(value: secondItem);
            return builder.ToString();
        }
        public string JoinUsingBuilder(string[] items)
        {
            StringBuilder builder = new StringBuilder();
            foreach (string item in items)
                builder.Append(value: item);
            return builder.ToString();
        }
 
        public string JoinUsingConcatenationOperator(string firstItem, string secondItem)
        {
            return firstItem + secondItem;
        }
        public string JoinUsingConcatenationOperator(string[] items)
        {
            string result = string.Empty;
            foreach (string item in items)
                result += item;
            return result;
        }
}

and a Test class to test above code as below,


class Program
{
        static void Main(string[] args)
        {
            string[] items = new string[] { "One-""Two-""Three" };
            StringJoin stringJoin = new StringJoin();
 
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcat("One-""Two"));
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcat(items));
 
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingJoin("One-""Two"));
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingJoin(items));
 
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingBuilder("One-""Two"));
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingBuilder(items));
 
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcatenationOperator("One-""Two"));
            Console.WriteLine("Result : {0}", stringJoin.JoinUsingConcatenationOperator(items));
 
            Console.ReadKey();
        }
}

and the output of the code is as below,
There would be some other ways to join .Net string. Happy to learn others.

Behind the scene of var in .Net

There are lots of discussion going on about var. Should we use var to declare a type or not. After reading lots of article I decided to disassemble code used var by .Net Reflector.

So I wrote a simple library named ImplicitCodeLibrary with two simple types VarDeclarationTester and TestClass.

  • VarDeclarationTester - will instantiate two types DateTime and TestClass using Implicit way such as var and another one explicit way.
  • TestClass - it is just a test class use to instantiate a custom type.


namespace ImplicitCodeLibrary
{
    using System;
    public class VarDeclarationTester
    {
        public void ImplicitTypeTest()
        {
            var dateTimeImplicit = new DateTime(2011, 3, 21);
            var testClassImplicit = new TestClass();
 
            DateTime dateTimeExplicit = new DateTime(2011, 1, 11);
            TestClass testClassExplicit = new TestClass();
        }
    }
 
    public class TestClass
    {
        public TestClass() { }
        public void GetAmount()
        {
        }
    }
}

After compiling the code, I open the generated DLL via .Net Reflector. The result I found is as follow,



So the lines,


var dateTimeImplicit and var testClassImplicit have been replaced by code DateTime dateTimeImplicit and TestClass testClassImplicit on compile time.

So, what we can see in here, on Compile time Type has been given by Compiler.

Thanks
mohammad