Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for the ‘General’ Category

Convert data from Generic List to DataTable.

Posted by Viral Sarvaiya on May 9, 2013

Today i am sharing very good a function which convert all Generic list’s data to Datatable is as below

public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
  DataTable dtReturn = new DataTable();

  // column names
  PropertyInfo[] oProps = null;

  if (varlist == null) return dtReturn;

  foreach (T rec in varlist)
    // Use reflection to get property names, to create table, Only first time, others will follow
    if (oProps == null)
      oProps = ((Type)rec.GetType()).GetProperties();
      foreach (PropertyInfo pi in oProps)
        Type colType = pi.PropertyType;

        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
          colType = colType.GetGenericArguments()[0];

        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
    DataRow dr = dtReturn.NewRow();

    foreach (PropertyInfo pi in oProps)
      dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);

  return dtReturn;

Hope this will helps you.


Posted in .Net, C#, General, LINQ | Tagged: , , , , , , , , , , | Leave a Comment »

Find Difference between 2 dates in Year, month, day, hour, minute, second and millisecond.

Posted by Viral Sarvaiya on May 3, 2013

After a long time i get time to post in my blog.

Few day ago i get very good function which finds difference between 2 dates.

Below is the class named “DateTimeSpan.cs”

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

public struct DateTimeSpan
  private readonly int m_years;
  private readonly int m_months;
  private readonly int m_days;
  private readonly int m_hours;
  private readonly int m_minutes;
  private readonly int m_seconds;

  private readonly int m_milliseconds;
  public DateTimeSpan(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds)
    this.m_years = years;
    this.m_months = months;
    this.m_days = days;
    this.m_hours = hours;
    this.m_minutes = minutes;
    this.m_seconds = seconds;
    this.m_milliseconds = milliseconds;

  public int Years
    get { return m_years; }
  public int Months
    get { return m_months; }
  public int Days
    get { return m_days; }
  public int Hours
    get { return m_hours; }
  public int Minutes
    get { return m_minutes; }
  public int Seconds
    get { return m_seconds; }
  public int Milliseconds
    get { return m_milliseconds; }

  private enum Phase

  public static DateTimeSpan CompareDates(DateTime date1, DateTime date2)
    if (date2 < date1)
      dynamic sub = date1;
      date1 = date2;
      date2 = sub;

    DateTime current = date1;
    int years = 0;
    int months = 0;
    int days = 0;

    Phase phase__1 = Phase.Years;
    DateTimeSpan span = new DateTimeSpan();

    while (phase__1 != Phase.Done)
      switch (phase__1)
        case Phase.Years:
          if (current.AddYears(years + 1) > date2)
            phase__1 = Phase.Months;
            current = current.AddYears(years);
            years += 1;
          break; // TODO: might not be correct. Was : Exit Select

        case Phase.Months:
          if (current.AddMonths(months + 1) > date2)
            phase__1 = Phase.Days;
            current = current.AddMonths(months);
            months += 1;
          break; // TODO: might not be correct. Was : Exit Select

        case Phase.Days:
          if (current.AddDays(days + 1) > date2)
            current = current.AddDays(days);
            dynamic timespan = date2 - current;
            span = new DateTimeSpan(years, months, days, timespan.Hours, timespan.Minutes, timespan.Seconds, timespan.Milliseconds);
            phase__1 = Phase.Done;
            days += 1;
          break; // TODO: might not be correct. Was : Exit Select
    return span;

Now in default.aspx page i am using this structure to get difference between 2 dates as below.

protected void Page_Load(object sender, EventArgs e)
  DateTimeSpan datetimespan = new DateTimeSpan(); // Create object of constructer to get difference.

  string date1 = "3-May-2013 9:26:10.011 AM";  //Date 1
  string date2 = "4-June-2014 6:50:20.136 PM";  // date2
  datetimespan = DateTimeSpan.CompareDates(Convert.ToDateTime(date1), Convert.ToDateTime(date2));  //Call static function of DateTimeSpan structure. which return difference of 2 dates.

  Response.Write("Date 1 : " + date1 + "  <br>");
  Response.Write("Date 2 : " + date2 + " <br><br>");

  Response.Write("Years : " + datetimespan.Years + "<br>");
  Response.Write("Months : " + datetimespan.Months + "<br>");
  Response.Write("Days : " + datetimespan.Days + "<br>");
  Response.Write("Hours : " + datetimespan.Hours + "<br>");
  Response.Write("Minutes : " + datetimespan.Minutes + "<br>");
  Response.Write("Seconds : " + datetimespan.Seconds + "<br>");
  Response.Write("Milliseconds : " + datetimespan.Milliseconds + "<br>");


