ASP.Net C#| Download File


  ASP.Net C#| Download File



Code - Method 1:

try
            {
                string strURL = "/Files/filename.pdf";
                WebClient req = new WebClient();
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                response.AddHeader("Content-Disposition""attachment;filename=\"" + strURL + "\"");
                byte[] data = req.DownloadData(Server.MapPath(strURL));
                response.BinaryWrite(data);
                response.End();
            }
            catch (Exception ex)
            {
            }

Code - Method 2:

try
            {
                Response.ContentType = "Application/pdf";
           Response.AppendHeader("Content-Disposition""attachment; filename=TechnicalDocumentforLogin.pdf");
           Response.TransmitFile(Server.MapPath("~/Files/filename.pdf"));
           Response.End();
            }
            catch (Exception ex)
            {
            }

  Enjoy !!!

:)

 

ASP.Net C#| Send Email


  ASP.Net C#| Send Email


Here I write a code to send email and its 100% working if you pass correct value.

HTML:

<div class="container">
       <div style="min-height30px">
           <label id="lblMessage" runat="server"></label>
       </div>
       <div class="row">
           <div class="col-md-6">
 
               <div class="form-group">
                   <label>SMTP:</label>
                   <asp:TextBox ID="txtSMTP" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Port:</label>
                   <asp:TextBox ID="txtPort" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Username</label>
                   <asp:TextBox ID="txtUsername" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Password</label>
                   <asp:TextBox ID="txtPassword" runat="server" TextMode="password" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>SSL Enable</label>
                   <asp:CheckBox ID="chkSSL" runat="server"></asp:CheckBox>
               </div>
           </div>
           <div class="col-md-6">
               <div class="form-group">
                   <label>From:</label>
                   <asp:TextBox ID="txtFrom" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Display Name:</label>
                   <asp:TextBox ID="txtFromDisplay" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>To:</label>
                   <asp:TextBox ID="txtTo" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Subject:</label>
                   <asp:TextBox ID="txtSubject" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <label>Body:</label>
                   <asp:TextBox ID="txtBody" runat="server" CssClass="form-control"></asp:TextBox>
               </div>
               <div class="form-group">
                   <asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" CssClass="btn btn-success" />
               </div>
           </div>
       </div>
   </div>

Code:

using System;
using System.Net;
using System.Net.Mail; 
protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                var mailmessage = new MailMessage { From = new MailAddress(txtFrom.Text.Trim(), txtFromDisplay.Text.Trim()) };
 
                mailmessage.To.Add(txtTo.Text.Trim());
                mailmessage.Subject = txtSubject.Text.Trim();
                mailmessage.Body = txtBody.Text.Trim();
                mailmessage.IsBodyHtml = true;
 
                SmtpClient smtpClient = null;
                smtpClient = new SmtpClient();
 
                smtpClient.Host = txtSMTP.Text.Trim();
                smtpClient.Port = Convert.ToInt32(txtPort.Text.Trim());
                smtpClient.UseDefaultCredentials = false;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;                
                smtpClient.Credentials = new NetworkCredential(txtUsername.Text.Trim(), txtPassword.Text.Trim());
 
                if (chkSSL.Checked)
                    smtpClient.EnableSsl = true;
                else
                    smtpClient.EnableSsl = true;
 
                smtpClient.Send(mailmessage);
                lblMessage.InnerText = "Email sent.";
            }
            catch (Exception ex)
            {
                lblMessage.InnerText = ex.Message;
            }
        }
 
        public static string GenerateRandomString(int length)
        {
            //It will generate string with combination of small,capital letters and numbers
            char[] charArr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
            string randomString = string.Empty;
            Random objRandom = new Random();
            for (int i = 0; i < length; i++)
            {
                //Don't Allow Repetation of Characters
                int x = objRandom.Next(1, charArr.Length);
                if (!randomString.Contains(charArr.GetValue(x).ToString()))
                    randomString += charArr.GetValue(x);
                else
                    i--;
            }
            return randomString;
        }

