How can I easily tell what caused the error – DbEntityValidationException ?

I came across with the situation where I have used Entity Framework 6.0. While calling SaveChanges on my DbContext, I get the following exception:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

 

After going into the exception detail all I could get to know that there is an exception at SaveChanges() method. So this is what I have done:

System.Data.Entity.Validation.DbEntityValidationException was unhandled
 HResult=-2146232032
 Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
 Source=EntityFramework
 StackTrace:
 at System.Data.Entity.Internal.InternalContext.SaveChanges()
 at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
 at System.Data.Entity.DbContext.SaveChanges()
 at ConsoleApplication1.Program.Main() in c:UsersamitmSkyDrivecodeConsoleApplication1ConsoleApplication1Program.cs:line 19
 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
 at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
 at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
 at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
 at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
 at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
 at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
 at System.Threading.ThreadHelper.ThreadStart()
 InnerException:

No where it is telling me about why it has actually occured.

 

Solution:

To solve this problem what I did is I override SaveChanges method, catch the exception of type DbEntityValidationException then get an entire exception through Linq:

public partial class BookContainer : DbContext
 {
 public BookContainer()
 : base("name=BookContainer")
 {
 }
public override int SaveChanges()
 {
 try
 {
 return base.SaveChanges();
 }
 catch (DbEntityValidationException ex)
 {
 // Retrieve the error messages as a list of strings.
 var errorMessages = ex.EntityValidationErrors
 .SelectMany(x => x.ValidationErrors)
 .Select(x => x.ErrorMessage);
 var fullErrorMessage = string.Join("; ", errorMessages);
 var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
 throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
 }
 }

 

Now when I get the exception result, I get it with “Column name” that has caused this trouble.


System.Data.Entity.Validation.DbEntityValidationException was unhandled
 HResult=-2146232032
 Message=Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
The validation errors are: The WebSite field is required.;
The WebSite field is required.;
The WebSite field is required.; The WebSite field is required.
 Source=ConsoleApplication1
 StackTrace:
 at ConsoleApplication1.BookContainer.SaveChanges() in c:UsersamitmSkyDrivecodeConsoleApplication1ConsoleApplication1Book.Context.cs:line 45
 at ConsoleApplication1.Program.Main() in c:UsersamitmSkyDrivecodeConsoleApplication1ConsoleApplication1Program.cs:line 19
 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
 at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
 at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
 at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
 at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
 at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
 at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
 at System.Threading.ThreadHelper.ThreadStart()
 InnerException:

How to download my documents from Azure Blob?

I have been in the position where I’ve been storing data on blob. However, there was a request to export all data in-house so that the same can be given to the third party.

The document ID, which is stored in the SQL database, is given as blob name.

I have managed to achieve this through the following piece of code:

storageConnectionString = “DefaultEndpointsProtocol=https;AccountName=<azure blob name >;AccountKey=<your private Key to blob>”

Settings a = new Settings();

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(a.StorageConnectionString);

using (SqlConnection conn = new SqlConnection(a.ConnectionString))
{
string sqlCommandText = @”select documentID, documentName from documentTable”;

SqlCommand command = new SqlCommand(sqlCommandText, conn);
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(“tra”);

while (reader.Read())
{

int documentID;
if (int.TryParse((reader[“DocID”] ?? “”).ToString(), out documentID))
{

string documentName = reader[“DocName”].ToString();

int subfolderID = documentID / 1000 * 1000;
var blobreference = string.Format(“docsearch/{0}/{1}”, subfolderID, documentID);
// Retrieve reference to a blob named “photo1.jpg”.
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobreference);

if (File.Exists(string.Format(@”C:TRAResume{0}”, documentName)))
{

}
else
{
// Save blob contents to a file.
using (var fileStream = System.IO.File.OpenWrite(string.Format(@”C:TRAResume{0}”, documentName)))
{

if (Program.Exists(blockBlob))
{
blockBlob.DownloadToStream(fileStream);
}
}
}
}

}
}
}
}

public static bool Exists(CloudBlockBlob blob)
{
try
{
blob.FetchAttributes();
return true;
}
catch
{
return false;

}
}