This will give difference in all possible ways as below output.


Hope this will helps you.

Posted in .Net, C#, General | Tagged: , , , , , , , , | Leave a Comment »

Comparison/Difference of IPv4 and IPv6

Posted by Viral Sarvaiya on July 20, 2012

Key differences between IPv4 and IPv6.



Source and destination addresses are 32 bits (4 ytes) in length. Source and destination addresses are 128 bits (16 bytes) in length.
IPsec header support is optional. IPsec header support is required.
No identification of packet flow for prioritized delivery handling by routers is present within the IPv4 header. Packet flow identification for prioritized delivery handling by routers is present within the IPv6 header using the Flow Label field.
Fragmentation is performed by the sending host and at routers, slowing router performance. Fragmentation is performed only by the sending host.
Has no link-layer packet-size requirements and must be able to reassemble a 576-byte packet. Link layer must support a 1,280-byte packet and be able to reassemble a 1,500-byte packet.
Header includes a checksum. Header does not include a checksum.
Header includes options. All optional data is moved to IPv6 extension headers.
ARP uses broadcast ARP Request frames to resolve an IPv4 address to a link-layer address. ARP Request frames are replaced with multicast Neighbor Solicitation messages.
Internet Group Management Protocol (IGMP) is used to manage local subnet group membership. IGMP is replaced with Multicast Listener Discovery (MLD) messages.
ICMP Router Discovery is used to determine the IPv4 address of the best default gateway and is optional. ICMPv4 Router Discovery is replaced with ICMPv6 Router Solicitation and Router Advertisement messages, and it is required.
Broadcast addresses are used to send traffic to all nodes on a subnet. There are no IPv6 broadcast addresses. Instead, a linklocal scope all-nodes multicast address is used.
Must be configured either manually or through DHCP for IPv4. Does not require manual configuration or DHCP forIPv6.
Uses host address (A) resource records in the Domain Name System (DNS) to map host names to IPv4 addresses. Uses AAAA records in the DNS to map host names to IPv6 addresses.
Uses pointer (PTR) resource records in the IN-ADDR.ARPA DNS domain to map IPv4 addresses to host names. Uses pointer (PTR) resource records in the IP6.ARPA DNS domain to map IPv6 addresses to host names.

Posted in General | Tagged: , , , , , , , , , , | Leave a Comment »

Features of IPv6

Posted by Viral Sarvaiya on July 19, 2012

The following list summarizes the features of the IPv6 protocol:
1) New header format
2) Large address space
3) Stateless and stateful address configuration
4) IPsec header support required
5) Better support for prioritized delivery
6) New protocol for neighboring node interaction
7) Extensibility

1) New Header Format:
The IPv6 header has a new format that is designed to minimize header processing. This is achieved by moving both nonessential and optional fields to extension headers that are placed after the IPv6 header. The streamlined IPv6 header is more efficiently processed at intermediate routers. IPv4 headers and IPv6 headers are not interoperable. IPv6 is not a superset of functionality that is backward compatible with IPv4. A host or router must use an implementation of both IPv4 and IPv6 to recognize and process both header formats. The new default IPv6 header is only twice the size of the default IPv4 header, even though the number of bits in IPv6 addresses is four times larger than in IPv4 addresses.

2) Large Address Space:
IPv6 has 128-bit (16-byte) source and destination addresses. Although 128 bits can express over 3.4 ~ 1038 possible combinations, the large address space of IPv6 has been designed to allow for multiple levels of subnetting and address allocation, from the Internet backbone to the individual subnets within an organization. Even with all of the addresses currently assigned for use by hosts, plenty of addresses are available for future use. With a much larger number of available addresses, address-conservation techniques, such as the deployment of NATs, are no longer necessary.

3) Stateless and Stateful Address Configuration:
To simplify host configuration, IPv6 supports both stateful address configuration (such as address configuration in the presence of a DHCP for IPv6, or DHCPv6, server) and stateless address configuration (such as address and routing configuration in the absence of a DHCPv6 server). With stateless address configuration, hosts on a link automatically configure themselves with IPv6 addresses for the link (called link-local addresses), with IPv6 transition addresses, with addresses derived from prefixes advertised by local routers, and local subnet and default routes. Both stateless and stateful addressing can be used at the same time. Even in the absence of a router, hosts on the same link can automatically configure themselves with link-local addresses and communicate without manual configuration. Link-local addresses are autoconfigured within seconds, and communication with neighboring nodes on the link is possible immediately. In comparison, some IPv4 hosts using DHCP must wait a full minute before abandoning DHCP configuration and selfconfiguring an IPv4 address.

4) IPsec Header Support Required:
Support for the IPsec headers is an IPv6 protocol suite requirement. This requirement provides a standards-based solution for network protection needs and promotes interoperability between different IPv6 implementations. IPsec consists of two types of extension headers and a protocol to negotiate security settings. The Authentication header (AH) provides data integrity, data authentication, and replay protection for the entire IPv6 packet (excluding fields in the IPv6 header that must change in transit). The Encapsulating Security Payload (ESP) header and trailer provide data integrity, data authentication, data confidentiality, and replay protection for the ESP-encapsulated payload. The protocol typically used to negotiate IPsec security settings for unicast communication is the Internet Key Exchange (IKE) protocol. The requirement to process IPsec headers does not make IPv6 inherently more secure. IPv6 packets are not required to be protected with IPsec, and IPsec is not a requirement of an IPv6 deployment. Additionally, the IPv6 standards do not require an implementation to support any specific encryption methods, hashing methods, or negotiation protocol (such as IKE).

5) Better Support for Prioritized Delivery:
New fields in the IPv6 header define how traffic is handled and identified. Traffic is prioritized by using a Traffic Class field, which specifies a DSCP value just like IPv4. A Flow Label field in the IPv6 header allows routers to identify and provide special handling for packets that belong to a flow (a series of packets between a source and destination). Because the traffic is identified in the IPv6 header, support for prioritized delivery can be achieved even when the packet payload is encrypted with IPsec and ESP.

6) New Protocol for Neighboring Node Interaction:
The Neighbor Discovery protocol for IPv6 is a series of Internet Control Message Protocol for IPv6 (ICMPv6) messages that manages the interaction of neighboring nodes (nodes on the same link). Neighbor Discovery replaces and extends the combination of the Address Resolution Protocol (ARP) (broadcast-based), ICMPv4 Router Discovery, and ICMPv4 Redirect messages with efficient multicast and unicast Neighbor Discovery messages.

7) Extensibility:
IPv6 can easily be extended for new features by adding extension headers after the IPv6 header. Unlike options in the IPv4 header, which can support only 40 bytes of options, the size of IPv6 extension headers is constrained only by the size of the IPv6 packet.

Posted in General | Tagged: , , , , , , , , | Leave a Comment »

How to recover lost/missing system tray icon?

Posted by Viral Sarvaiya on June 10, 2011

Please follow the steps for recover Lost/missing system tray icon.

1. Back up the Registry by creating a restore point.
2. Go to Start > Run (or Windows-key + R), type in regedit and hit OK.
3. Navigate to the key HKEY_CURRENT_USER\Software\Cla sses\Local Settings\Software\Microsoft\Wi ndows\CurrentVersion \TrayNotify.
4. Delete the values IconStreams and PastIconsStream.
5. Open up the Task Manager (Ctrl + Shift + Esc), go to the Processes tab, select explorer.exe and click End Process.
6. Open the Applications tab and click New Task at the bottom-right of the window.
7. In the message box that pops up type in explorer.exe and hit OK.
8. Explorer.exe will reload, and the missing icons should now be back in the system-tray where they belong.
9. Then if the volume bar isnt there, go to taskbar properties (where the volume was gray) and simply tick the box.

Posted in General | Tagged: , , , | Leave a Comment »

My First Presantation in Industrial Experience.

Posted by Viral Sarvaiya on January 12, 2011


Yesterday dated 11th January 2011, I have a presentation in my company. My presentation topic is “.Net 3.5 Mysteries”. In this presentation I have include

1.       Automatic  property

2.       Object and Collection Initializes

3.       Extension Methods

4.       Lambda Expressions

5.       Implicit Typing

6.       Anonymous Types

7.       Partial Methods

8.       LINQ  (Linq to sql, Linq to XML, Linq to object)

This is my first presentation after the industrial experience start.  It was very good, I get very feedback and whole presentation was full of interaction with people.

Thanks to Mr. Jay Joshi to present this presentation in last .Net Tech Talk and Mr. Ruchit Surti for handling great event of .Net Tach Talk and Mr. Bakir Padaniya to help to get some example for my presentation.

Hope this will continue and we share more knowledge to society.

click  for Download Presantation only and for code check the flash widget from right panel file named “.Net 3.5” of this blog.

Posted in General | Tagged: | Leave a Comment »

Google Music India Launched

Posted by Viral Sarvaiya on October 25, 2010

Google India has pulled the covers off the Google Music service in India, offering users access to live streaming of Hindi film songs online. This is not new, but the reach that Google has makes it the service to watch. The implementation of Google Music India is similar to that of, which has been sued by music label T-Series, but in Google’s case, they’ve partnered with companies that have licensed content legally: Music label Saregama, Web18 owned and the Hungama-212 media JV – Saavn. Like Guruji, Google music search suggests albums, allows users to search artists, films and albums, and offers to even sort music by date. Google music search doesn’t have top 10 lists yet.

As you can see from the screenshot below, the music is played in a pop-up window, and a display ad is run as a footer there. There is probably a revenue share arrangement between the music licensee and Google. Remember that in case of songs that were being played at via Guruji, there were similar ads. Only, this music is legal, and like Guruji was doing, it is being hosted and played from the someone elses site.

Enjoy Music…

Posted in General | Tagged: , , , | 2 Comments »

Microsoft DOS tracert command

Posted by Viral Sarvaiya on August 12, 2010


The tracert command is used to visually see a network packet being sent and received and the amount of hops required for that packet to get to its destination.


MS-DOS 6.2
Windows 95
Windows 98
Windows ME
Windows NT
Windows 2000
Windows XP
Windows Vista
Windows 7


tracert    [-d] [-h maximum_hops] [-j host-list] [-w timeout] target_name


-d  : Do not resolve addresses to hostnames.
-h  : maximum_hops    Maximum number of hops to search for target.
-j  : host-list    Loose source route along host-list.
-w  : timeout    Wait timeout milliseconds for each reply.



Tracing route to []
over a maximum of 30 hops:

1     1 ms    <1 ms    <1 ms
2     4 ms     1 ms     1 ms
3     3 ms     2 ms     1 ms
4    10 ms    10 ms    10 ms
5    12 ms    11 ms    15 ms
6   255 ms   255 ms   255 ms []
7   289 ms   255 ms   255 ms []
8   267 ms   263 ms   271 ms []
9   288 ms   289 ms   287 ms []
10   292 ms   293 ms   291 ms []
11   299 ms   298 ms   297 ms []
12   300 ms   299 ms   299 ms []
13   299 ms   300 ms   297 ms
14   296 ms   312 ms   300 ms []

Trace complete.

Thanks You.

Posted in General | Tagged: , , , , | Leave a Comment »

scrollable div

Posted by Viral Sarvaiya on March 11, 2010

to view scroll in div tag just copy and paste below code.

<div style="width:100px; height:100px; overflow:auto;"> PUT YOUR TEXT HERE  </div>

when you html height becomes bigger then 100 px then scroll will come.

enjoy coding…..

Posted in General | Tagged: , , | Leave a Comment »

%d bloggers like this: