Tuesday, February 18, 2014

Quick note on Microsoft.Net Thread.Start, Delegate.BeginInvoke, Control.BeginInvoke

Thread.Start
Starts a new OS thread to execute the delegate. When the delegate returns, the thread is destroyed. This is quite a heavy-weight operation (starting and destroying a thread) so you typically only do it if the method is going to be long-running.

Delegate.BeginInvoke
Delegate.BeginInvoke will call the delegate on a thread pool thread. Once the method returns, the thread is returned to the pool to be reused by another task. The advantage of this is that queuing a method to the thread pool is relatively light-weight because you don't have to spin up a whole new thread every time.

Control.BeginInvoke

Control.BeginInvoke executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. It basically takes a delegate and runs it on the thread that created the control on which you called BeginInvoke. In other words Control.BeginInvoke invokes the method on the thread for the control. UI components are inherently single-threaded and every interaction with a UI control must be done on the thread that created it. Control.BeginInvoke is a handy way to do that.

Reference links:-

TechNet Guru Award - Jan 2014 on How to make asynchronous method call in C#

Monday, January 20, 2014

How to make asynchronous method call in C#

I created an application wherein I needed to call a method and forget it; the called method will perform several operations in background. I don’t want to wait for all the operation to be completed and then proceed. I wanted to call the method to perform the operations in background and meanwhile I can proceed with other operations.

There are various ways the above problem can be solved; however I wanted to go with asynchronous method call which is demonstrated below with code example:-

Demo Console Application: Programm.CS class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MethodA();

            Console.ReadKey();
        }

        private static void MethodA()
        {
            Console.WriteLine("Method A Execution Started");

            DemoAsyncMethodCall.Capture("Call from Method A");

            MethodB();

            Console.WriteLine("Method A completed");

        }

        private static void MethodB()
        {
            Console.WriteLine("Inside Method B");
        }
    }
}


Demo Console Application: DemoAsyncMethodCall.CS class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApplication1
{
    public class DemoAsyncMethodCall
    {
        delegate void MethodDelegate(string message);
       
        public static void Capture(string message)
        {
            MethodDelegate dlgt = new MethodDelegate(saveData);

            IAsyncResult ar = dlgt.BeginInvoke(message, null, null);
        }
       
        private static void saveData(string message)
        {
            Console.WriteLine("Aync method call saveData with message: " + message);
        }
               
    }
}


Demo Console Application:  Output



Monday, August 5, 2013

Unable to cast COM object of type 'Microsoft.Office.Interop.PowerPoint.ApplicationClass' to interface type 'Microsoft.Office.Interop.PowerPoint._Application

My team have been struggling with COM Component issue for about one week, it almost frustrated the developer, me and project manager. Uff.. after intense amount of googling and trial method, several time repair and installation of office, the problem was still bugging all the team members. Finally the issue was resolved with couple of settings in Registry. The real cause of the issue was a mystery. Finally we succeeded to identify the reason for the issue and then killed the exception.

Exception thrown by the system:-

Below is the most boring exception frustrated me every time when I debug the code

System.InvalidCastException was unhandled
  Message=Unable to cast COM object of type 'Microsoft.Office.Interop.PowerPoint.ApplicationClass' to interface type 'Microsoft.Office.Interop.PowerPoint._Application'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{91493442-5A91-11CF-8700-00AA0060263B}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).

  Source=Microsoft.Office.Interop.PowerPoint

Read the entire post at :  

Wednesday, October 12, 2011

Modal popup dialog box using JQuery

Before going into the implementation let me first share the screen shot how the popup will look like (and obviously you can customize it as per your branding needs)



Just download the css, images and Java script files from below link
Above download will give you a demo html page, you can just take a look and copy pastes the code on your page. This works great!!
For more detail on the JQuery modal dialog box you can visit to http://www.ericmmartin.com/projects/simplemodal-demos/
 
 

Saturday, June 4, 2011

Modifying Web.Config file and IIS Reset


What do you think changing in web.config file reset the IIS? Are you sure??

