Thursday, June 4, 2015

Invalid object name 'dbo.__MigrationHistory'

Recently I faced an issue with Entity Framework 6.0. The error did not crashed the website, but I got it frequently in event viewer. To resolve this, I just added a line in DbContext's constructor:

public DatabaseContext() : base("name=Sample")
{
       Database.SetInitializer<DatabaseContext>(null);
}


If you use an existing database with Code First approach, you may not want to execute any initialization code. You can disable the database initialization process altogether by passing null to SetInitializer() method

Wednesday, December 17, 2014

C# CSV to Datatable

Add reference of  Microsoft.VisualBasic which would enable TextFieldParser class

using Microsoft.VisualBasic.FileIO;

public static DataTable GetDataTabletFromCsvFile(string csvFilePath)
{
    DataTable csvData = new DataTable();
    using (TextFieldParser csvReader = new TextFieldParser(csvFilePath,Encoding.UTF7))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;
        //read column names
        string[] colFields = csvReader.ReadFields();
        foreach (string column in colFields)
        {
            DataColumn datecolumn = new DataColumn(column);
            datecolumn.AllowDBNull = true;
            csvData.Columns.Add(datecolumn);
        }
        while (!csvReader.EndOfData)
        {
            string[] fieldData = csvReader.ReadFields();
            //Making empty value as null
            for (int i = 0; i < fieldData.Length; i++)
            {
                if (fieldData[i] == "")
                {
                    fieldData[i] = null;
                }
            }
            csvData.Rows.Add(fieldData);
        }
    }
    return csvData;
}

ASP.NET MVC partial view to string

protected string RenderPartialViewToString(string viewName, object model)
{
   if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

   using (StringWriter sw = new StringWriter())
  {
     ViewEngineResult viewResult = 
           ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
     ViewContext viewContext = 
          new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
      viewResult.View.Render(viewContext, sw);

      return sw.GetStringBuilder().ToString();
  }
}

Get query string in javascript from URL

function getUrlParameterByName(name) {
     
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
     
}

URL: http://www.nishitvaghela.blogspot.com?page=2&size=10

getUrlParameterByName('page') = 2

The EXECUTE permission was denied on the object 'sp_OACreate'

use [master]
GO

GRANT EXECUTE ON [sys].[sp_OASetProperty] TO [public]
GO

use [master]
GO

GRANT EXECUTE ON [sys].[sp_OAMethod] TO [public]
GO

use [master]
GO

GRANT EXECUTE ON [sys].[sp_OAGetErrorInfo] TO [public]
GO

use [master]
GO

GRANT EXECUTE ON [sys].[sp_OADestroy] TO [public]
GO

use [master]
GO

GRANT EXECUTE ON [sys].[sp_OAStop] TO [public]
GO

use [master]
GO

GRANT EXECUTE ON [sys].[sp_OACreate] TO [public]
GO

use [master]
GO

GRANT EXECUTE ON [sys].[sp_OAGetProperty] TO [public]
GO

sp_configure 'show advanced options', 1
GO

reconfigure
go

exec sp_configure
go

exec sp_configure 'Ole Automation Procedures', 1
go

reconfigure

Entity framework load children objects

The code below would fetch a list of all the categories through entity framework and would include the Products associated with each category and Brands associated with each product.


public class Category
{
  public ICollection<Product> Products;
}

public class Product
{
  public ICollection<Brand> Brands;
}

public class Brand
{
   public string Name{get;set;}
}

using (var db = new DatabaseContext())
{
   var schema = db.Categories
     .Include("Products")
     .Include("Products.Brands").ToList();
}

Thursday, October 16, 2014

Speed up ASP.NET/MVC website loading with IIS tweaks

ASP.NET/MVC websites hosted on a dedicated hosting face problems while loading the website at the start of the day.  It usually takes a while to load it for the first time and then every subsequent requests are returned pretty quickly.  To resolve this issue, you need to make few configurations in IIS:

  1. In application pool advanced settings set Start Mode = AlwaysRunning
  2. In site advanced settings set Preload Enabled = True and Start Automatically = True