Saturday, September 26, 2009

Using HttpWebRequest in C#

Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");

            // Create the web request
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

            // Set type to POST
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            // Create the data we want to send
            string appId = "YahooDemo";
            string context = "Italian sculptors and painters of the renaissance"
            + "favored the Virgin Mary for inspiration";
            string query = "madonna";
            StringBuilder data = new StringBuilder();
            data.Append("appid=" + HttpUtility.UrlEncode(appId));
            data.Append("&context=" + HttpUtility.UrlEncode(context));
            data.Append("&query=" + HttpUtility.UrlEncode(query));

            // Create a byte array of the data we want to send
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

            // Set the content length in the request headers
            request.ContentLength = byteData.Length;

            // Write data
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            // Get response
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Console application output
                Console.WriteLine(reader.ReadToEnd());

            }

Friday, September 25, 2009

Simple sample code using SortedList and IComparable in C#

Here is the simple code which uses SortedList and IComparable


Entity

class Test : IComparable<Test>    {
        int _order = 0;
        string _result = string.Empty;

        public int Order
        {
            get { return _order; }
            set{_order = value; }
        }
        public int CompareTo(Test t)
        {
            return _order.CompareTo(t.Order);
        }
        public string Result
        {
            get { return _result; }
            set { _result = value; }
        }
    }



Code to execute:


SortedList<Test, string> tests = new SortedList<Test, string>();
            Test t = new Test();
            t.Order = 10;
            t.Result = "1";
            tests.Add(t, "hello");
            t = new Test();
            t.Order = 5;
            t.Result = "2";
            tests.Add(t, "world");

            foreach (KeyValuePair<Test, string> kp in tests)
            {
                Console.WriteLine(kp.Key.Order);
            }

Simple Linq and Lamda Expression samples using C#

Lamda Expression to select specific columns in the Generic List

var timeWeeksDistincts = timeWeeks.Select(item => new {item.MemberId,item.TimesheetId,item.ProjectId,
                                                                                                                      item.WorkPackageId,
                                                                                                                      item.TimesheetDate
                });


Linq to select Distinct records


var timeWeeksDistincts = timeWeeks.Distinct();

Linq to select list based on WHERE condition


                    IEnumerable timeWeeksMatching = from c in timeWeeks
                                                                   where c.TimesheetId == timeWeek.TimesheetId
                                                                   && c.TimesheetDate == timeWeek.TimesheetDate
                                                                   && c.ProjectId == timeWeek.ProjectId
                                                                   && c.MemberId == timeWeek.MemberId
                                                                   && c.WorkPackageId == timeWeek.WorkPackageId
                                                                   select c;





Simple code to get weeks in month using C#

Code to get Week in a month:


public static int GetWeekInMonth(DateTime date)
        {
            DateTime tempdate = date.AddDays(-date.Day + 1);

            CultureInfo ciCurr = CultureInfo.CurrentCulture;
            int weekNumStart = ciCurr.Calendar.GetWeekOfYear(tempdate, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
            int weekNum = ciCurr.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

            return weekNum - weekNumStart + 1;

        }



Code to get number of Weeks in a month: 

public static int Weeks(int year, int month)
        {
            DayOfWeek wkstart = DayOfWeek.Monday;

            DateTime first = new DateTime(year, month, 1);
            int firstwkday = (int)first.DayOfWeek;
            int otherwkday = (int)wkstart;

            int offset = ((otherwkday + 7) - firstwkday) % 7;

            double weeks = (double)(DateTime.DaysInMonth(year, month) - offset) / 7d;

            return (int)Math.Ceiling(weeks);
        }



Thursday, September 24, 2009

Asynchronous programming using IAsyncResult in ASP.NET

Here is the sample code for achieving asynchronous calls in ASP.NET using IAsyncResult


Asynchronous Provider:


public delegate List<Test> AsyncMethodCaller();
    public class AsyncProvider
    {
       
        public List<Test> GetTests()
        {
            System.Threading.Thread.Sleep(2000);
            return TestServices.provider.GetAllTests();
        }

    }



Using BeginInvoke and EndInvoke along with IAsyncResult in .aspx page:


public partial class TestAsync : System.Web.UI.Page
    {
        IAsyncResult result = default(IAsyncResult);
        AsyncProvider _provider = new AsyncProvider();
        AsyncMethodCaller caller = default(AsyncMethodCaller);
        List<Test> res = default(List<Test>);


        protected void Page_Load(object sender, EventArgs e)
        {
            txtFirstLoad.Text = "loaded first";           
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            caller = new AsyncMethodCaller(_provider.GetTests);
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            result = caller.BeginInvoke(null, null);
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            res = caller.EndInvoke(result);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);  
          
            grid.DataSource = res;
            grid.DataBind();
            grid.RenderControl(writer); 
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

    }

Wednesday, September 23, 2009

Simple Modal Popup using Javascript which works in sharepoint and ASP.NET

Here is the code for simple modal popup using Javascript which works in sharepoint as well as ASP.NET



<div id='modal' style='position: absolute; top: 0px; left: 0px; display: none; z-index: 9;
    background-color: #383838; filter: alpha(opacity=60);'>
</div>
<div id='chart' style='position: absolute; top: 100px; left: 180px; display: none;
    z-index: 10;'>
    <asp:Button ID="btnYes" runat ="server" Text ="Yes" OnClick ="btnYes_Click" />
    <button onclick="javascript:document.getElementById('modal').style.display='none';document.getElementById('chart').style.display='none';">
        CANCEL</button>
    <br />
    <br />
</div>
<a href='#'  onclick="javascript:document.getElementById('modal').style.width = document.body.clientWidth + 'px';document.getElementById('modal').style.height = document.body.clientHeight + 'px';document.getElementById('modal').style.display='block';document.getElementById('chart').style.display='block';">
<asp:Label ID="lblClick" runat ="server" Text ="Click Me"></asp:Label>
</a>


To get this code working properly in ASP.NET remove the following code in .aspx pages
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Binding the multiple drop down boxes in GridView using JQuery in ASP.NET

Here is the code for binding the multiple drop down boxes in GridView using JQuery in ASP.NET


ASPX and JQuery code:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TimeSheetGrid.ascx.cs" Inherits="TimesheetApp.UserControls.TimeSheetGrid" %>
<script src="../Script/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
    $("select[id$='cboWorkPackage']").each(function()
    {
        getWorkPackages($(this));
    }
    );
   
    $("select[id$='cboModule']").each(function()
    {
        getModules($(this));
    }
    );
}
);

function getWorkPackages(t) {
  $.ajax({
    type: "POST",
    url: "/WebMethods/GridValuesService.asmx",
    data: "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><GetWorkPackages xmlns='http://tempuri.org/'><ProjectId>" + $("span[id$='lblProjectValue']").html() + "</ProjectId></GetWorkPackages></soap:Body></soap:Envelope>",
    contentType: "text/xml; charset=\"utf-8\"",
    dataType: "xml",
    success: function(response)
    {
     
    },
    complete: function (result,status)
    {
    $(result.responseXML).find("WorkPackage").each(function()
        {
       
           
            var val = $(this).find("WPId").text();
            var text = $(this).find("WPCode").text();
            var myOptions = {
                                val1 : val,
                                val2 : text
                            };
             t.append
                (
                $('<option></option>').html(text).val(val)
                );              
               
        }
    );
    },
    error: function (result,status)
    {
    alert(status);
    }
  });
}


function getModules(t) {
  $.ajax({
    type: "POST",
    url: "/WebMethods/GridValuesService.asmx",
    data: "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><GetModules xmlns='http://tempuri.org/'><WorkPackageId>" + 1 + "</WorkPackageId></GetModules></soap:Body></soap:Envelope>",
    contentType: "text/xml; charset=\"utf-8\"",
    dataType: "xml",
    success: function(response)
    {
     
    },
    complete: function (result,status)
    {
    $(result.responseXML).find("Module").each(function()
        {
       
           
            var val = $(this).find("ModuleId").text();
            var text = $(this).find("ModuleCode").text();
            var myOptions = {
                                val1 : val,
                                val2 : text
                            };
             t.append
                (
                $('<option></option>').html(text).val(val)
                );              
               
        }
    );
    },
    error: function (result,status)
    {
    alert(status);
    }
  });
}
</script>
<asp:GridView ID="grdTimeSheetView" runat="server" AutoGenerateColumns="false" EnableViewState="true">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:Label ID="lblProject" runat="server" Text="Project"></asp:Label>
            </HeaderTemplate>
            <ItemTemplate>
               <asp:Label ID="lblProjectValue" runat ="server" Text ='<%# Eval("ProjectId") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:Label ID="lblWorkPkg" runat="server" Text ="Work Package"></asp:Label>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="cboWorkPackage" runat ="server" EnableViewState ="true"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
        <HeaderTemplate>
        <asp:Label ID="lblModule" runat="server" Text ="Module"></asp:Label>
        </HeaderTemplate>
            <ItemTemplate>
                <asp:DropDownList ID="cboModule" runat ="server" EnableViewState ="true"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
 


Web Service and Web Methods


/// <summary>
    /// Summary description for GridValuesService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class GridValuesService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public List<WorkPackage> GetWorkPackages(long ProjectId)
        {
            WorkPackageDAL wp = new WorkPackageDAL();
            return wp.GetWorkPackages(ProjectId);
        }
        [WebMethod]
        public List<Module> GetModules(long WorkPackageId)
        {
            ModuleDAL module = new ModuleDAL();
            return module.GetModules(WorkPackageId);
        }

    }





Tuesday, September 22, 2009

Simple code for Provider Model pattern along with Singleton pattern using C#

Here is the sample code for Provider Model pattern along with Singleton pattern using C#.


public abstract class TestProviderBase : System.Configuration.Provider.ProviderBase
    {
        public abstract List<Test> GetAllTests();
    }



public class TestProvider : TestProviderBase
    {
        public override List<Test> GetAllTests()
        {
            string connString = ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                using (SqlCommand command = new SqlCommand("select dbo.Test.ColA,dbo.Test.ColB from dbo.Test", conn))
                {
                    return Common.ConvertReaderToTest(command.ExecuteReader());
                }
            }
           
        }
    }



public sealed class TestServices
    {
        static TestProvider testInstance = null;
        static readonly object padlock = new object();

        TestServices()
        {

        }
        public static TestProvider provider
        {
            get
            {
                lock (padlock)
                {
                    if (testInstance == null)
                    {
                        testInstance = new TestProvider();
                    }
                    return testInstance;
                }

            }
        }

    }



Code to execute:
GridView1.DataSource = TestServices.provider.GetAllTests();
 GridView1.DataBind();

Binding an XML to TreeView using C#

Here is the code for binding an XML to TreeView control


private void button1_Click(object sender, EventArgs e)
        {
            inputFile.ShowDialog();
            txtInputFile.Text = inputFile.FileName;
        }


