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 :)

MVC | Could not load file or assembly 'Microsoft.AI.Web' or one of its dependencies



Could not load file or assembly 'Microsoft.AI.Web' or one of its dependencies.

 

 

 If you are getting below error then install or update below nuget package.

Install-Package Microsoft.ApplicationInsights.Web  



I hope your issue will be resolved.

Enjoy !!! :)