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;
        }

    }