private void updateTreeView(string filename)
        {
            try
            {
                txtInputFile.Text = filename;
                tvXMLView.Nodes.Clear();
                tmpxmldoc = new XmlDocument();
                tmpxmldoc.Load(filename);
                FillTree(tmpxmldoc.DocumentElement, tvXMLView.Nodes);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void FillTree(XmlNode node, TreeNodeCollection parentnode)
        {
            // End recursion if the node is a text type
            if (node == null || node.NodeType == XmlNodeType.Text || node.NodeType == XmlNodeType.CDATA)
                return;

            TreeNodeCollection tmptreenodecollection = AddNodeToTree(node, parentnode);

            // Add all the children of the current node to the treeview
            foreach (XmlNode tmpchildnode in node.ChildNodes)
            {
                FillTree(tmpchildnode, tmptreenodecollection);
            }
        }


        private TreeNodeCollection AddNodeToTree(XmlNode node, TreeNodeCollection parentnode)
        {
            TreeNode newchildnode = CreateTreeNodeFromXmlNode(node);

            // if nothing to add, return the parent item
            if (newchildnode == null) return parentnode;

            // add the newly created tree node to its parent
            if (parentnode != null) parentnode.Add(newchildnode);

            return newchildnode.Nodes;
        }


        private TreeNode CreateTreeNodeFromXmlNode(XmlNode node)
        {
            TreeNode tmptreenode = new TreeNode();

            if ((node.HasChildNodes) && (node.FirstChild.Value != null))
            {
                tmptreenode = new TreeNode(node.Name);
                //TreeNode tmptreenode2 = new TreeNode(node.FirstChild.Value);
                //tmptreenode.Nodes.Add(tmptreenode2);
            }
            else if (node.NodeType != XmlNodeType.CDATA)
            {
                tmptreenode = new TreeNode(node.Name);
            }

            return tmptreenode;
        }

Custom Matching Rules and Custom Handlers using Unity Application Block


There might be times where-in you will have to write custom matching rules and the corresponding handlers to achieving auditing. Unity Application Block provides that flexibility to achieve this. Below is the code which will help to to do

Matching Rule:


 public class MethodMatchingRule : IMatchingRule
    {

string _MethodName = string.Empty;

public MethodMatchingRule(string MethodName)
{
  _MethodName =  MethodName;
}


public MethodMatchingRule()
{

}


        public bool Matches(MethodBase member)
        {
            return member.Name == _
MethodName;
        }

    }



Custom Handler:
public class DynamicHandler : ICallHandler
    {
        public int Order { get; set; }

        public DynamicHandler()
        {

        }

        public DynamicHandler(int order)
        {
            this.Order = order;
        }
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {

            Console.Write("DynamicHandler, ");
            //We can write to DB or file or anything
            string name = input.MethodBase.Name;
            Type objType = input.MethodBase.DeclaringType;

            IMethodReturn result = getNext()(input, getNext);

            //Console.Write("By Dynamic Handler ");
            //We can write to DB or file or anything

            return result;
        }

    }



Code to create Objects:
public static TInterface GetFactory() where TObject : TInterface
        {
            container.AddNewExtension();
            container.RegisterType().Configure().SetInterceptorFor(
                new InterfaceInterceptor());
            container.Configure().AddPolicy("Test").AddMatchingRule(new MethodMatchingRule("Write")).AddCallHandler(new DynamicHandler());
            var logger = container.Resolve();
            return (TInterface)logger;
        }



Code to execute:
            ILogger logger = InterfaceInterceptorProxy.GetFactory<ILogger, Logger>();
            logger.Write("World.");

Getting Word from Running Object Table (ROT) using C#

Usually in Word Automation, we need to ensure that only one instance of word application is running. This is can be achieved by getting the word application from ROT and use it. Below is the code which does this functionality


Word.Application objApplication;

                try
                {
                    objApplication = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Word.Application;
                   
                   
                }
                catch
                {
                    objApplication = new Microsoft.Office.Interop.Word.Application();
                }



This code can be used for any application which is hosted in ROT.

Monday, September 21, 2009

Exporting a GridView to PDF using iTextSharp and C#


Here is the code for exporting the GridView contents in PDF format using the iTextSharp library and C#.


StringWriter stringReader = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stringReader);
grid.RenderControl(htextw);
System.Text.StringBuilder builder = stringReader.GetStringBuilder();
MemoryStream m = new MemoryStream();
Document d = new Document();
PdfWriter writer = PdfWriter.GetInstance(d, m);
writer.CloseStream = false;
d.Open();
XmlTextReader reader = new XmlTextReader(new StringReader(builder.ToString()));
HtmlParser.Parse(d, reader);
d.Close();
writer.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", String.Format("inline;filename={0}", "abc.pdf"));
Response.BinaryWrite(m.ToArray());
Response.End();

Exporting specific columns in a grid to Excel in ASP.NET

Here is the code for exporting only specific columns in a grid to Excel in ASP.NET


HtmlForm form = new HtmlForm();
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
GridView grid = new GridView();
List<Test> t = (List<Test>)GridView1.DataSource;
DataTable dt = Common.ToDataTable<Test>(t);
dt.Columns.Remove("ColB");
grid.DataSource = dt;
grid.DataBind();
form.Controls.Add(grid);
this.Controls.Add(form);
form.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();

public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection props =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name, prop.PropertyType);
            }
            object[] values = new object[props.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }

Simple code to read and convert the CSV into List using C#

ere is the simple code for converting a CSV into List<Object>

static void Main(string[] args)
        {
            List<object> result = new List<object>();
            string FileName = @"D:\Samples\test.csv";
            FileStream f = File.Open(FileName, FileMode.Open);
            TextReader reader = new StreamReader(f);
            string Row = string.Empty;
            while((Row = reader.ReadLine()) != null)
            {
                List<string> RowDetails = SplitRow(Row);
                result.Add(RowDetails);
            }
            reader.Close();
            f.Close();
        }
       static List<string> SplitRow(string Row)
        {
            List<string> result = new List<string>();
            string[] splitRow = Row.Split(",".ToCharArray());
            result = splitRow.ToList<string>();
            return result;
        }