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

C# | Write error log in text file



C# : Write error log in text file


How to write error in text file. Where we can set configuration that we want to write or not, without editing code file.

Create service signature using interface.

public static void WriteLog(string LogValues)
{
 try
 {
  if (!Convert.ToBoolean(ConfigurationManager.AppSettings["writelog"].ToString()))
   return;
// for web application
//var folder = System.Web.HttpContext.Current.Request.PhysicalApplicationPath.ToString() +  "\\ErrorLog\\"
//For Static path
 var folder = ConfigurationManager.AppSettings["LogPath"].ToString();
 
 if (!Directory.Exists(folder))
  {
   Directory.CreateDirectory(folder);
  }
  var fileName = DateTime.Today.ToString("dd-MMM-yy", CultureInfo.InvariantCulture) + ".txt";
  var serverPath = folder + fileName;
  if (!File.Exists(serverPath))
  {
   File.Create(serverPath).Close();
  }
  var w = File.AppendText(serverPath);
  try
  {
   w.WriteLine("\n" + System.DateTime.Now + "\t" + LogValues);

   w.Flush();
   w.Close();
  }
  catch
  {
  }
  finally
  {
   w.Close();
  }
 }
 catch (Exception ex)
 {
  
 }

}

Set configuration in web.config file.

 <add key="writelog" value="true" />
 <add key="logpath" value="D:\ErrorLog\" />

Enjoy to write error log in text file, trace issue and give solution.


MVC | No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'



No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'.


Issue:


error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file


Solution:


Make sure that you installed entityFramework on presentation layer as well.

It will add following configuration in web.config of presentation layer.

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>



And more thing

Please make sure that you have EntityFramework.SqlServer.dll
 

Hope your issue will resolved.

Enjoy :)