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