How to redirect to another page after alert message in c#?

There is some situation where we want to show alert message and confiration
message before redirecting to another page.

Method 1

Response.Write("<script> alert('Your Message.');window.location='TargetpageURL'; </script>");

Method 2

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ScriptKey", "alert('Your Message will go here.');window.location='TargetpageURL'; ", true);

Method 3

HTMLHelper.jsAlertAndRedirect(this, "This is an alert.", ResolveUrl("~/Default.aspx"));

Method 4

string  strScript = "<script>"+"alert('your message.');";
                strScript += "window.location='test.aspx';";
                strScript += "</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Startup", strScript);

How to Get Client Ip address in asp.net .

You can capture Ip address of client.
Firs Method

        /// <summary>
        /// Get Client Ip address
        /// </summary>
        /// <returns></returns>
        public string GetClientIpAddress()
        {
            HttpRequest currentRequest = HttpContext.Current.Request;
            string ipAddress = currentRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (ipAddress == null || ipAddress.ToLower() == "unknown")
                ipAddress = currentRequest.ServerVariables["REMOTE_ADDR"];

            return ipAddress;
        }

Alternative One:

        /// <summary>
        /// Get Client Ip address
        /// </summary>
        /// <returns></returns>
        public string GetClientIpAddress()
        {
            string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            return ipAddress;
        }

Hope this will help 🙂

How to Upload Image asynchronously in asp.net by c#.

 +Summary

In Asp.net we have File Uploader control which is used for upload image , document and file on server. But it need postback to save on server. Some time this is not feasible solution for uploading image by post back. So In this post we will used Jquery plugin which will help us to upload image asynchronously.

 + Jquery File

Jquery File Uploader file Download From Here

 + AjaxFileUploader.ashx.cs File 

For uploading image asynchronously we will create generic handler in c#. First create generic handler and pest below code.

    /// <summary>
    /// Summary description for AjaxFileUploader
    /// </summary>
    public class AjaxFileUploader : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                string path = context.Server.MapPath("~/images/Temp");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                var file = context.Request.Files[0];

                string fileName;

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = file.FileName.Split(new char[] { '\\' });
                    fileName = files[files.Length - 1];
                }
                else
                {
                    fileName = file.FileName;
                }
                string strFileName = fileName;
                fileName = Path.Combine(path, fileName);
                file.SaveAs(fileName);

                string msg = "{";
                msg += string.Format("error:'{0}',\n", string.Empty);
                msg += string.Format("msg:'{0}'\n", "images/Temp/"+strFileName);
                msg += "}";
                context.Response.Write(msg);
            }
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
 + FileUploader.aspx File 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script src="Scripts/ajaxfileupload.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:FileUpload ID="fuProfilePicUpload"  ClientIDMode="Static" runat="server" />
      <div id="divLoader" style="display:none">Please wait.............</div>
      <button id="btnUpload" onclick="return ajaxFileUpload();">Upload</button>
    </div>
    </form>
</body>
</html>
 + JavaScript Code 
<script type="text/javascript">
    function ajaxFileUpload() {

        $("#divLoader").ajaxStart(function () {
            $(this).show();
        }).ajaxComplete(function () {
            $(this).hide();
        });
        $.ajaxFileUpload(
       {
           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fuProfilePicUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                       alert(data.error);
                   } else {
                       alert("Uploaded Successfully");
                   }
               }
           },
           error: function (data, status, e) {
               alert(e);
           }
       }
   )
        return false;
    }
</script>

I hope it will help you 🙂

C#: How to send email by using your gmail account by c#.

For sending email by c# using google smtp server and your gmail account you can send email.For this you must have to provide your gmail credential.

public bool SendMail(string to, string from, string subject, string msgBody)
        {
            bool mailSendStatus = false;

            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = new MailAddress(from, "from Name");
                message.To.Add(new MailAddress(to));
                message.Subject = subject;
                message.Priority = System.Net.Mail.MailPriority.High;
                message.IsBodyHtml = true;
                message.Sender = new MailAddress(from, "Sender Name");
                message.Body = msgBody;

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Credentials = new System.Net.NetworkCredential("xyz@gmail.com", "password");

                smtp.Send(message);
                mailSendStatus = true;
            }
            catch
            {
                mailSendStatus = false;
            }
            return mailSendStatus;
        }

And alternatively instead of hardcoding smtp settings you can keep in web config file in below format.

<system.net>
      <mailSettings>
        <smtp from="codeDestination@gmail.com" deliveryMethod="Network">
          <network enableSsl="true" defaultCredentials="false"
		        host="smtp.gmail.com" port="587"
			userName="myaccountuesrname@gmail.com"
			password="mypassword" />
        </smtp>
      </mailSettings>