When you say IIS RESET do you know IIS Reset stops and restarts the entire web server
Lets take a look at IIS.
In IIS you can create multiple websites, application pools. You can run multiple applications under one application pool. Now think in your IIS you have so many applications running, and you just modified one of your application web.config file and if you are thinking modifying web.config file reset the IIS then that means you have impacted all the applications running on the IIS server, is that really making sense??

The Answer to the above question is NO, it doesn't reset the IIS when you modify web.config file of your application.Editing the web.config in a web application only affects that web application (recycles just that app), so it doesn't require to reset the IIS, it just impact that particular application and reload the app domain. And if you are recycling an app pool that will only affect applications running in that app pool. But Editing the machine.config on the machine will recycle all app pools running.

Another question is when you change/update dlls/drop new dlls in the bin directory of your web application, is that will reset IIS?? Again the answer is NO, it doesn't reset the IIS. IIS monitors the /bin directory of your application. Whenever a change is detected in dlls, it will recycle the app and re-load the new dlls.

Thursday, May 19, 2011

How to copy an image from an URL to own server and resize it


First: Download the image with Url.
Second: Resize the image and save it into disk.

<!   1) For the first requirement, you can use WebClient class. Refer to the following code
  private void Page_Load(object sender, System.EventArgs e)
    {
        WebClient wc = new WebClient();

        byte[] data = wc.DownloadData("http://www.google.cn/intl/en-us/images/logo_cn.gif");

        MemoryStream ms = new MemoryStream(data);

        System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

        GetThumbnailImage(img);//Resize Image
    }
   
->   2) For the second requirement refer to the code below:
private void GetThumbnailImage(System.Drawing.Image img)
    {
        float iScale = img.Height > img.Width ? (float)img.Height / 100 : (float)img.Width / 100;

        img = img.GetThumbnailImage((int)(img.Width / iScale), (int)(img.Height / iScale), null, IntPtr.Zero);

        MemoryStream memStream = new MemoryStream();

        img.Save(Server.MapPath("att.jpeg"), System.Drawing.Imaging.ImageFormat.Jpeg);

        memStream.Flush();
    }

How to Know Country Location of a user - asp.net C#

You can use below code snippet to get the region description of the current user.


using System.Globalization;

string name = RegionInfo.CurrentRegion.DisplayName;

For more information visit below link

SMTP Server Relay setting and sending email from c# code

Use below steps to set up your SMTP server first
1. Start>>Run>inetmgr
2. Now check if SMTP server already installed with IIS (if not then open Control Panel>>Add Remove Programs >> click on add remove windows components, your will get a window , here you can select Internet Information Services and double click on this, now you will get list IIS of components, here you can select SMTP Server) install it.
2. Once SMTP Server is installed, then right click on SMTP Server >> click properties, it will open a window, now select Access Tab on the top, click on Relay button, here you will get radio button option (1. Only list below, 2.All except the list below), select only list below and add your ip address and mask (127.0.0.1) in the list
Click OK, you are done, 
Now in your application, you can specify your SMTP Server IP address and credentials for sending emails. You can use below sample code for sending emails from c# code.
static public void SendMail(string fromEmail, string fromName, string toAddress,
                                    string toName, string ccAddress, string subject,
                                    string body
                                    )
        {
            SendMail(new System.Net.Mail.MailAddress(fromEmail, fromName), toAddress, ccAddress, subject, body);
        }

        static public void SendMail(System.Net.Mail.MailAddress fromAddress, string toAddress, string ccAddress,
                                    string subject, string body)
        {
            //Read SMTP Server Name or IP from Config xml file
            string SmtpServer = ConfigSettings.GetProperty(Constants.SMTP_SERVER);

            //Read User Name from Config xml file
            string SmtpUserName = ConfigSettings.GetProperty(Constants.SMTP_USERNAME);
           
            //Read User Password from Config xml file
            string SmtpUserPass = ConfigSettings.GetProperty(Constants.SMTP_PASSWORD);
           
            //Read port setting from Config xml file
            string smtpPort = ConfigSettings.GetProperty(Constants.SMTP_PORT);

            System.Net.Mail.SmtpClient smtpSend = new System.Net.Mail.SmtpClient(SmtpServer);

            using (System.Net.Mail.MailMessage emailMessage = new System.Net.Mail.MailMessage())
            {
                emailMessage.To.Add(toAddress);

                if (!string.IsNullOrEmpty(ccAddress))
                    emailMessage.CC.Add(ccAddress);

                emailMessage.From = fromAddress;
                emailMessage.Subject = subject;
                emailMessage.Body = body;
                emailMessage.IsBodyHtml = true;


                if (!Regex.IsMatch(emailMessage.Body, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase) ||
                        !Regex.IsMatch(emailMessage.Subject, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase))
                {
                    emailMessage.BodyEncoding = Encoding.Unicode;
                }

                if (SmtpUserName != null && SmtpUserPass != null && smtpPort != null)
                {

                    smtpSend.Port = Convert.ToInt32(smtpPort);
                    smtpSend.UseDefaultCredentials = false;
                    smtpSend.Credentials = new System.Net.NetworkCredential(SmtpUserName, SmtpUserPass);
                }

                try
                {
                    smtpSend.Send(emailMessage);
                }
                catch (Exception ex)
                {
                    AppException.HandleException(ex);
                }

            }
        }

