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

Friday, March 25, 2011

JavaScript to auto increase height of multiline text box


Here is the Java script code for auto resizing multiline text box. What it does is when user keeps typing in the text box and reach to the end line then text box height automatically increases.
<script type="text/javascript">
// this function takes text box as input parma which need to grow in height upon typing
    function AutoResizeMultilineTextBox(txtBox) {

        nCols = txtBox.cols; // find total columns set to the text box
        sVal = txtBox.value; // total characters
        nVal = sVal.length; // total lenth of the character
        nRowCnt = 1; // new row count variable reset to 1

        // this loop is written to find out total new row count to be added depending upon the character lenght
        //and new line found in the character
        for (i = 0; i < nVal; i++) {
            if (sVal.charAt(i).charCodeAt(0) == 13) {
                nRowCnt += 1;
                }
            }

        // check if new row count is less than the rown count covered by the character
        if (nRowCnt < (nVal / nCols)) { nRowCnt = 1 + (nVal / nCols); }
            txtBox.rows = nRowCnt+2;      

    }
</script>


Example text box

<asp:TextBox ID="txtMsg" runat="server"  TextMode="MultiLine"  onkeyup="AutoResizeMultilineTextBox(this)" Rows="3" Columns="50" />

Above code will cover all scenarios
-          User Continuous typing
-          User keep hitting new line (Enter Button)
-          User hit back button

Event Validation Error when switching between aspx pages


 In .Net web applications when you switch between pages very frequently sometimes you might observe exceptions (page breaks).

Exception:
Invalid postback or callback argument. Event validation is enabled using <pages enableeventvalidation="true" /> in configuration or <%@ page enableeventvalidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.”

Solution:
This problem occurs when post back happen before completely loading the previous page, to avoid this problem you need add following code under page element in web.config file
<pages  ValidateRequest="false"  EnableEventValidation="true" >
This will solve your problem; you don’t need to add these setting codes in all your aspx pages, if you have added it under page element in web.config then it will work for all the pages throughout the application.