Method 2

 using (MailMessage email = new MailMessage())
                {
                    email.From = new MailAddress(contact.Email);
                    email.To.Add(toEmail);
                    email.Subject = "Hello World";
                    email.Body = "<h1>Hello</h1>";
                    email.IsBodyHtml = true;
                   email.Attachments.Add(new Attachment("C:\\file.zip"));

                    using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
                    {
                        smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["fromUserName"], password);
                        smtp.EnableSsl = true;
                        smtp.Send(email);
                    }
                }

After 2024

Follow the steps mentioned https://mailtrap.io/blog/gmail-smtp/


Enjoy !!!

:)

 

ASP.Net Webform | Show progress image on page load



ASP.Net Webform | Show progress image on page load


Sometime we need to show loader image before page load on user interface. Here below is the code to implement this.

HTML:

<div>
           <asp:Button ID="btnLoad" runat="server" Text="Load Country" OnClick="btnLoad_Click" />
</div>
        <div>
            <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="CountryName" HeaderText="Country Name" />
                    <asp:BoundField DataField="CountryCode" HeaderText="Country Code" />                    
                </Columns>
            </asp:GridView>

            <div class="loading" align="center">
                Please wait ! Page loading...<br />
                <br />
                <img src="Images/loader.gif" />
                
            </div>
        </div>

 

CSS:

<style type="text/css">
    .modal
    {
        positionfixed;
        top0;
        left0;
        background-colorblack;
        z-index99;
        opacity0.8;
        filteralpha(opacity=80);
        -moz-opacity0.8;
        min-height100%;
        width100%;
    }
    .loading
    {
        font-familyArial;
        font-size10pt;
        border5px solid #67CFF5;
        width200px;
        height100px;
        displaynone;
        positionfixed;
        background-colorWhite;
        z-index999;
    }
</style>

 

JS:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
 
<script type="text/javascript">
    function ShowProgress() {
        setTimeout(function () {
            var modal = $('<div />');
            modal.addClass("modal");
            $('body').append(modal);
            var loading = $(".loading");
            loading.show();
            var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
            var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
            loading.css({ top: top, left: left });
        }, 200);
    }
    $('form').live("submit"function () {
        ShowProgress();
    });
</script>

 

Code:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string script = "$(document).ready(function () { $('[id*=btnLoad]').click(); });";
                ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
            }
        }
 
        protected void btnLoad_Click(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(5000);
 
            string strConnString = ConfigurationManager.ConnectionStrings["constrDemo"].ConnectionString;
            string query = "SELECT * FROM Country";
            SqlCommand cmd = new SqlCommand(query);
            
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds, "Customers");
                        gvCustomers.DataSource = ds;
                        gvCustomers.DataBind();
                    }
                }
            }
            btnLoad.Visible = false;
        }

 

Configuration:

<connectionStrings>
 <add name="constrDemo" connectionString="Data Source=servername;Initial Catalog=datbasename;User id =dbusername;password=dbpassword" />
</connectionStrings>

 Enjoy !!! 

:)

Entityframework | DbEntityValidationException Validation failed for one or more entities



Entityframework | DbEntityValidationException

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities


Resolved entity framework db entity validation exception.

Code:

catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage); 
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }

Another way....

catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
                var fail = new Exception(msg, dbEx);                
                throw fail;
            }

  Enjoy !!!

  :)

MVC | Upload file from server to FTP


MVC | Upload file from server to FTP


Upload file from server to another Server using FTP detail in mvc C#.

Code:

public static class FileUpload
    {
        public static string FTPUpload(HttpPostedFileBase file)
        {
            try
            {
                string _FileName = Path.GetFileName(file.FileName);
                string _path = Path.Combine(Server.MapPath("~/Temp"), _FileName);
                file.SaveAs(_path);
 
               string FtpFilePath = ConfigurationManager.AppSettings["ftpFolder"].ToString() + _FileName;
                       string ftpurl = ConfigurationManager.AppSettings["ftpName"].ToString() + FtpFilePath;  
                       string ftpusername = ConfigurationManager.AppSettings["ftpUsername"].ToString();
                       string ftppassword = ConfigurationManager.AppSettings["ftpPassword"].ToString();
 
 
               string filename = Path.GetFileName(_path);
               string ftpfullpath = ftpurl;
               FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
               ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
 
               ftp.KeepAlive = true;
               ftp.UseBinary = true;
               ftp.Method = WebRequestMethods.Ftp.UploadFile;
 
               FileStream fs = System.IO.File.OpenRead(_path);
               byte[] buffer = new byte[fs.Length];
               fs.Read(buffer, 0, buffer.Length);
               fs.Close();
 
               Stream ftpstream = ftp.GetRequestStream();
               ftpstream.Write(buffer, 0, buffer.Length);
               ftpstream.Close();
           }
           catch (Exception ex)
           {
                throw ex;
           }

            return "success";

        }
    }

 

Configuration settings:

<appSettings>
    <add key="ftpName" value="ftp://testftp/"></add>
    <add key="ftpUsername" value="username"></add>
    <add key="ftpPassword" value="password"></add>
    <add key="ftpFolder" value="folderpath"></add>
  </appSettings>

 

MVC | Upload file on FTP


MVC | Upload file on FTP


Upload file on Server using FTP detail in mvc C#.

Code:

public static class FileUpload
    {
        public static string FTPUpload(HttpPostedFileBase file)
        {
            // //FTP Server URL.
            string ftp = ConfigurationSettings.AppSettings["ftpName"].ToString();
            

            // //FTP Folder name. Leave blank if you want to upload to root folder.
            string ftpFolder = ConfigurationSettings.AppSettings["ftpFolder"].ToString();

            byte[] fileBytes = null;

            // //Read the FileName and convert it to Byte array.
            string fileName = Path.GetFileName(file.FileName);
            using (StreamReader fileStream = new StreamReader(file.InputStream))
            {
                fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
                fileStream.Close();
            }

            try
            {
                //Create FTP Request.
                string path = ftp + ftpFolder + fileName;
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                //Enter FTP Server credentials.
                request.Credentials = new NetworkCredential(ConfigurationSettings.AppSettings["ftpUsername"].ToString(), ConfigurationSettings.AppSettings["ftpPassword"].ToString());
                request.ContentLength = fileBytes.Length;
                request.UsePassive = true;
                request.UseBinary = true;
                request.ServicePoint.ConnectionLimit = fileBytes.Length;
                request.EnableSsl = false;

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(fileBytes, 0, fileBytes.Length);
                    requestStream.Close();
                }

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                response.Close();
            }
            catch (WebException ex)
            {
                //throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
                return (ex.Response as FtpWebResponse).StatusDescription;
            }
            catch (Exception e)
            {
                return e.Message;
            }

            return "success";

        }
    }

 

Configuration settings:

<appSettings>
    <add key="ftpName" value="ftp://testftp/"></add>
    <add key="ftpUsername" value="username"></add>
    <add key="ftpPassword" value="password"></add>
    <add key="ftpFolder" value="folderpath"></add>
  </appSettings>

 

MVC | Upload file



MVC | Upload file 


Upload file in mvc in local folder of web application.


HTML:

@using (Html.BeginForm("UploadFile", "HomeBanner", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
 <div>
  @Html.TextBox("file", "", new { type = "file" }) <br />
  <input type="submit" value="Upload" />
  @ViewBag.Message

 </div>
}

Code:

using System;
using System.IO;
using System.Web;

[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
 try
 {
  if (file.ContentLength > 0)
  {
   string _FileName = Path.GetFileName(file.FileName);
   string _path = Path.Combine(Server.MapPath("~/Temp"), _FileName);
   file.SaveAs(_path);   
  }
  ViewBag.Message = "File Uploaded Successfully!!";
  
  return View();
 }
 catch(Exception ex)
 {
  ViewBag.Message = ex.Message;
  return View();
 }
}