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;
}
Wednesday, December 17, 2014
C# CSV to Datatable
Add reference of Microsoft.VisualBasic which would enable TextFieldParser class
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:
- In application pool advanced settings set Start Mode = AlwaysRunning
- In site advanced settings set Preload Enabled = True and Start Automatically = True
Tuesday, July 1, 2014
What's new in ASP.NET MVC 5?
ASP.NET MVC 5 is a framework for building scalable, standards-based web applications using well-established design patterns and the power of ASP.NET and the .NET Framework. Below is the list of features which are bundled in ASP.NET MVC 5.
1) One ASP.NET
MVC Project templates are integrated very efficiently with one ASP.NET experience. Microsoft has finally brought all the ASP.NET related project templates together, and the result is One ASP.NET.
The figure depicted below shows, how the web templates in Visual Studio 2013 are now pointing to a single web application. You can also combine multiple projects like Web API, MVC etc. in case you’re designing a complex system.
The figure depicted below shows, how the web templates in Visual Studio 2013 are now pointing to a single web application. You can also combine multiple projects like Web API, MVC etc. in case you’re designing a complex system.
2) ASP.NET Identity
MVC project templates have been updated to use ASP.NET
identity for authentication and identity management. You can easily configure the type of
authentication at the initial stage of the project and MVC would configure all
the required settings accordingly.
As shown in the screenshot, 3 choices are provided:
No authentication: If user does not want to implement
any authentication or implement a custom authentication
Individual User accounts: Allows you to have full control of user accounts in your
application. Users can create their
account or sign in through social media sites like Facebook, Google etc.
Windows Authentication: If user wants to implement windows
authentication mode in their web application
3) Bootstrap
MVC project templates have been updated to use bootstrap CSS framework to provide a slick and responsive UI for your application which can be easily customized. Bootstrap makes front-end web development faster and easier. It's made for folks of all the skill levels, devices of all shapes, and projects of all sizes.
MVC 5 now provides a neat responsive UI when creating a new web application as depicted in the screenshot below. The layout on the right is for mobile devices.
MVC 5 now provides a neat responsive UI when creating a new web application as depicted in the screenshot below. The layout on the right is for mobile devices.
4) Authentication filters
Prior to ASP.NET MVC 5, there were 4 types of filters:
- Authorization filters
- Action filters
- Result filters
- Exception filters
Previously [Authorization] attribute was used to enforce role based security.
MCV 5 introduces new kind of features called authentication filters, which run prior to authorization filters. The main advantage of using authentication filter is, it runs prior to authorization filters. It allows you to specify authentication logic at action, controller or global level.
The main purpose of adding authentication filters is to separate authentication from authorization (first authenticate, then authorize)
- Authentication verifies who you are
- Authorization verifies what are you authorized to do
5) Filter overrides
Filters can now be overridden for a given action or controller by applying override filter attribute. Override filters specify a set of filter types that should not run for a given scope (action or controller). This allows you to add global filters, but then exclude some from specific actions or controllers.
There are different types of override attributes in ASP.NET MVC 5, which allows you to clear filters by their type:
The example given below, applies “OverrideAuthorization” filter to Index action, which would exclude authorization filter and would override Authorization filter applied at the controller level.
There are different types of override attributes in ASP.NET MVC 5, which allows you to clear filters by their type:
- [OverrideActionFilters]
- [OverrideAuthentication]
- [OverrideAuthorization]
- [OverrideExceptionFilters]
- [OverrideResultFilters]
The example given below, applies “OverrideAuthorization” filter to Index action, which would exclude authorization filter and would override Authorization filter applied at the controller level.
6) Attribute Routing
Routing is the term used by MVC to match a URI to an action. MVC 5 now supports a new type of routing called attribute routing. As the name suggests, attribute routing uses attributes to define routes. It gives you more control over the URIs in your web application.
In the previous versions of MVC, rules were set in RouteConfig.cs file like shown below:
In the previous versions of MVC, rules were set in RouteConfig.cs file like shown below:
The example given above, can be simply defined in MVC 5 like
this:
Attribute routing can be enabled by using a single line of
code in RegisterRoutes:
Monday, June 9, 2014
ASP.NET MVC AJAX error handling through filters and jQuery
Consider a scenario where you make an AJAX request in ASP.NET MVC through jQuery, i.e. $.ajax. If you want to handle server side validations/exceptions and trap them in "error" callback of $.ajax, you can do it in a slick way:
1) Create a filter attribute:
2) Apply filter to controller/action
3) Throw exceptions
4) Catch exceptions in jQuery
1) Create a filter attribute:
public class ClientErrorAttribute : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IExceptionFilter { public void OnException(ExceptionContext filterContext) { var response = filterContext.RequestContext.HttpContext.Response; response.Write(filterContext.Exception.Message); response.ContentType = MediaTypeNames.Text.Plain; filterContext.ExceptionHandled = true; } }
2) Apply filter to controller/action
[ClientError] public class HomeController : Controller { }
3) Throw exceptions
[HttpGet] public JsonResult CheckLogin() { if (!User.IsLoggedIn) { throw new Exception("You are not authorised to perform this operation"); } }
4) Catch exceptions in jQuery
$.ajax({ type: "post", url: "/SomeController/SomeAction", success: function (data, text) { //... }, error: function (request, status, error) { alert(request.responseText); } });
Saturday, May 24, 2014
The name 'model' does not exist in current context
I recently installed Visual Studio 2013 and updated my MVC3 application to MVC4 by following these steps. I noticed that my MVC3 project disabled the intellisense for @model as well as other c# code including LINQ.
Solution:
Create a web.config in the "Views" folder and add following configurations:
<?xml version="1.0"?> <configuration> <configSections> <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> </sectionGroup> </configSections> <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> </namespaces> </pages> </system.web.webPages.razor> <system.web> <pages validateRequest="false" pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <controls> <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" /> </controls> </pages> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="BlockViewHandler"/> <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /> </handlers> </system.webServer> </configuration>
Friday, April 25, 2014
Call a method after multiple AJAX requests are finished through jQuery
You may face a situation where you need to make multiple AJAX requests and call your function after all those requests are completed.
jQuery provides a way to handle this neatly:
jQuery provides a way to handle this neatly:
$.when($.ajax( "/page1" ), $.ajax( "/page2" ) ).then(function( a1, a2)
{
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests
// Each argument is an array with the following structure: [ data, statusText,jqXHR ]
});
{
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests
// Each argument is an array with the following structure: [ data, statusText,jqXHR ]
});
Friday, April 18, 2014
CSS media queries for different Internet Explorer versions
/* IE6/7 uses media, */
@media, {
.container { color: green; }
.item { color: red; }
}
/* IE8 uses \0 */
@media all\0 {
.container { color: brown; }
.item { color: orange; }}
/* IE9 uses \9 */
@media all and (monochrome:0) {
.container { color: yellow\9; } .
.item { color: blue\9; }}
/* IE10 and IE11 both use -ms-high-contrast */
@media all and (-ms-high-contrast:none)
{
.foo { color: green } /* IE10 */
*::-ms-backdrop, .foo { color: red } /* IE11 */
}
Subscribe to:
Posts (Atom)