How to create jquery Plugin?

Idea behind this plugin is to catch any event on <a> link and open the URL on new screen.

/*! jQuery anchormaaster Plugin – v1.0 – 18/2/2014
* Copyright CM (c) 2014 codebased@hotmail.com; Licensed MIT */

(function ($) {

// function that go through each link available in the given html object/
// and connect click event for opening a link to the new window.
$.fn.linkExtender = function (options) {

// default settings are merged with options parameter.
var settings = $.extend({
channelmode: 0,
fullscreen: 0,
height: 600,
left: 50,
location: 0,
menubar: 0,
resizable: 1,
scrollbars: 0,
status: 1,
titlebar: 1,
toolbar: 1,
top: 100,
width: 800
}, options || {});

var winprop = JSON.stringify(settings).replace(/}|{|”/g, ”).replace(/:/g, “=”);

// loop through all a link that has been within
return this.find(“a”).each(function () {

$(this).click(function () {

// it did not worked as expected by sending settings object.
// window.open($(this).attr(‘href’), “anchormasterwinpop”, settings);
// hence I’d to use winprop – string based value.
window.open($(this).attr(‘href’), “anchormasterwinpop”, winprop);

// STOP THE CLICK BUBLE!!!
return false;
});
});
};
})(jQuery);

How to Extend string object in JavaScript?

$(function () {

// — DOM is ready to action on.

/*
Summary: startsWith should take a single argument and return true if the provided string is a
prefix of this.
*/

if (typeof String.prototype.startsWith !== ‘function’) {

// checked and there is no startsWith (pre-defined) method.
String.prototype.startsWith = function (prefix) {
return this.indexOf(prefix) == 0;
};
} else {

// raise the log message for the developer.
raiseLog(“startsWith prototype is already defined. Unable to attach StringExtensinos.js.startsWith”);
}

/*
Summary: endsWith should take a single argument and return true if the provided string is a
postfix of this.
*/

if (typeof String.prototype.endsWith !== ‘function’) {

// checked and there is no endsWith (pre-defined) method.
String.prototype.endsWith = function (postfix) {
return this.indexOf(postfix, this.length – postfix.length) !== -1;
};
} else {

// raise the log message for the developer.
raiseLog(“endsWith prototype is already defined. Unable to attach StringExtensinos.js.endsWith”);
}

/*
Summary: This method should remove all html/xml tags from this.
*/

if (typeof String.prototype.stripHtml !== ‘function’) {
// checked and there is o stripHtml (pre-defined) method.
String.prototype.stripHtml = function () {
// By wrapping around p tag we have made
// sure that it is actually a valid html.
return jQuery(‘<p>’ + this + ‘</p>’).text();
};
} else {

// raise the log message for the developer.
raiseLog(“stripHtml prototype is already defined. Unable to attach StringExtensinos.js.stripHtml”);
}

// raise the log to the console. This tool is handy for Mr. developer – F12
function raiseLog(message) {

// ensure that we have a console function available.
// later we may move this object into more jquery form and add a plugin.
if (typeof console == “object” && typeof console.log == ‘function’) {
console.log(message);
}
}
});

ELMAH Vs. Log4Net

  ELMAH Log4Net
  Can go complex if you don’t know what are you after Easier to use as compare to Elmah.
  ELMAH will help you to catch any unhandled exception and store them in order to be checked. Log4Net will do what you will ask it to do. Hence you will have to write the code.
  ELMAH can only be used with Web based application. Log4Net can be used with any windows form/ console application. It can also be used with web based application.
  A very good solution for “Screen of Death”: It can just log.
  It can only be used for exception messages I can be used for any kind of logging.
 

 

Practically speaking, we need both.

And that is why it will be great if we can something in between who can pass out the message from one to another.

 

The ELMAH-Appender is what it does. It communicate with the ELMAH library on behalf of Log4Net. So we can use Log4Net like LogManager.GetLogger(typeof(MvcApplication)).Info(“<message>”).

 

For more details please refer: https://nuget.org/packages/elmahappender_log4net/