Tuesday, July 4, 2017

TLS 1.2 in .Net 4.0/4.5

Just add this line before you make your web request:

.Net Framework 4.0:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

.Net Framework 4.5+
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls;

IIS services fail to start: "Windows could not start the Windows Process Activation Service - Error 6801: Transaction support within the specified resource manager is not started or was shut down due to an error" when WAS service is started

1) Open command prompt in "Administrative Mode"

2) type "fsutil resource setautoreset true c:\"  without quotation

3) Reboot the server

Fatal error 824


EXEC sp_resetstatus 'DatabaseName' ;
ALTER DATABASE DatabaseName SET EMERGENCY
DBCC checkdb('DatabaseName')
ALTER DATABASE DatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE DBCC CheckDB ('DatabaseName' , REPAIR_ALLOW_DATA_LOSS) 
ALTER DATABASE DatabaseName SET MULTI_USER

Monday, March 28, 2016

Handling jQuery conflicts

Many times you have to deal with multiple versions of jQuery in single page. jQuery provides a way to do that:

 <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
 <script type="text/javascript">  
   var jQuery_1_10_2 = $.noConflict();  
 </script>  
 <script src="~/Scripts/Closure/NewVersion.js"></script>  
 <script src="~/Scripts/jquery-1.7.2.min.js"></script>  
 <script src="~/Scripts/Closure/OldVersion.js"></script>  

HTML
 <div id="container" style="margin-bottom:20px;">  
 </div>  
 <input type="button" id="btnAddNew" value="Add new" />  


Scenario:
There is a div and a button inside HTML page. We want to add new buttons to this div dynamically, when button 'btnAddNew' is clicked. We'll add 2 buttons: 
1) To test the code in older version of jQuery i.e. 1.7.2
2) To test the code in new version i.e. 1.10.2


I've included 2 references of jQuery: version 1.10.2 and 1.7.2.

Version 1.7.2 had live feature, which is obsolete in 1.10.2. 
Version 1.10.2 has on feature, which is missing in 1.7.2.

We'll use both these features on the same page i.e. use both the jQuery versions on the same page.


After including 1.10.2, I've included the script for noConflict. This would tell jQuery to use variable jQuery_1_10_2 instead of default '$' variable for referring jQuery 1.10.2. This means, that if you want to use any function or feature in 1.10.2, you'll have to use jQuery_1_10_2 variable, not '$'.

NewVersion.js contains the code to bind the click event for 'newbtn' class:


 jQuery_1_10_2(function () {  
   jQuery_1_10_2(document).on('click', '.newbtn', function () {  
     alert(jQuery_1_10_2(this).val() + ' clicked!!!');  
   });  
 });  

The code above, binds the click event of the buttons (added dynamically) having the class 'newbtn'. 

OldVersion.js contains the code to bind click event for 'oldjsbtn' class:


 $(function () {  
   $('#btnAddNew').click(function () {  
     var buttonText = "Button " + $('.newbtn').length + 1;  
     $('#container').append('<div class="col-xs-12"><input class="oldjsbtn btn-secondary" type="button" value="Old Js ' + buttonText + '" /><input class="newbtn btn-primary" type="button" value="New Js ' + buttonText + '" /></div>');  
   });  
   $('.oldjsbtn').live('click', function () {  
     alert($(this).val() + ' clicked');  
   });  
 });  


Note that we've used the jQuery variable jQuery_1_10_2 instead of $ here. This can however, make the code very untidy. 

Imaging you'd a javascript file with thousands of lines of code. Changing the $ sign with jQuery_1_10_2 won't be a good solution for that. You'll need to check each and every line and make sure that the code is replaced correctly. This can be cumbersome and time consuming. There is a slick way to resolve this issue using javascript closure.

Closure is basically a self executing function, which initializes and calls itself. You can also pass parameters to this function, which we'll be using in our case. 

Below is our modified NewVersion.js file using closure:


 (function ($) {  
   $(function () {  
     $(document).on('click', '.newbtn', function () {  
       alert($(this).val() + ' clicked!!!');  
     });  
   });  
 })(jQuery_1_10_2);  

We've passed jQuery_1_10_2 as an argument to this closure function and used '$' as alias. Because of it, we'll be able to use '$' throughout our script and get rid of the messy code using the variable jQuery_1_10_2. 

Friday, January 29, 2016

Scrum vs Kanban vs Scrumban

Scrum Kanban Scrumban
Iterations 1-4 week sprints Continuous work alongside releases shorter than one week or bigger iterations like goals Continuous work with short cycles for planning and longer cycles for release
Work routines Push and pull principle mixed with early binding to team members Pull principle with late binding to team members Pull principle with late binding to team members
Scope limits Push and pull principle mixed with early binding to team members Pull principle with late binding to team members Pull principle with late binding to team members
Planning routines Sprint planning Release/iteration planning, demand planning Planning on demand for new tasks
Estimation Must be done before start of sprint Optional Optional
Performance metrics Burndown Cumulative flow diagram, lead time cycle time Average cycle time
Continuous improvement Sprint retrospective Optional Short Kaizen event as an option
Meetings Sprint planning, daily scrum, retrospective Can be avoided Short Kaizen event
Roles Product owner, Scrum master, team Team and other work specific roles Team and other work specific roles
Team members Cross-functional team members Cross-functional team members, specialization is allowed Specialization or preference to tasks
Task size The size that can be completed in sprint Any size Any size
New items in iteration Forbidden Allowed whenever queue allows it Allowed whenever queue allows it
Ownership Owned by a team Supports multiple teams ownership Supports multiple teams ownership
Board Defined/reset each sprint Persistent Persistent
Prioritization Through backlog Optional Recommended on each planning
Rules Constrained process Only a few constraints, flexible process Slightly constrained process
Fit for Enterprise maturity for teams working on product or especially project which is longer than a year Support and maintenance teams, continuous product manufacturing Startups, fast-pace projects, continuous product manufacturing
Continuous improvement Sprint retrospective Optional Short Kaizen event as an option
Meetings Sprint planning, daily scrum, retrospective Can be avoided Short Kaizen event

Thursday, January 28, 2016

Create class from database table

declare @TableName sysname = 'CustomerProfile'
declare @ClassText varchar(max) = 'public class ' + @TableName + '
{'

select @ClassText = @ClassText + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'char'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @ClassText = @ClassText  + '
}'

print @ClassText

Thursday, June 18, 2015

Display loader until the image gets fully loaded using javascript

One of the most common problems with web based applications involving high resolution images is the time taken to load the images. The images would load slowly section by section and it might be annoying for end users. To resolve this issue, we can display a loader before the image gets fully loaded and then display the actual image with a simple fade effect through jQuery:

First set the loader image as the default image

<img src="/ajax-loader.gif" id="profileImage" />


Declare the javascript to handle image loading

function loadImage(control, src) {
        var loadImage = new Image();
        loadImage.src = src;
        if (loadImage.complete) {
            control.hide().attr('src', src).fadeIn();
            loadImage.onload = function () { };
        }
        else {
            loadImage .onload = function () {
                control.hide().attr('src', src).fadeIn();
                loadImage.onload = function () { };
            }
        }
}


Call the function

loadImage($('#profileImage'), 'https://www.microsoft.com/global/learning/en-us/PublishingImages/ms-logo-site-share.png');

- Notice that I've used jQuery to fetch image object i.e. $('#profileImage') because of which I could use control.hide() in the function directly without having to use $(control).





Tuesday, June 9, 2015

LINQ prioritize order

I recently faced a scenario of prioritizing search results filtered by LINQ. Here is the scenario:

I have these records in database table:

1. Superman vs Batman
2. Batman
3. Dark night rises - Batman
4. Batman Returns

I want to search all the records having 'batman' text, however the words starting with batman should be displayed first. i.e. the order should be:

1. Batman
2. Batman Returns
...


This can be achieved using this simple LINQ query:

DbContext.Movies.Where(w => w.Name.Contains("batman")).OrderBy(d => d.Name.IndexOf("batman")).ToList();

I've highlighted the key part of the query which sorts the results based on the Index of word "batman". This means, if the word starts with 'batman', the index would be 0 and it would be displayed first.

Thursday, June 4, 2015

Executing MySQL sub routine in Entity Framework

Entity framework has an easy and slick way to support MySql. In MySQL stored procedures are called stored routines. Routines can be called from Entity Framework using below syntax:


using (var dbContext = new DatabaseContext())
{
  var subRoutine = string.Format("CALL StoredRoutineName('{0}','{1}')", value1, value2);
   signInAttempts = dbContext.Database.SqlQuery<int>(subRoutine,
                     new MySqlParameter("value1", value1),
                     new MySqlParameter("value2", value2)).FirstOrDefault();

}

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

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.

































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.














4) Authentication filters

Prior to ASP.NET MVC 5, there were 4 types of filters:

  1. Authorization filters
  2. Action filters
  3. Result filters
  4. 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
Here is a short overview of how to implement your custom action filter:

























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:

  1. [OverrideActionFilters]
  2. [OverrideAuthentication]
  3. [OverrideAuthorization]
  4. [OverrideExceptionFilters]
  5. [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:
















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: