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