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...

}


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 ...