</system.net>

If you use smtp settings in web config then sendEmail function will look like

        // to : Adress of person whom you are sending email
 	public bool SendMail(string to, string from, string subject, string msgBody)
        {
            bool mailSendStatus = false;

            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = new MailAddress(from, "from Name");
                message.To.Add(new MailAddress(to));
                message.Subject = subject;
                message.Priority = System.Net.Mail.MailPriority.High;
                message.IsBodyHtml = true;
                message.Sender = new MailAddress(from, "Sender Name");
                message.Body = msgBody;

                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();

                smtp.Send(message);
                mailSendStatus = true;
            }
            catch
            {
                mailSendStatus = false;
            }
            return mailSendStatus;
        }

page keyword: Send Email via C# through Google Apps account,.net – Sending email through Gmail SMTP server with C# How to send email in asp.net (c#) using google or gmail smtp server, send email from c# code

How to get Feed from url in C#.

Below function will used to get feed item from URL.

        public static string GetRssFeedInList(string url, int howMany)
        {
            // Get the rss feed
            var x = ReturnXmlFromUrl(url);

            // Create a string builder for the feed
            var sb = new StringBuilder();

            // Try and get the movie
            var nodes = x.GetElementsByTagName("item");
            var i = 0;
            sb.Append("<ul>");
            foreach (XmlNode node in nodes)
            {
                if (i &lt;= (howMany - 1))
                {
                    sb.Append(&quot;<li>");
                    if (node != null)
                        sb.Append(String.Format("<a target='_blank' href='{0}'>{1}</a>", node["link"].InnerText,    node["title"].InnerText));
                    sb.Append("</li>");
                }
                i++;
            }
            sb.Append("</ul>");
            return sb.ToString().Trim();
        }

Page Keyword: How to Get a Feed from URL in .Net. Really Simple Syndication (RSS) feed from Url,
Get feed content from code in c#, get feed content in .net, Return rss feed item from url. Creating RSS Feed, c# Code for RSS Feed. Live Feed Item from URL. How to get Rss or ATOM feed from URL in c#, In .Net.

Return number of word from given text in c#.

Some time we come across situation to return fixed number of word from text. Below function will return string which contain number of word which you have supplied during function calling.

        public static string ReturnAmountWordsFromGivenString(string text, int wordAmount)
        {
            string tmpStr;
            string[] stringArray;
            var tmpStrReturn = "";
            tmpStr = text.Replace("\t", " ").Trim();
            tmpStr = tmpStr.Replace("\n", " ");
            tmpStr = tmpStr.Replace("\r", " ");

            while (tmpStr.IndexOf("  ") != -1)
            {
                tmpStr = tmpStr.Replace("  ", " ");
            }
            stringArray = tmpStr.Split(' ');

            if (stringArray.Length < wordAmount)
            {
                wordAmount = stringArray.Length;
            }
            for (int i = 0; i < wordAmount; i++)
            {
                tmpStrReturn += stringArray[i] + " ";
            }
            return tmpStrReturn;
        }

Page Keyword: Return word from text in c#, Return fixed number of word from text program in c#. Return word from text.pgm in c# to count number of words in a text document

Count number of word in text in c#.

How to count number of word in text. Below function will return number of word in text.

        public static int CountNoWordsInString(string text)
        {
            if (String.IsNullOrEmpty(text))
            { 
               return 0; 
            }
            var tmpStr = text.Replace("\t", " ").Trim();
            tmpStr = tmpStr.Replace("\n", " ");
            tmpStr = tmpStr.Replace("\r", " ");
            while (tmpStr.IndexOf("  ") != -1)
              {
                tmpStr = tmpStr.Replace("  ", " ");
              }
            return tmpStr.Split(' ').Length;
        }

Page Keyword: Word count in text, total number of word in Text, count word in text in c#, word count program in text, Find number of word in text code , Number of word in text by c# program. total word count in umbraco. word count in text program.

How to create twitter link from user name in c# or in .Net.

For creating navigation link for twitter user name you can use below function. It just take user name and return navigation link.

        public static string CreateTwitterLinkFromUsername(string username)
        {
            return username != null ? string.Format("{0}", username) : null;
        }

Page keyword: twitter link from user name in .Net, twitter link from user name in C# create twitter link from user name. twitter link from user name in umbraco.

Umbraco: How to Format Date in Umbraco or in .net by c#.

For formatting date use below function.

       public static string FormatDate(DateTime theDate)
        {
            return theDate.ToString("dd MMMM yyyy");
        }

Page Keyword: Format date in .net. Format Date and time in C#. Format Date and time in c#. Date format in umbraco, Date formation in c#.

Umbraco Article