Code Simplified – Viral Sarvaiya

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

Posts Tagged ‘.net’

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);
    }

    dtReturn.Rows.Add(dr);
  }
  return dtReturn;
}

Hope this will helps you.
Thanks.

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

Monitoring the File System

Posted by Viral Sarvaiya on September 20, 2011


Today i get new thing in my project that use FileSystemWatcher Class, so here i explain how to monitoring the file system,

You can use the FileSystemWatcher class (part of the System.IO namespace) to respond to updated files, new files, renamed files, and other updates to the file system. First, create an instance of FileSystemWatcher by providing the path to be monitored. Then, configure roperties of the FileSystemWatcher instance to control whether to monitor subdirectories and which types of changes to monitor. Next, add a method as an event handler. Finally, set the FileSystemWatcher.EnableRaisingEvent property to true. The following code sample demonstrates a basic usage.

// Create an instance of FileSystemWatcher
FileSystemWatcher fsw = new FileSystemWatcher(Environment.GetEnvironmentVariable("USERPROFILE"));
// Set the FileSystemWatcher properties
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
// Add the Changed event handler
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
// Start monitoring events
fsw.EnableRaisingEvents = true;

Handling FileSystemWatcher Events When a file is changed that meets the criteria you specify, the CLR calls the FileSystemWatcher.Changed event handler for all changes, creations, and deletions. For files and folders that are renamed, the CLR calls the FileSystemWatcher.Renamed event handler. The previous code sample added the fsw_Changed method to handle the Changed event. The following code sample shows a simple way to handle the event:


static void fsw_Changed(object sender, FileSystemEventArgs e)
{
// Write the path of a changed file to the console
Console.WriteLine(e.ChangeType + ": " + e.FullPath);
}

You can use a single event handler for the Changed, Created, and Deleted events. The FileSystemEventArgs parameter provides the path to the updated file and the type of change that occurred. If you need to respond to files that are renamed, you need to create an event handler that accepts a RenamedEventArgs parameter instead of a FileSystemEventArgs parameter, as the following code sample demonstrates:


static void fsw_Renamed(object sender, RenamedEventArgs e)
{
// Write the path of a changed file to the console
Console.WriteLine(e.ChangeType + " from " + e.OldFullPath + " to " + e.Name);
}

Configuring : FileSystemWatcher Properties You can configure the following properties of the FileSystemWatcher class to control which types of updates cause the CLR to throw the Changed event:

Filter : Used to configure the filenames that trigger events. To watch for changes in all files, set the Filter property to an empty string (“”) or use wildcards (“*.*”). To watch a specific file, set the Filter property to the filename. For example, to watch for changes in the file MyDoc.txt, set the Filter property to “MyDoc.txt”. You can also watch for changes in a certain type of file. For example, to watch for changes in text files, set the Filter property to “*.txt”.

NotifyFilter Configure the types of changes for which to throw events by setting NotifyFilter to one or more of these values:

  • FileName
  • DirectoryName
  • Attributes
  • Size
  • LastWrite
  • LastAccess
  • CreationTime
  • Security

Path : Used to define the folder to be monitored. You can define the path using the FileSystemWatcher constructor. You can watch for the renaming, deletion, or creation of files or directories. For example, to watch for the renaming of text files, set the Filter property to “*.txt” and call the WaitForChanged method with a Renamed value specified for its parameter.

Posted in .Net, ASP.NET, asp.net feature | Tagged: , , , , , , , | Leave a Comment »

NHibernate for .NET

Posted by Viral Sarvaiya on September 5, 2011


Recently I have do some work in new technology – NHibernate.

NHibernate is same as JAVA’s Hibernate Core in .net framework. NHibernate is object-relational mappers(ORM). It handles persisting plain .NET objects to and from an underlying relational database. with an XML description of your entities and relationships, NHibernate automatically generates SQL for the objects.Persistent classes do not need to implement any interface or inherit from a special base class. This makes it possible to design the business logic using plain .NET (CLR) objects and object-oriented idiom.

NHibernate key features:

Natural programming model – NHibernate supports natural OO idiom; inheritance, polymorphism, composition and the .NET collections framework, including generic collections.

Native .NET – NHibernate API uses .NET conventions and idioms

Support for fine-grained object models – a rich variety of mappings for collections and dependent objects

No build-time bytecode enhancement – there’s no extra code generation or bytecode processing steps in your build procedure

The query options – NHibernate addresses both sides of the problem; not only how to get objects into the database, but also how to get them out again

Custom SQL – specify the exact SQL that NHibernate should use to persist your objects. Stored procedures are supported on Microsoft SQL Server.

Support for “conversations” – NHibernate supports long-lived persistence contexts, detach/reattach of objects, and takes care of optimistic locking automatically

Free/open source – NHibernate is licensed under the LGPL (Lesser GNU Public License)

 

For More details :

http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx

http://nhforge.org/wikis/howtonh/your-first-nhibernate-based-application.aspx

Posted in .Net, asp.net feature | Tagged: , , , , | Leave a Comment »

Check printer status in .net

Posted by Viral Sarvaiya on August 1, 2011


Hi

Today i get new thing from my current projet, how to check the status of the printer means wether the printer is connected to PC or not.

For that we have to add reference of the “System.Management”

Here it is code for check status of the printer.


using System.Management;

class PrinterOffline
{
private static void Main(string[] args)
{
// Set management scope
ManagementScope scope = new ManagementScope("\\root\\cimv2");
scope.Connect();
// Select Printers from WMI Object Collections
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get()) {
printerName = printer("Name").ToString().ToLower();
if (printerName.Equals("Name_Of_Printer")) {
Console.WriteLine("Printer = " + printer("Name"));
if (printer("WorkOffline").ToString().ToLower().Equals("true")) {
// printer is offline by user
Console.WriteLine("Your Plug-N-Play printer is not connected.");
} else {
// printer is not offline
Console.WriteLine("Your Plug-N-Play printer is connected.");
}
}
}
}
}

 

thanks and enjoy coding…

Posted in .Net, ASP.NET, asp.net feature, Visual Studio, WPF | Tagged: , , , , , , , | 6 Comments »

Memory Management and Garbage Collection in .NET

Posted by Viral Sarvaiya on September 10, 2010


This video describe the how .net doing memory management and garbage collection. Great video……

Watch Video : Click Here

Click Here

Posted in ASP.NET | Tagged: , , , | 2 Comments »

Difference between Assembly and dll

Posted by Viral Sarvaiya on May 29, 2010


Whats the difference between Assembly and dll in .net.? This is the important question in any .net interview.So i thought of summarising the information which i gathered from various sources.

Assembly:

Assembly  contains meta data ,manifest,resource files.

Metadata:Classes,interfaces,base class,scope,properties.

Manifest:Assembly name,version,culture info, strong name,list of all files, type reference and reference assembely

Functions:

Security

-StrongName: Public/private key decryptyion/encryption correspondingly.

-digital certificate to assembly using signcode.exe :Gives details abt developers identity.

Type Identity:

Defing a type “Datastore” in 2 different assembly..Net framework can differentiate it.

Reference Scope:

-Gives info about its type and resources.

-Gives info abt other assemblies which it depends on.

Versioning:

Each assembly has a 128-bit version number that is presented as a set of four decimal pieces: Major.Minor.Build.Revision

Deployment:

Assemblies are the natural unit of deployment.

Assembly with different version can be present only in GAC folder which has the ability to differentiate diff version.

You cant add a file with 2 diff version in same project.Bcoz bin folder of the project will not have 2 files with same file name.

What’s the difference between private and shared assembly?

Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.

Strong Name:

  • A strong name includes the name of the assembly, version number, culture identity, and a public key token.
  • The .NET Code Access Policy can be used to grant or restrict permissions to assemblies based on their strong name. In addition, the strong name can also be used programmatically to control access to resources.
  • It allows assemblies to have the same name, because the assemblies are identified by their unique information—not their name.

Steps in creatting strong name:

1. This scheme relies on a private key that is used for encryption and a public key that decrypts. To create a file containing this key pair, use the Strong Name command-line utility as shown here:

SN –k KeyFileName

SN –k  KeyLib.snk

2. [assembly: AssemblyKeyFile(“KeyLib.snk”)]

3.Add this KeyLib.snk to the project.

4.Gacutil /I gettimelibrary.dll

If this assembly is used in client projects.The public key token of the referenced assembly is stored in the manifest of the client assembly as a way to reference the target assembly.

To make this appear in add reference u need to do 2 things:

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\MyAssemblies]@=”C:\\MyAssemblies

1.Create MY Assemblies  folder in above location

2.Give the path of ur dll file in value of a Default key.

Assembly Dll
An assembly  is the unit of deployment and security for managed code projects.  It is a .NET Component and can be used only in .NET managed applications.Compiled code at run time is an assembly and After compilation of the requested ASP.NET file is complete, the assembly is loaded into the application domain, allowing late binding.

Codes in APP_Code folder during compilation will become one assembly.

Assembly  present in bin can have either strong/weak Name and assembly in GAC Should have strong name.

DLL contains library code to be used by any program running on Windows. A DLL may contain either structured or object oriented libraries.

Dll is an assembly.

Posted in ASP.NET | Tagged: , , , , , , , , | Leave a Comment »

 
%d bloggers like this: