Tuesday, September 2, 2014

Difference between Stored Procedure and Function in SQL Server

1. Functions must always return a value (either a scalar value or a table). Stored procedures may return a scalar value, a table value or nothing at all.

2. Functions can have only input parameters whereas Stored Procedures can have input/output parameters .

3. Functions can be called from Stored Procedure whereas Stored Procedures cannot be called from Function.

4. Stored Procedure allows SELECT as well as INSERT/UPDATE/DELETE statement whereas Function allows only SELECT statement.

5. Stored Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.

6. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.

7. The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of function it will be compiled every time.

8. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.

9. Exception can be handled by try-catch block in a Stored Procedure whereas try-catch block cannot be used in a Function.

10. We can go for Transaction Management in Stored Procedure whereas we can't go in Function.

11. Stored procedures are called independently, using the EXEC command, while functions are called from within another SQL statement

Friday, August 8, 2014

A very simple example on System.Reflection in Asp.net

Today I will show you a very simple example on Reflection.

Follows the steps:

Step 1. Create a project with asp.net empty web application and name it "ReflectApp".

Step 2. Create a web form in it and paste following code and run it.

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, 
                            ByVal e As System.EventArgs) Handles Me.Load
        Dim currentAppName = System.Reflection.Assembly.Load("ReflectApp")

        For Each type As Type In currentAppName.GetTypes
            If type.Name = "Customer" Then
                Dim o As Object = Activator.CreateInstance(type)

                Dim mInfo As System.Reflection.MethodInfo = type.GetMethod("getName")

                If mInfo IsNot Nothing Then
                    Dim result As String = mInfo.Invoke(o, Nothing)

                    Response.Write(result)
                End If

                Exit For
            End If

        Next 
    End Sub
    Public Class Customer
        Private Property _Name As String

        Sub New()
            _Name = "John Miller"
        End Sub

        Public Function getName() As String
            Return _Name
        End Function

    End Class

End Class


Result will be: John Miller

You can debug and see how it works.

Thursday, August 7, 2014

Wednesday, August 6, 2014

Explain with example ISNULL, NULLIF and COALESCE in SQL Server


ISNULL : Replaces NULL with the specified replacement value.

NULLIF : Returns a null value if the two specified expressions are equal.

COALESCE : Returns the first non-null argument.(msdn: Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL).

Here are the examples and it's results:

SELECT ISNULL(null,1)
--Result: 1

SELECT NULLIF(1,1)
--Result: NULL

SELECT COALESCE(1,null,null,null)
--Result: 1

SELECT COALESCE(null,2,3,4)
--Result: 2

SELECT COALESCE(null,null,3,4)
--Result: 3

SELECT COALESCE(null,null,null,4)
--Result: 4

SELECT ISNULL(NULLIF(COALESCE(null,null,null,4),4),1)
--Result: 1


Tuesday, August 5, 2014

A very simple example on KnockoutJS in Asp.net

Today I will show you a very simple example on KnockoutJS in Asp.net

Please follows the steps:

Step 1: Create a project with Asp.net empty web application and add web form.

Step 2: Now, paste following code in "body" tag of your aspx page.
<body>
     
    <p>First name: <strong data-bind="text: firstName"></strong></p>
    <p>Last name: <strong data-bind="text: lastName"></strong></p>
    <p>
        First name:
            <input data-bind="value: firstName" />
    </p>
    <p>
        Last name:
            <input data-bind="value: lastName" />
    </p>
    <script
        src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js">
    </script>
    <script>

        function AppViewModel() {
            this.firstName = ko.observable("John");
            this.lastName = ko.observable("Miller");
        }

        // Activates knockout.js
        ko.applyBindings(new AppViewModel());
    </script>
</body>


Now run your web form and try to change first name, it will automatically change the first name in the label as well.

Monday, August 4, 2014

How to bind dynamically HTML Ordered List in Asp.net using AngularJS?

Today I will show you a very simple example on binding HTML Ordered List dynamically in Asp.net using AngularJS.

Follows the steps:

Step 1: Create a project with asp.net empty web application and add web form in it.

Step 2: Now, paste following code in ".aspx" page
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div ng-app="" ng-controller="itemController">
            <ol>
                <li ng-repeat="item in items">{{ item }}
                </li>
            </ol>
        </div>

        <script>
            function itemController($scope) {
                $scope.items = [<%=items%>];
            }

        </script>
        <script 
            src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">

        </script>

    </form>
</body>
</html>


Step 3: Now, paste following code in ".aspx.vb" code behind page
Public Class WebForm1
    Inherits System.Web.UI.Page

    Public items As String = ""

    Protected Sub Page_Load(ByVal sender As Object,
                            ByVal e As System.EventArgs) Handles Me.Load

        If Not Page.IsPostBack Then
            'You can change this items dynamically '
            items = "'Orange', 'Apple', 'Banana', 'Grape', 'Watermelon'"
        End If

    End Sub

End Class


Result will be:

1.Orange
2.Apple
3.Banana
4.Grape
5.Watermelon


Friday, August 1, 2014

How to check or compare that two dates, not including time, are equal? in Asp.net

A very simple example of comparing two dates without including time as below:

One Way:
Dim date1 As Date = CDate("8/1/2014 11:00:00 PM")
Dim date2 As Date = CDate("8/1/2014 02:25:15 AM")

Dim result As Boolean = date1.Date.Equals(date2.Date)
'Result: True


Second Way:
Dim date1 As Date = CDate("8/1/2014 11:00:00 PM").ToShortDateString()
Dim date2 As Date = CDate("8/1/2014 02:25:15 AM").ToShortDateString()

Dim result As Boolean = Date.Equals(date1, date2)
'Result: True 


Thursday, July 31, 2014

How to display data on Asp.net web form without postback? using JSON, JQuery.ajax and WebMethod

To display data on web form without postback, we will use JSON, JQuery $.ajax, WebMethod and JavascriptSerializer. Sometime we need some data to be displayed when user wants it. Without user request, we don't want to show that data on aspx page. In this situation, we should give one button, so whenever user wants it, he will click and get the result.

How do we achieve this? just follows the steps:

Step 1: Create a project with Asp.net empty web application. and add "Default.aspx" page.

Step 2: In Default.aspx page, add following code.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script> 
             function getRandomNumber() {
                 
                $.ajax({

                    url: "Default.aspx/getRandomNumber",
                    data: '',
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (mydata) {

                        var i = JSON.parse(mydata.d);
                        $("#lblRandomNumber").text(i);
                         
                    }
                });
            }  
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnRandomNumber" runat="server" 
                OnClientClick="javascript:getRandomNumber(); return false;"   
                Text="Get Random Number" />
            <asp:Label ID="lblRandomNumber" runat="server" ></asp:Label>
        </div>
    </form>
</body>
</html>


Step 3: Now, In Default.aspx.vb page, add following code.
Imports System.Web.Services
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services

Public Class _Default
    Inherits System.Web.UI.Page
     
    <WebMethod> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Shared Function getRandomNumber() As String

        Dim s As String = New Random().Next(100).ToString()
        Dim ser As New JavaScriptSerializer()
        Dim jsonString = ser.Serialize(s)
        Return jsonString
    End Function
     
End Class


Step 4: Now run it, and click on "get random number" button to get the random number without postback.



Wednesday, July 30, 2014

The thread '<No Name>' (0x12f8) has exited with code 0 (0x0). on await

Issue on Await: The thread '<No Name>' (0x12f8) has exited with code 0 (0x0). on await

This is thread deadlock issue. To avoid this issue, you should use ConfigureAwait(false) to make the runtime continue in a different thread.

await Task.WhenAll(aAsync, bAsync).ConfigureAwait(false);


The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Today I was working on Asp.net 4.5 website and I got following error:

The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

I have solved this issue by adding one line in web.config file:

    <compilation debug="true" targetFramework="4.5">
      <assemblies> 
        <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> 
      </assemblies>
    </compilation>


I got three of them, I have added all those assemblies into web.config like above and it works perfect.

How to convert JSON string to Javascript object?

You can convert JSON String to JavaScript Object Using JSON.parse method of JavaScript.

<script>
   //Json string
   var customer = '{"Name":"John","City":"NJ"}';
   var customers = '[{"Name":"John","City":"NJ"},{"Name":"Miller","City":"PA"}]';

   //Converting Json to Javascript Object
   var Customer = JSON.parse(customer);
   var Customers = JSON.parse(customers);

   //Result
   alert(Customer.Name);
   alert(Customers[1].Name);

</script>


Tuesday, July 29, 2014

How to connect Salesforce from Asp.net? Salesforce Integration in Asp.net

Today I will show you how to use new salesforce toolkit for .NET Application. Follows the steps:

Step 1. Create a project with C# ASP.NET 4.5 empty web application.

Step 2. Right click on this project and click on “Manage NuGet Packages”. Now search for “salesforce” and install “DeveloperForce.Force” NuGet package like this: see screen.



Step 3. After installing this package, add new webform in the project. Name it “Default.aspx”

Step 4. Before I show you complete code, you need five things from salesforce: “ConsumerKey, ConsumerSecret, username, password and security token”.

Note:A security token is an automatically generated key that you must add to the end of your password in order to log into Salesforce from an untrusted network. For example, if your password is mypassword, and your security token is XXXXXXXXXX, then you must enter mypasswordXXXXXXXXXX to log in.

Step 5. Paste following code in your “Default.aspx.cs” page.

    public partial class Default : System.Web.UI.Page
    {
        List<contact> Contacts;
        protected void Page_Load(object sender, EventArgs e)
        {
            Do().Wait();

            foreach (var item in Contacts)
            {
                Response.Write(item.LastName + ",");
            }
        }
        async Task Do()
        {
            //get credential values
            string consumerkey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
            string consumersecret = "XXXXXXXXXXXXXXXXX";
            string username = "XXXXXXXXXXX";
            string password = "mypasswordXXXXXXXXXX";

            //create auth client to retrieve token
            var auth = new AuthenticationClient();

            //get back URL and token
            await auth.UsernamePasswordAsync(consumerkey, 
                       consumersecret, username, password);

            var instanceUrl = auth.InstanceUrl;
            var accessToken = auth.AccessToken;
            var apiVersion = auth.ApiVersion;
            var client = new ForceClient(instanceUrl, accessToken, apiVersion);

            var contacts = await 
                client.QueryAsync<contact>("SELECT Id, LastName From Contact");

            Contacts = contacts.records;

        }
        public class Contact
        {
            public string Id { get; set; }
            public string LastName { get; set; }
        }

    }


Now, run your application and it works perfect :)

I hope this article will help you in connecting Salesforce from Asp.Net

Monday, July 28, 2014

What is the difference between IEnumerable and IEnumerator? ASP.Net

IEnumerable is an interface for all non-generic collections that can be enumerated. IEnumerable contains a single method, GetEnumerator, which returns an IEnumerator.

Syntax:
public interface IEnumerable
{
IEnumerator GetEnumerator();
}


IEnumerator provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

Syntax:
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}


Friday, July 25, 2014

Partitions in Multidimensional Models (SSAS, SQL Server 2014)

In Analysis Services, a partition provides the physical storage of fact data loaded into a measure group. A single partition is created for each measure group automatically, but it is common to create additional partitions that further segment the data, resulting in more efficient processing and faster query performance.

Processing is more efficient because partitions can be processed independently and in parallel, on one or more servers. Queries run faster because each partition can be configured to have storage modes and aggregation optimizations that result in shorter response times. For example, choosing MOLAP storage for partitions containing newer data is typically faster than ROLAP. Likewise, if you partition by date, partitions containing newer data can have more optimizations than partitions containing older data that is accessed less frequently. Note that varying storage and aggregation design by partition will have a negative impact on future merge operations. Be sure to consider whether merging is an essential component of your partition management strategy before optimizing individual partitions.

Dimensions in Multidimensional Models (SSAS, SQL Server 2014)

A database dimension is a collection of related objects, called attributes, which can be used to provide information about fact data in one or more cubes. For example, typical attributes in a product dimension might be product name, product category, product line, product size, and product price. These objects are bound to one or more columns in one or more tables in a data source view. By default, these attributes are visible as attribute hierarchies and can be used to understand the fact data in a cube. Attributes can be organized into user-defined hierarchies that provide navigational paths to assist users when browsing the data in a cube.

Cubes contain all the dimensions on which users base their analyses of fact data. An instance of a database dimension in a cube is called a cube dimension and relates to one or more measure groups in the cube. A database dimension can be used multiple times in a cube. For example, a fact table can have multiple time-related facts, and a separate cube dimension can be defined to assist in analyzing each time-related fact. However, only one time-related database dimension needs to exist, which also means that only one time-related relational database table needs to exist to support multiple cube dimensions based on time.

Cubes in Multidimensional Models (SSAS, Sql Server 2014)

A cube is a multidimensional structure that contains information for analytical purposes; the main constituents of a cube are dimensions and measures. Dimensions define the structure of the cube that you use to slice and dice over, and measures provide aggregated numerical values of interest to the end user. As a logical structure, a cube allows a client application to retrieve values, of measures, as if they were contained in cells in the cube; cells are defined for every possible summarized value. A cell, in the cube, is defined by the intersection of dimension members and contains the aggregated values of the measures at that specific intersection.

Data Source Views in Multidimensional Models (DSV in SSAS) Sql Server 2014

A data source view (DSV) is an abstraction of a relational data source that becomes the basis of the cubes and dimensions you create in a multidimensional project. The purpose of a DSV is to give you control over the data structures used in your project, and to work independently of the underlying data sources (for example, the ability to rename or concatenate columns without directly modifying the original data source).

You can build multiple data source views in an Analysis Services project or database on one or more data sources, and construct each one to satisfy the requirements for a different solution.

Thursday, July 24, 2014

Merge Transformation vs Union All Transformation in SSIS

The main difference is: Merge Transformation takes two inputs and gives one output whereas Union All Transformation takes multiple inputs and gives one output

Merge Transformation:

The Merge transformation combines two sorted datasets into a single dataset. The rows from each dataset are inserted into the output based on values in their key columns.

By including the Merge transformation in a data flow, you can perform the following tasks:

• Merge data from two data sources, such as tables and files.
• Create complex datasets by nesting Merge transformations.
• Remerge rows after correcting errors in the data.

Union All Transformation:

The Union All transformation combines multiple inputs into one output. For example, the outputs from five different Flat File sources can be inputs to the Union All transformation and combined into one output.

The Merge transformation is similar to the Union All transformations. Use the Union All transformation instead of the Merge transformation in the following situations:

• The transformation inputs are not sorted.
• The combined output does not need to be sorted.
• The transformation has more than two inputs.


Wednesday, July 23, 2014

How can i convert LookupSet result, which is in array, into comma separated? SSRS

You can convert array to comma separated string by using Join() function.

=JOIN(LookupSet(Fields!ID.Value, Fields!ID.Value, Fields!Name.Value, "Sections"),",")


Syntax:
LookupSet(source_expression, destination_expression, result_expression, dataset)



How can i find all matching values from other dataset based on current dataset field ? (SSRS 2008 R2)

You can find all matching values of another dataset by using LookupSet() function.

Syntax:
LookupSet(source_expression, destination_expression, result_expression, dataset)



How can i find a value from other dataset based on current dataset field ? (SSRS 2008 R2)

You can find a value of another dataset by using Lookup() function.

Syntax:
Lookup(source_expression, destination_expression, result_expression, dataset)



How can i show created by user in the report? or current logged in user in SSRS?

You can get current logged in user in SSRS by User!UserID property. This property gives you the user name of the person who is running the report.

How to check the time it takes to run a report in SSRS? SQL Server 2012

You can check that from executionLog3 table, if you do not have a dependency on an older view, for example ExecutionLog.

You can use Execution Log to find out how many milliseconds of processing time has spent on each processing phase.


Use ReportServer
select * from ExecutionLog3



Tuesday, July 22, 2014

How to apply style to all disabled buttons throughout the application? Asp.Net, CSS

To apply style to disabled button in Asp.net like this:

  .button:disabled
  { 
    color:gray;
    CURSOR: default;
  }


To apply style to button only in Asp.net like this:

  .button
  { 
    CURSOR:pointer; 
  }


Monday, July 21, 2014

What is, Why we need, How to implement IQueryable<T>? C#.Net

IQueryable provides ability to query against specific data.

Why we need? Let’s take a scenario. Assume that you have created one class which is returning all the customers and you want to give ability to query on those customers to the developers. As a Technical Leader, in BLL layer, you have created one repository class and given to the team. But you are not aware that on which page what type of filters they need. So the best solution is to give some power to developer, so that they can also query on that data.

Here is the simple example/implementation of IQueryable<T>. You can copy and paste in your visual studio to understand more.

        protected void Page_Load(object sender, EventArgs e)
        {

            using(CustomerRepository cr = new CustomerRepository())
            {

                IQueryable<Customer> fCust = cr.getCustomers()
                    .Where(c => c.City_Id > 2);

                foreach (var item in fCust)
                {
                    Response.Write(string.Format(
                        "<br>Customer {0}'s cityId is {1}",
                        item.Name, item.City_Id));
                }

            }
             
        }

        public class CustomerRepository : IDisposable
        {
            IQueryable<Customer> iCust;
            MyTestEntities db;

            public CustomerRepository()
            {
                db = new MyTestEntities();
            }

            public IQueryable<Customer> getCustomers()
            {
                iCust = (from Customer c in db.Customers 
                            select c);

                return iCust;
            }

            public void Dispose()
            {
                db.Dispose(); 
            }
        }


Friday, July 18, 2014

Thursday, July 17, 2014

What is HTML5?

HTML5 is the latest standard for HTML.

It has designed to deliver rich content without the need for additional plugins.  It supports everything from animation to graphics, music to movies, and can also be used to build complicated web applications.

HTML5 is compatible with a PC, or a Tablet, a Smartphone, or a Smart TV.

Wednesday, July 16, 2014

You do not have permission to view this directory or page because of the access control list (ACL) configuration or encryption settings for this resource on the Web server. IIS, Asp.Net

I got following error :

HTTP Error 401.3 - Unauthorized
You do not have permission to view this directory or page because of the access control list (ACL) configuration or encryption settings for this resource on the Web server.

I have tried different solutions such as changing permission on folder, and than changing permission on IIS website to everyone etc...

But nothing works, Finally I have changed in "IIS->Authentication->Edit Anonymous Authentication to Application pool Identity instead of specific user". It worked perfectly.

IIS Screen shot is below for reference purpose:


How can I set the SRC attribute to an IFRAME with JQuery?

You can set the SRC attribute of the iFrame using JQuery like following:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>

     $(document).ready(function(){

          $("#btn").click(function () {
          
             $("#iframe").attr("src", "Home.aspx");
             return false;

          });

      });

</script>



Tuesday, July 15, 2014

Use "Dictionary" instead of "Hashtable" – Performance Tips for Asp.Net

Tip 6. Use Dictionary instead of Hashtable