AJAX AutoComplete Feature Implementation Example

1.       Add AJAXControltoolkit dll in your web site reference
2.       Drag n drop script manager on the top of the page (if already included inmaster page then no need)
3.     Place folowing html in your html page

<ajaxToolkit:AutoCompleteExtender ID="AutoCompletePeople" runat="server" TargetControlID="txtUsers " 
DelimiterCharacters=","  MinimumPrefixLength="1" ServicePath="NewQuestion.aspx"
ServiceMethod="GetUsersList" UseContextKey="True"
EnableCaching="true"
CompletionSetCount="5"
CompletionInterval="1000"
BehaviorID="autoCompleteBehavior1">


4.      Write following code in aspx.cs class file
#region AutoComplete Users
        //Specify this method as ServiceMethod for Company Completion List
        [System.Web.Services.WebMethod]
        public static string[] GetUsersList(string prefixText, int count)
        {
            string[] result = selectUsers(prefixText);// this method returns all the users
            return result;
        }
        #endregion  AutoComplete Users END

Here is the link for AJAX  Auto complete features  and more
http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/AutoComplete/AutoComplete.aspx

Custom Rating Control, create your own simple rating control


I have implemented rating control in one of my application by using two images (blue star and white star), and written c# code for displaying the rating selected by the user, you can store the selected rating in the database also and display accordingly.

You might be wondering if rating controls are already available then why build from scratch, your thinking is absolutely right; however I wanted a simple light weight control for my application so that I can change anything I want.
First what is does it display 5 rating white stars and when user click on any star let’s say click on 3rd  then you have to replace the image URL of previous 2 images and the clicked one to blue (whatever color you like), so it will become 3 blue star.
Lets have a look at the sample code. You just need to pass the rating value to the setFeebackScore method; it will set the images and display the score description accordingly. You can create this control as a component and use it wherever you want in your application.

  private const string IMAGE_FEEDBACK_BLUE      = "/_layouts/images/neon_FeedbackBlue.JPG";
  private const string IMAGE_FEEDBACK_WHITE   = "/_layouts/images/neon_FeedbackWhite.JPG";

  private void setFeedbackScore(float rating)
        {
            if (rating == float.Parse("1"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Poor)";
            }
            else if (rating == float.Parse("2"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Fair)";
            }
            else if (rating == float.Parse("3"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Good)";
            }
            else if (rating == float.Parse("4"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Very Good)";
            }
            else if (rating == float.Parse("5"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_BLUE;

                lblScoreDescription.Text = "(Excellent)";
            }
            else
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = string.Empty;
            }