Hashtable has less performance than Dictionary because of Boxing and Unboxing. Dictionary is strongly typed key/value pair – Dictionary(Of TKey, TValue). Comparing both as following:

        Dim objDictionary As New Dictionary(Of String, String)
        Dim objHashtable As New Hashtable

        Dim sw As New Stopwatch
        sw.Start()

        For index = 1 To 1000000 Step 1
            Dim str As String = index.ToString & "i"
            objDictionary.Add(str, "Mitesh")
        Next

        Response.Write("<br>Dictionary Add time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


        sw = New Stopwatch
        sw.Start()

        For index = 1 To 1000000 Step 1
            Dim str As String = index.ToString & "i"
            objHashtable.Add(str, "Mitesh")
        Next

        Response.Write("<br>Hashtable Add time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


        sw = New Stopwatch
        sw.Start()

        For Each s As String In objDictionary.Keys

        Next

        Response.Write("<br>Dictionary Loop time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


        sw = New Stopwatch
        sw.Start()

        For Each s As String In objHashtable.Keys

        Next

        Response.Write("<br>Hashtable Loop time: " _
                       & sw.ElapsedMilliseconds.ToString())
        sw.Stop()
        sw = Nothing


Result will be :

Dictionary Add time: 278 ms
Hashtable Add time: 536 ms
Dictionary Loop time: 8 ms
Hashtable Loop time: 49 ms



There are other dictionary collections available like:

ConcurrentDictionary(Of TKey, TValue)
SortedDictionary(Of TKey, TValue)
ReadOnlyDictionary(Of TKey, TValue)
HybridDictionary
ListDictionary
OrderedDictionary
StringDictionary


Monday, July 14, 2014

VB.Net: Hashset(Of T) vs List(Of T), C#.Net: HashSet<T> vs List<T>

Here are the differences.

1. List(Of T) can contain duplicates.
Hashset(Of T) contains unique values, No duplicates. Example below:

         
        Dim ls As New List(Of Integer)
        ls.Add(3)
        ls.Add(2)
        ls.Add(1)
        ls.Add(1)
        'Result: 3, 2, 1, 1 '

        Dim hs As New HashSet(Of Integer)
        hs.Add(3)
        hs.Add(2)
        hs.Add(1)
        hs.Add(1)
        'Result: 3, 2, 1 '


2. In List(Of T), Order can be predictable
But In Hashset(Of T), Order can not be predictable

        ls.Remove(2)
        ls.Add(4)
        'Result: 3, 1, 1, 4 '

        hs.Remove(2)
        hs.Add(4)
        'Result: 3, 4, 1 '


3. List(Of T) doesn't have properties like IntersectWith, UnionWith,
IsProperSubsetOf, IsProperSupersetOf, ExceptWith, SymmetricExceptWith
Hashset(Of T) does have all these properties (IntersectWith, UnionWith,
IsProperSubsetOf, IsProperSupersetOf, ExceptWith , SymmetricExceptWith)


Hashset(Of T)


The HashSet(Of T) class provides high-performance set operations. The capacity of a HashSet(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object.

List(Of T)


The List(Of T) class is the generic equivalent of the ArrayList class. It implements the IList(Of T) generic interface by using an array whose size is dynamically increased as required.You can add items to a List(Of T) by using the Add or AddRange methods

Friday, July 11, 2014

Can I compress ASP.NET session-state data?

Yes, You can compress asp.net session-state data with compressionEnabled attribute. When the CompressionEnabled value is set to true, ASP.NET uses the GZipStream class to compress and expand session-state data. This attribute for the sessionState element can be mentioned in the web.config, like this:

<sessionState compressionEnabled="true">     
</sessionState>


Thursday, July 10, 2014

Adding custom code or external assembly to Local Reports .RDLC in Visual Studio.NET causes error

Today i was working on console application which is generating automatic notices using .rdlc file. I was adding barcode into each page of dynamic generated N number of pages. which i have decided to accomplish by referencing external assembly which has one function from where i can pass the parameter and it's give me barcode in terms of bytes. but while adding that assembly i got following error.

"Error while loading code module: ‘Neodynamic.SDK.Barcode, Version=4.0.2000.0, Culture=neutral, PublicKeyToken=c6b33c3093a0d4cd’. Details: Could not load file or assembly 'Neodynamic.SDK.Barcode, Version=4.0.2000.0, Culture=neutral, PublicKeyToken=c6b33c3093a0d4cd' or one of its dependencies. The system cannot find the file specified. "

There are lots of options to solve on internet like adding into "private assemblies" folder of visual studio program files, or add localreport.AddTrustedCodeModuleInCurrentAppDomain etc....

but nothing works. finally i got the solution and it's very simple.

To solve, just do following:

Step 1. Add your external assembly into bin directory of your application, in my case, i am using console application so i moved there.

Step 2. Right click on your "xyz.rdlc" file and click on properties and change "Build Action: None" and "Copy to Output Directory: Do not copy".

That's it.
You can run the application and it will generate report smoothly.
some of the screen shots which i would like to share, so you can see and understand it visually as well.





Wednesday, July 9, 2014

How to convert Byte Array to Image in VB.NET?

You can convert byte array to Image like this.

Public Function byteArrayToImage(ByVal byteArray As Byte()) _
   As System.Drawing.Image

   Dim ms As New System.IO.MemoryStream(byteArray)
   Dim returnImage As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
   Return returnImage
End Function

How to convert Image to Byte Array in VB.NET?

You can convert Image to Byte Array like this.

    Public Function imageToByteArray(ByVal image As System.Drawing.Image) As Byte()
        Dim ms As New System.IO.MemoryStream()
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
        Return ms.ToArray
    End Function

What is Pipes? with a simple example in the .Net Framework

A pipe is a section of shared memory that processes use for communication. There are two types of pipes:

1. Anonymous pipes (Always for local communication, not for network communication)

2. Named pipes (For communication between server and clients. Any process can act as either a named pipe server or client, or both)

Namespace : System.IO.Pipes

To implement NamedPipes in the .Net Framework, Use “NamedPipeServerStreem” and “NamedPipeClientStream” classes.

Server Code Example:

Dim pipeServer As New NamedPipeServerStream("mypipe", PipeDirection.Out)
pipeServer.WaitForConnection()
Try 
   Dim sw As New StreamWriter(pipeServer)
   sw.AutoFlush = True 
   sw.WriteLine(Console.ReadLine())
Catch ex As IOException 
   Console.WriteLine("ERROR: {0}", ex.Message)
End Try 
 


Client Code Example:


Dim pipeClient As New NamedPipeClientStream("localhost", _
                    "mypipe", PipeDirection.In, PipeOptions.None)
pipeClient.Connect()
Dim sr As New StreamReader(pipeClient)
Dim temp As String

temp = sr.ReadLine()
While Not temp Is Nothing
   Console.WriteLine("From server: {0}", temp)
   temp = sr.ReadLine()
End While
Console.Write("Press Enter to continue...")
Console.ReadLine()
 


Tuesday, July 8, 2014

Inversion of control and Dependency injection – Design Pattern

I am going to show you a very simple example on IoC (Inversion of Control) and DI (Dependency Injection). I will show you problem, solution based on design pattern and implementation based on design pattern.

Problem: Tight Coupling

    Public Class Customer

        Private objOrder As Order

        Public Sub New()
            objOrder = New Order 'Issue: Aware of concrete class'
        End Sub

    End Class

    Public Class Order

    End Class


Solution: Inversion of Control

    Public Class Customer

        Private objOrder As Order

        Public Sub New(ByVal objO As Order) 'IoC concept: Passing Object'
            objOrder = objO 'instead of creating it'
        End Sub

    End Class

    Public Class Order

    End Class

    Sub Main()

        Dim objOrder As New Order
        Dim objCustomer As New Customer(objOrder)

    End Sub


Implementation: Dependency Injection


So, basically IoC is a principal and DI is implementation way. You can implement DI in four different way.

1. A constructor injection
2. Parameter injection
3. A setter injection
4. An Interface injection

So following is the example of “Constructor Injection”.

    Public Class Customer

        Private iDOrder As IDairyOrder

        Public Sub New(ByVal objDOrder As IDairyOrder) 'Passing Interface'
            iDOrder = objDOrder 'Instead of passing concreate class object'
        End Sub

    End Class

    Public Interface IDairyOrder

    End Interface

    Public Class Order1
        Implements IDairyOrder

    End Class

    Public Class Order2
        Implements IDairyOrder

    End Class

    Sub Main()
        Dim iDOrder as IDairyOrder
        iDOrder = New Order1
        Dim objCustomer As New Customer(iDOrder)

        iDOrder = New Order2
        objCustomer = New Customer(iDOrder)

    End Sub


Monday, July 7, 2014

A Very Simple Example on Asynchronous Programming in ASP.NET 4.5

Tip 5. Use Asynchronous Programming to give speed to your code wherever possible

Today i will show you a very simple example of Asynchronous Programming. This example gives you an idea about how to increase speed of your web application using Asynchronous Programming. Let's start with traditional code and it's result. You can copy and paste this code in your aspx.vb page to understand more.

Imports System.IO
Imports System.Threading.Tasks

Public Class Home
    Inherits System.Web.UI.Page
 Protected Sub Page_Load(ByVal sender As Object, 
                        ByVal e As System.EventArgs) Handles Me.Load
        Dim sw As Stopwatch = Stopwatch.StartNew()


        Dim trainId As Integer = bookTrain()
        Dim hotelId As Integer = bookHotel()
        Dim meetingLocation As String = arrangMeetingLocation()

        Response.Write("<br>Finished all task: " 
                       & sw.ElapsedMilliseconds() / 1000.0)

    End Sub

    Dim rand As New Random(100)

    Private Function bookTrain() As Integer
        Response.Write("<br>booking Tain...")
        Threading.Thread.Sleep(5000)
        Response.Write("<br>booked Train.")

        Return rand.Next()
    End Function

    Private Function bookHotel() As Integer
        Response.Write("<br>booking Hotel...")
        Threading.Thread.Sleep(7000)
        Response.Write("<br>booked Hotel.")

        Return rand.Next()
    End Function

    Private Function arrangMeetingLocation() As String
        Response.Write("<br>arranging meeting location...")
        Threading.Thread.Sleep(4000)
        Response.Write("<br>arranged meeting location.")

        Return "meetingPlaceName"
    End Function
End Class

Result will be:

booking Tain...
booked Train.
booking Hotel...
booked Hotel.
arranging meeting location...
arranged meeting location.
Finished all task: 16.018 seconds


As you can see in above code, there is no dependency on each other. so we can run these all methods parallel.
Now, let's use Asynchronous Programming. See the following code and it's result. You can copy and paste this code in your aspx.vb page to understand more.
Imports System.IO
Imports System.Threading.Tasks

Public Class Home
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, 
                   ByVal e As System.EventArgs) Handles Me.Load
        Dim sw As Stopwatch = Stopwatch.StartNew()

        Dim trainTask As Task(Of Integer) = 
             Task.Factory.StartNew(Of Integer)(Function() bookTrain())

        'Each Task will start new thread, so it will run parallel.'
        Dim hotelTask As Task(Of Integer) = 
             Task.Factory.StartNew(Of Integer)(Function() bookHotel())

        Dim meetingLoc As Task(Of String) = 
             Task.Factory.StartNew(Of String)(Function() arrangMeetingLocation())

        Response.Write(String.Format(
                  "<br>train Id: {0}, hotel Id: {1}, meeting Loc: {2}", 
                  trainTask.Result, hotelTask.Result, meetingLoc.Result))

        'If you do not write result '
        'and you want to wait until task completed, '
        'write following line'
        'Task.WaitAll(trainTask, hotelTask, meetingLocId)'

        Response.Write("<br>Finished all task: " 
                    & sw.ElapsedMilliseconds() / 1000.0)

    End Sub

    Dim rand As New Random(100)

    Private Function bookTrain() As Integer
        Response.Write("<br>booking Tain...")
        Threading.Thread.Sleep(5000)
        Response.Write("<br>booked Train.")

        Return rand.Next()
    End Function

    Private Function bookHotel() As Integer
        Response.Write("<br>booking Hotel...")
        Threading.Thread.Sleep(7000)
        Response.Write("<br>booked Hotel.")

        Return rand.Next()
    End Function

    Private Function arrangMeetingLocation() As String
        Response.Write("<br>arranging meeting location...")
        Threading.Thread.Sleep(4000)
        Response.Write("<br>arranged meeting location.")

        Return "meetingPlaceName"
    End Function
End Class

Result will be:

booking Tain...
booking Hotel...
arranging meeting location...
arranged meeting location.
booked Train.
booked Hotel.
train Id: 2080427802, hotel Id: 341851734, meeting Loc: meetingPlaceName
Finished all task: 7.003 seconds

Thursday, July 3, 2014

Explain ASP.NET Identity

Asp.Net Membership has evolved over the years. Now web is more social. People are using facebook, twitter and other sources. Users are now demanding the way where they can login with the facebook accout, twitter accout or any other social account. The concept of login with username and password that they have registered on your own application has been gone. A modern membership system must enable redirection-based log-ins to authentication providers such as Facebook, Twitter, and others.

Asp.net Identity has developed with following goals:

1. One ASP.NET Identity system

• ASP.NET Identity can be used with all of the ASP.NET frameworks, such as ASP.NET MVC, Web Forms, Web Pages, Web API, and SignalR.

• ASP.NET Identity can be used when you are building web, phone, store, or hybrid applications.

2. Ease of plugging in profile data about the user

• You have control over the schema of user and profile information. For example, you can easily enable the system to store birth dates entered by users when they register an account in your application.

3. Persistence control

• By default, the ASP.NET Identity system stores all the user information in a database. ASP.NET Identity uses Entity Framework Code First to implement all of its persistence mechanism.

• Since you control the database schema, common tasks such as changing table names or changing the data type of primary keys is simple to do.

• It's easy to plug in different storage mechanisms such as SharePoint, Windows Azure Storage Table Service, NoSQL databases, etc., without having to throw System.NotImplementedExceptions exceptions.

4. Unit testability

• ASP.NET Identity makes the web application more unit testable. You can write unit tests for the parts of your application that use ASP.NET Identity.

5. Role provider

• There is a role provider which lets you restrict access to parts of your application by roles. You can easily create roles such as “Admin” and add users to roles.

6. Claims Based

• ASP.NET Identity supports claims-based authentication, where the user’s identity is represented as a set of claims. Claims allow developers to be a lot more expressive in describing a user’s identity than roles allow. Whereas role membership is just a boolean (member or non-member), a claim can include rich information about the user’s identity and membership.

7. Social Login Providers

• You can easily add social log-ins such as Microsoft Account, Facebook, Twitter, Google, and others to your application, and store the user-specific data in your application.

8. Windows Azure Active Directory

• You can also add log-in functionality using Windows Azure Active Directory, and store the user-specific data in your application.

9. OWIN Integration

• ASP.NET authentication is now based on OWIN middleware that can be used on any OWIN-based host. ASP.NET Identity does not have any dependency on System.Web. It is a fully compliant OWIN framework and can be used in any OWIN hosted application.

• ASP.NET Identity uses OWIN Authentication for log-in/log-out of users in the web site. This means that instead of using FormsAuthentication to generate the cookie, the application uses OWIN CookieAuthentication to do that.

10. NuGet package

• ASP.NET Identity is redistributed as a NuGet package which is installed in the ASP.NET MVC, Web Forms and Web API templates that ship with Visual Studio 2013. You can download this NuGet package from the NuGet gallery.

• Releasing ASP.NET Identity as a NuGet package makes it easier for the ASP.NET team to iterate on new features and bug fixes, and deliver these to developers in an agile manner.



Wednesday, July 2, 2014

How to do INNER JOIN, LEFT JOIN and RIGHT JOIN in LINQ as well as in SQL? Part 2

Before you see this VB.Net LINQ Query, Please go through Part 1.

Now we will write LINQ Queries in VB.Net for INNER JOIN, LEFT JOIN and RIGHT JOIN.

            
       Using db As New MyTestEntities

            'Inner Join '
            Dim results = (From cust As Customer In db.Customers _
                           Join ct As City In db.Cities _
                           On ct.Id Equals cust.City_Id _
                           Select cust.Name).ToList()

            'Left Join '
            results = (From cust As Customer In db.Customers _
                           Group Join ct As City In db.Cities _
                           On ct.Id Equals cust.City_Id Into Joined = Group _
                           From lj In Joined.DefaultIfEmpty() _
                           Select cust.Name).ToList()

            'Right Join (Just swap it)  '
            results = (From ct As City In db.Cities _
                           Group Join cust As Customer In db.Customers _
                           On ct.Id Equals cust.City_Id Into Joined = Group _
                           From rj In Joined.DefaultIfEmpty() _
                           Select ct.Name).ToList()

        End Using 


Tuesday, July 1, 2014

HttpResponse.IsClientConnected - Performance Tips for ASP.NET Applications

Tip 4. HttpResponse.IsClientConnected

Before you start any large operation, make sure you check "Response.IsClientConnected"
if (Response.IsClientConnected)
{

// If client is still connected, then start your large operation here...

}


Monday, June 30, 2014

Asp.net Security: EnableViewStateMac Property

For Asp.net web application security, you should never set EnableViewStateMac to false. Because A ViewStateMac is an encrypted version of the hidden variable that a page's view state is persisted to when the page is sent to the browser. When this property is set to true, the encrypted view state is checked to verify that it has not been tampered with on the client.

By default value for EnableViewStateMac is true. MAC stands for Message Authentication Codes. It gets or sets a value indicating whether ASP.NET should check message authentication codes (MAC) in the page's view state when the page is posted back from the client.

Do not set this property in code. Set the EnableViewStateMac attribute using the @ Page directive in the .aspx file. When the page is requested, the dynamically generated class sets the property.

<%@ Page language="C#" EnableViewStateMac="true" %>

Note: This attribute should never be set to false in a production Web site, even if the application or page does not use view state. The view state MAC helps ensure the security of other ASP.NET functions in addition to view state.

In Asp.net 4.5.2, the runtime enforces EnableViewStateMac=true. Even if you set it to false, the runtime will ignores this value and proceeds with the value set to true.

Friday, June 27, 2014

Very Simple WCF Example with IIS in Asp.net

Today I would like to show you very simple example on WCF hosted on IIS. I am using Visual studio 2012. So let's start creating a very very simple WCF example.

Steps are following for "SERVICE".

Step 1. Open visual studio and click on file menu -> New -> Project

Step 2. Select "Asp.net Empty Web Application" with .Net Framework 4.5 and give Name "SimpleWCF" and checked checkbox on "Create directory for solution." and then click OK.

Step 3. Now, Right click on project and Add New Item "AJAX-enabled WCF Service" and give name "Hello.svc" and click ADD.

Step 4. By default, it will add some code, so first delete all the existing code and make that file as following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace SimpleWCF
{
     
    public class Hello :IHello 
    {

        public string getResponse(string name)
        {
            return "Hello " + name;
        }
    }

    [ServiceContract]
    public interface IHello {

        [OperationContract]
        string getResponse(string name);
    }
}

Step 5. Open web.config file and make changes like following.
<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>

    <system.serviceModel>
        <behaviors>
   <serviceBehaviors>
    <behavior>
     <serviceMetadata httpGetEnabled="true"/>
    </behavior>
   </serviceBehaviors>
        </behaviors>
        
    </system.serviceModel>
</configuration>


That's it! Service is ready.

Now, Steps are following for "CLIENT".

Step 1. Right click on the same solution -> Add -> New Project

Step 2. Select "Asp.net empty web application" with .net framework 4.5 and give name "SimpleWCFClient" and click OK.

Step 3. Now, right click on this project and "Add Service Reference".

Step 4. In this dialog box, add Address, in my case, i have "http://localhost:54304/Hello.svc" and click GO.

Step 5. You can see your Service and give name "HelloClientService" and Click OK.

Step 6. It will automatically add all the necessary code in web.config like following.
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>

    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IHello" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:54304/Hello.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IHello" contract="HelloClientService.IHello"
                name="BasicHttpBinding_IHello" />
        </client>
    </system.serviceModel>
</configuration>

Step 7. Now right click on project and add New Item "Web Form" and name it "Default.aspx"

Step 8. In code behind of this default.aspx page, write following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SimpleWCFClient
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HelloClientService.HelloClient hc = new HelloClientService.HelloClient();
            string result = hc.getResponse("John Miller");
            hc.Close();
        }
    }
}

Result will be:
Hello John Miller
You can see, it will return response with "Hello" in prefix. This is very simple example and project structure will look like following:

Thursday, June 26, 2014

How to redirect parent window on particular page when we close the modal popup window? using JQuery or Javascript (NOT on reload or post back)

I was looking for JQuery solution which will fire only when I close a modal popup window. I found some JQuery examples but none of them gave me correct JQuery solution. What I was looking is that whenever I close the modal popup Window, it prompts with message before closing and redirect to particular page. So I got the following JQuery solution, But the issue in this solution is that it will fire on both event "close" and "reload or post back". This is wrong. I want a JQuery solution which should work only on closing a modal popup window, not on reload or post back.

     $(window).unload(function() {
           //redirection code here
           alert('your message');   
     });

So after some research, I made it and solved the issue with following. I hope this will help you as well.
     $(window).unload(function(event) {
        if (event.target.readyState=='complete') {

            alert('Closing Window and redirecting...');
            var opener = window.dialogArguments;
            opener.parent.location = '../YourRedirected.aspx?id=<%=Record_ID %>';
            top.window.close();

        }
        else {
            alert('Reloading Window');
        }   
     });

Which project management style is right for you?

Sometimes, the secret to a successful project is selecting the right project management style. Establishing an effective framework is crucial for any project to run smoothly. But when you have "WATERFALL" and "AGILE" planning methods to choose from, how do you know which is the best for your project and team?

Here's a list of the pros and cons for each method to help you decide.

WATERFALL


Water fall requires detailed planning at the beginning of a project. All the steps are laid out, dependencies mapped, and you move to the next stage only after completing the previous one.

Pros.

  • Best for projects that deal with physical objects - from a construction project to a hardware installation project.
  • Best for projects with defined tasks and phases that must be completed in a specific sequence (e.g. build the first floor of a building before the second floor).
  • Project plans are repeatable for identical or similar projects in the future.

Cons.

  • Requires substantial scope and schedule planning before work begins.
  • Scope changes can be slow and require formal change control processes.
  • Less effective for software, design and other non-physical or service-based projects.


AGILE


This is a fast and flexible approach to project management based on principles of collaboration, adaptability and continuous improvement. Unlike the orderly stages of a waterfall approach, agile project management is typically set up in quick, iterative project release cycles.

Pros.

  • Best for projects that deal with services-oriented and non-physical deliverables like code, copywriting and design projects.
  • Allows for quick course correction based on stakeholder feedback.
  • Empowers project teams to work creatively and efficiently.
  • Includes engagement and collaboration from all team members.

Cons.

  • Not suited for projects with strictly defined requirements and scope.
  • Uncertainty around scope and schedules can make stakeholders and executives nervous (at first).
  • Requires vigilant backlog and documentation maintenance, and tech debt management.


Wednesday, June 25, 2014

How to do INNER JOIN, LEFT JOIN and RIGHT JOIN in LINQ as well as in SQL? Part 1

Today I will show you how to write LINQ Query as well as SQL Query. Both LINQ and SQL examples will clear your idea about INNER JOIN, LEFT JOIN and RIGHT JOIN. And also it will show you different results based on different JOINs.

Let’s create platform for it. Suppose we have following tables with data.
SELECT * FROM CUSTOMER


SELECT * FROM CITY


Now we will write SQL Queries for INNER JOIN, LEFT JOIN and RIGHT JOIN.
--Inner Join
SELECT cust.Name 
FROM CUSTOMER cust
 INNER JOIN CITY ct 
  ON ct.id = cust.city_id
  
--Left Join
SELECT cust.Name
FROM CUSTOMER cust
 LEFT JOIN CITY ct 
  ON ct.id = cust.city_id
 
--Right Join
SELECT ct.name AS City  
FROM CUSTOMER cust
 RIGHT JOIN CITY ct 
  ON ct.id = cust.city_id

After SQL, we will write LINQ Queries in C# for INNER JOIN, LEFT JOIN and RIGHT JOIN.
            
using (MyTestEntities db = new MyTestEntities())
{

 //Inner Join
 var results = (from Customer cust in db.Customers
                join City ct in db.Cities
                on cust.City_Id equals ct.Id
                select cust.Name).ToList();


 //Left Join
 results = (from Customer cust in db.Customers
            join City ct in db.Cities 
            on cust.City_Id equals ct.Id into Joined
            from lj in Joined.DefaultIfEmpty()
            select cust.Name).ToList();


 //Right Join (Just swap it)
 results = (from City ct in db.Cities
            join Customer cust in db.Customers 
            on ct.Id equals cust.City_Id into Joined
            from rj in Joined.DefaultIfEmpty()
            select ct.Name).ToList();

}
Now it's time to see results:

INNER JOIN Result for both queries will be like this



LEFT JOIN Result for both queries will be like this



RIGHT JOIN Result for both queries will be like this




Now you can compare SQL, LINQ and Result to get clear idea about it.

Tuesday, June 24, 2014

How to Insert Values into an Identity Column in SQL Server?

To insert values into an identity column, you have to first set identity_insert ON and after inserting or updating, you have to set it OFF like following:
SET IDENTITY_INSERT [dbo].[YourTableName] ON 
GO
INSERT INTO [dbo].[YourTableName]
           ([ID] 
           ,[Code]
           ,[Description]
           ,[Required_by_System] )
     VALUES
           (9
           ,900
           ,'Record Updated'
           ,'Y' )
GO
SET IDENTITY_INSERT [dbo].[YourTableName] OFF
GO

Monday, June 23, 2014

Simple example for Asp.net MVC 4 and Entity Framework for Add/Edit/Delete/View/List Customers

Today we will create very simple Asp.net MVC 4 application with entity framework which will give you basic idea about MVC and entity framework. I am going to use “database first” workflow for entity framework.

Let’s start with following steps:

Step 1: Create a new project with .net 4.5 and choose Asp.net MVC 4 Web application and give name “MvcDemo” and click ok.

Step 2: Now choose “Empty” in template selection. View engine will be “Razor” by default and click Ok. This will create project with basic files and folders.

Step 3: Please create database and create “customer” table with following script.

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Name] [nvarchar](50) NULL,
 [City] [nvarchar](50) NULL,
 [State] [nvarchar](50) NULL,
 CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 4: We will create entity model in our project, for this, right click on “Models” folder and add new item as following and give name “MvcModel”.



Step 5: Select “Generate from database” and click next :



Step 6: Choose “connection string”, click “new connection” and give your database connection and name it “MvcDataEntities” and click Next.



Step 7: Choose “Customer” table and click on finish.



Step 8: This will create model :



Step 9: We have model, now we will create controller which will automatically create views for us.

Step 10: Right click on “Controllers” folder and add “HomeController” with Template “MVC controller with read/write actions and views, using Entity Framework." and click Add.



Step 11: This will create “HomeController” and also associated Views like create.cshtml, delete.cshtml, edit.cshtml etc… :



Step 12: Make it start up project and run. Initial screen will look like following:



Step 13: Click on “Create New” and it will give you following error:



Step 14: To solve this, you have to run nuget package with following command :
Install-Package Microsoft.AspNet.Web.Optimization


Step 15: once you run this nuget package, you have to add namespace in web.config like following.
<add namespace="System.Web.Optimization"/> 

Step 16: Now run your project and you can successfully add, edit, delete and view list of cutomers.

the name 'Scripts' does not exists in the current context in Asp.net MVC 4

You will get this error message when you want to build asp.net MVC 4 application with blank solution. To solve this issue, you have to install the following nuget package in your project:
Install-Package Microsoft.AspNet.Web.Optimization
And also in web.config, add following:
<add namespace="System.Web.Optimization"/> 
It will solve your issue.

Friday, June 20, 2014

Cache Aggressively – Performance Tips for ASP.NET Applications

Tip 3. Cache Aggressively

When designing Asp.net application, make sure you put all static pages in cache. You can cache data as well as pages/user controls. Asp.net 4.0 also providing extensible output cache through which you can put your cache on local or remote disks, cloud storage and distributed cache engines.

Caching makes significant performance improvement in your application.

You can cache data using application cache which provides a programmatic way to store data in memory using key/value pairs.

You can cache page using page output cache. Output caching enables you to store rendered HTML. You can cache a whole web page or just the output of Asp.net control.

An application can often increase performance by storing data in memory that is accessed frequently and that requires significant processing time to create. For example, if your application processes large amounts of data using complex logic and then returns the data as a report accessed frequently by users, it is efficient to avoid re-creating the report every time that a user requests it. Similarly, if your application includes a page that processes complex data but that is updated only infrequently, it is inefficient for the server to re-create that page on every request.

To help you increase application performance in these situations, ASP.NET provides caching using two basic caching mechanisms. The first is application caching, which allows you to cache data you generate, such as a DataSet object or a custom report business object. The second is page output caching, which saves the output of page processing and reuses the output instead of re-processing the page when a user requests the page again.

Thursday, June 19, 2014

What is SSAS? (SQL Server Analysis Services)

SQL Server Analysis Services (SSAS) delivers online analytical processing (OLAP) and data mining functionality for business intelligence applications. Analysis Services supports OLAP by letting you design, create, and manage multidimensional structures that contain data aggregated from other data sources, such as relational databases. For data mining applications, Analysis Services lets you design, create, and visualize data mining models that are constructed from other data sources by using a wide variety of industry-standard data mining algorithms.

What is SSIS? (SQL Server Integration Services)

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. You use Integration Services to solve complex business problems by copying or downloading files, sending e-mail messages in response to events, updating data warehouses, cleaning and mining data, and managing SQL Server objects and data. The packages can work alone or in concert with other packages to address complex business needs. Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations; tools for constructing packages; and the Integration Services service for running and managing packages. You can use the graphical Integration Services tools to create solutions without writing a single line of code; or you can program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Use Session State Only If You Need To - Performance Tips in Asp.net

Tip 2. Use Session State Only If You Need To

One extremely powerful feature of ASP.NET is its ability to store session state for users, such as a shopping cart on an e-commerce site or a browser history. Since this is on by default, you pay the cost in memory even if you don't use it. If you're not using Session State, turn it off and save yourself the overhead by adding <@% EnabledSessionState = false %> to your asp.

For pages that only read session state, you can choose EnabledSessionState=readonly. This carries less overhead than full read/write session state, and is useful when you need only part of the functionality and don't want to pay for the write capabilities.

Throw Fewer Exceptions - Performance Tips for Asp.net

Performance is must for any successful project. I will try to give you some performance tips in “Performance Tips” category in my blog.

Tip 1. Throw Fewer Exceptions.

Throwing exceptions can be very expensive to your project. So make sure that you don’t throw a lot of them. I recommend that test your project thoroughly and try to handle all the error instead of throwing them and catching them into database. Why? See below example and its result. Note that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want.
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            int j = 0;
            for (int i = 0; i < 1000; i++)
            {
                try
                {
                    j = i / j; //Attempted to divide by zero.
                    //This code will throw exception

                }
                catch { }
            }

            sw.Stop();

            Response.Write("With exception : " +
                sw.ElapsedMilliseconds.ToString() + " Milliseconds.");

            sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            j = 0;
            for (int i = 0; i < 1000; i++)
            {
                try
                {
                    if (j > 0) //Handle like this will improve performance.
                    {
                        j = i / j;  
                    }
                }
                catch { }
            }

            sw.Stop();

            Response.Write("WITHOUT exception : " +
                sw.ElapsedMilliseconds.ToString() + " Milliseconds.");
Result will be:
With exception : 15772 Milliseconds.
WITHOUT exception : 0 Milliseconds. 


In above code, you can see clearly that if we handle error or try to eliminate it, it will improve performance tremendously.

Wednesday, June 18, 2014

How to create simple chat application using SignalR 2.0 in Asp.net?

Today I will show you how to create simple chat application using SignalR. The tutorial demonstrates the following SignalR development tasks:

• Adding the SignalR library to an ASP.NET web application.

• Creating a hub class to push content to clients.

• Creating an OWIN startup class to configure the application.

• Using the SignalR jQuery library in a web page to send messages and display updates from the hub.

The following screen shot shows the chat application running in a browser.



Steps are following:

Step 1: Create a new project in .NET 4.5 “Asp.net Empty Web Application” like following.



Step 2: As I am using Visual Studio 2012, I have to manually run the following command to install “Microsoft.AspNet.SignalR” which will add necessary script files and assembly references to support SignalR.

install-package Microsoft.AspNet.SignalR


Go to “Tools” -> Library Package Manager -> Click on Package Manager Console

Choose default project to Your SimpleChat project and write “install-package Microsoft.AspNet.SignalR” in the console and press “Enter” to install. Console looks like following.



Now we need "json2.js". To install this file in our project follow THIS ARTICLE. This is necessary to work smoothly with SignalR application.

Step 3: Create “Users” folder in your project and Create User.cs file in it like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SimpleChat.Users
{
    public class User
    {
        public string Name { get; set; }
        public string Id { get; set; }
    }
}

Step 4. Create “UserRepository.cs” file in “Users” foler like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SimpleChat.Users
{
    public static class UserRepository
    {
        static List<User> lstUser = new List<User>();

        public static void add(User u)
        {
            lstUser.Add(u);
        }

        public static User getById(string id)
        {
            return lstUser.Where(usr => usr.Id == id).FirstOrDefault();

        }
        public static User getByName(string name)
        {
            return lstUser.Where(usr => usr.Name == name).FirstOrDefault();

        }
        public static List<User> getAll()
        {
            return lstUser;
        }
        public static void remove(User u)
        {
            lstUser.Remove(u);
        }
    }
}

Step 5. Create “ChatHub.cs” file in your project like this.
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SimpleChat
{
    public class ChatHub : Hub
    {
        public void Send(string ToName, string message, string FromName)
        {
            //Check ToName, If ToName is specified, send message to that specified Name
            //If ToName is not specified, Send to All Users
            if (ToName != null)
            {
                //Get the ConnectionId of ToName
                string id = Users.UserRepository.getByName(ToName).Id;
                
                //Send message to specified User
                Clients.Client(id).broadcastMessage(FromName, message);

                //Check, if it is not self
                if (id != Context.ConnectionId.ToString())
                {
                    Clients.Client(Context.ConnectionId.ToString()).broadcastMessage("Me", message);
                }
            }
            else
            {
                //Send to all because no user selected.
                Clients.All.broadcastMessage(FromName, message);
            } 
        }

        //Add User in listview
        public void AddUser(string userName)
        {
            Users.User u = new Users.User();
            u.Id = Context.ConnectionId.ToString();
            u.Name = userName;
            Users.UserRepository.add(u);

            Clients.All.updateuserslist(userName);
        }

        //If user leaves the browser, remove from listview or from online users list.
        public override System.Threading.Tasks.Task OnDisconnected()
        {
            Users.User u = Users.UserRepository.getById(Context.ConnectionId.ToString());
            if (u != null)
            {
                RemoveUser(u.Name);
                Users.UserRepository.remove(u);

            }

            return base.OnDisconnected();
        }
        public void RemoveUser(string name)
        {
            Clients.All.updateuserslist_remove(name);
        }

    }
}
Step 6. Create “Startup.cs” file in your project like this.
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SimpleChat.Startup))]
namespace SimpleChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

Step 7. Create “index.aspx” file in your project like this.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            border: 0px solid #808080;
        }
    </style>

</head>
<body>

    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/json2.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.0.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            // Declare a proxy to reference the hub. 
            var chat = $.connection.chatHub;
            // Create a function that the hub can call to broadcast messages.
            chat.client.broadcastMessage = function (name, message) {
                // Html encode display name and message. 
                var encodedName = $('<div />').text(name).html();
                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page. 
                $('#discussion').append('<li><strong>' + encodedName
                    + '</strong>:  ' + encodedMsg + '</li>');
            };

            //Update listview to add user
            chat.client.updateuserslist = function (name) {
                $('#ddlUsers').append(
                    $('<option></option>').val(name).html(name)
                );

            };

            //Update listview to remove user
            chat.client.updateuserslist_remove = function (name) {
                $('#ddlUsers option[value=' + name + ']').remove();

            };
             
            // Set initial focus to message input box.  
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub. 
                    chat.server.send($('#ddlUsers').val(), $('#message').val(), $('#displayname').val());
                    // Clear text box and reset focus for next comment. 
                    $('#message').val('').focus();
                });
                $('#btnEnter').click(function () {
                    // Call the AddUser method on the hub. 
                    chat.server.addUser($('#displayname').val());
                    $('#btnEnter').hide();
                    $('#displayname').hide();
                    $('#FromName').text($('#displayname').val());
                });
            });
        });
    </script>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="displayname" runat="server"></asp:TextBox>

            <input type="button" id="btnEnter" value="Enter Your Name" />
            <br />
            <br />
             
            <table>
                <tr>
                    <td style="vertical-align: top;">Online Users:<br />
                        <asp:ListBox ID="ddlUsers" runat="server"></asp:ListBox>
                    </td>
                    <td style="border:solid 1px black;">
                        <div class="container" style="height: 330px; width: 300px;">
                            <ul id="discussion" style="overflow: auto; height: 280px; width: 250px;">
                            </ul>
                            <span id="FromName"></span>
                            <input type="text" id="message" />
                            <input type="button" id="sendmessage" value="Send" />

                        </div>
                    </td>
                </tr>
            </table>




        </div>
    </form>
</body>
</html>

Step 8. In code behind of “index.aspx” file, which is “index.aspx.cs” file like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SimpleChat
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                ddlUsers.DataSource = Users.UserRepository.getAll();
                ddlUsers.DataTextField = "Name";
                ddlUsers.DataValueField = "Name";
                ddlUsers.DataBind();


            }



        }


    }
}


That's it! you are ready to run it, BUT before you run your application, make sure that your referencing script files in index.aspx are matching with the project script files. sometimes .js files are updating their version frequently.

In our case, we are referencing following script files:
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/json2.js"></script>
    
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.1.0.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>

And we have following script files in our project structure.


How it works:


1. Run the application.

2. It will ask you for your "Name".

3. Open another browser and paste the same URL. and again give some name.

4. You can see that all the names will be added in "Online Users" list.

5. Once some user will close the browser, User will be removed from the list automatically.

6. Now you can send message to anybody or to all.

7. To send message to all, don't select any user. and To send messsage to particular User, select it from Online Users list and start chating...like following

Tuesday, June 17, 2014

What is SSRS? (SQL Server Reporting Services)

SQL Server Reporting Services provides a full range of ready-to-use tools and services to help you create, deploy, and manage reports for your organization. Reporting Services includes programming features that enable you to extend and customize your reporting functionality.

Reporting Services is a server-based reporting platform that provides comprehensive reporting functionality for a variety of data sources. Reporting Services includes a complete set of tools for you to create, manage, and deliver reports, and APIs that enable developers to integrate or extend data and report processing in custom applications. Reporting Services tools work within the Microsoft Visual Studio environment and are fully integrated with SQL Server tools and components.

With Reporting Services, you can create interactive, tabular, graphical, or free-form reports from relational, multidimensional, or XML-based data sources. Reports can include rich data visualization, including charts, maps, and sparklines. You can publish reports, schedule report processing, or access reports on-demand. You can select from a variety of viewing formats, export reports to other applications such as Microsoft Excel, and subscribe to published reports. The reports that you create can be viewed over a Web-based connection or as part of a Microsoft Windows application or SharePoint site. You can also create data alerts on reports published to a SharePoint site and receive email messages when report data changes.

Monday, June 16, 2014

SignalR doesn’t work in IE – Internet Explorer (SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support)

Today I was working on SignalR Application and I got this error (SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. less than IE 8.)

The very simple solution to fix this issue is “Just download JSON2 from Manage NuGet Packages and Install it”.

Steps are:
1. Right click on your project and click on “Manage NuGet Packages”

2. Now, in NuGet window, search “Json2” like following: (Note: you can click on Online, which is on left of NuGet window, to get it from online)



3. Once you have it, just click on “Install” button to install it in your project.

4. Once installation is complete, it will be like following in your project. (make sure that json2.js file will be before SignalR.js)



Now run your app and it works fine.

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...