Code Simplified – Viral Sarvaiya

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

Posts Tagged ‘.net’

Getting Started with AWS Lambda and C#

Posted by Viral Sarvaiya on December 26, 2017

I know its very late to write about AWS Lambda but i just learned AWS and writing vary basic things on AWS lambda.

What is Lambda?
First of all we need to know what is AWS lambda.
Lambda is compute service provided by Amazon web service that let you run your code without managing servers. if you like to create small bunch of code or simple function that works for you into AWS Lambda.
You can run code for virtually any type of application or backend service – all with zero administration.
All we need to do is supply your code in one of the languages that AWS lambda supports. Currently AWS Lambda supports Node.js, Java, Python and C#.

Prerequisites to Create New Lambda Function using Visual Studio and C#.

To create AWS lambda function we have following Prerequisites
– Visual Studio 2015 SP1 or Visual Studio 2017 and .Net core for windows installed. ( Dotnet core –
– Toolkit for Visual Studio. –
– Then we need to specify our credentials into AWS Explorer of Visual Studio.
○ After installing AWS toolkit it enables option of AWS Explorer into Visual studio -> View menu as below image.

It will open AWS Explorer.

○ Click to new Account Profile and it will open below popup.

Add your AWS account’s Access key ID, Secret Access Key or you can import CSV file exported from AWS while creating user. Then click to OK at last.

Create New Lambda function using Visual Studio.

Now we are creating new project for AWS lambda function.
– File Menu -> New -> Project, it will open new project selection popup.

Select Installed pane from left side and choose AWS Lambda and then choose project type as “AWS Lambda Project (.Net Core).
– After you select project type choose Blueprint, here we will choose Empty function.

It will open default template for Lambda function, Listed all files as displayed into Solution explorer.

And Function.cs file will have as below code default.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Amazon.Lambda.Core;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace AWSLambdaTest
public class Function

/// <summary>
/// A simple function that takes a string and does a ToUpper
/// </summary>
/// <param name="input"></param>
/// <param name="context"></param>
/// <returns></returns>
public string FunctionHandler(string input, ILambdaContext context)
return "Hello from Lambda!" + " - " + DateTime.UtcNow;

We can modify as per our need, we can also modify Class Name, Function Handler name.

Here I am updating Class Name = LambdaTestFunction
And Function name = LamndaDemoHandler

Body of function I am keeping as it is.

Publish to Lambda

– In solution explorer, right click to Lambda project and choose “Publish to AWS Lambda

– It will open “Upload Lambda function” window.

– We need to confirm Account profile to use and its region where we like to upload our Lambda function.
– If you are creating new Lambda function then write name into textbox or select existing Lambda function from same dropdown.
– Configuration will be “Release”
– Framework = “netcoreapp1.0”
– Assembly Name will be namespace of our Lambda project. Here for us it will AWSLambdaTest
– Type Name will be namespace.class name, here for us AWSLambdaTest.LambdaTestFunction
– Method Name will be handler name, here for us LamndaDemoHandler
– If you like to save settings then we can check checkbox
– Click to Next for selecting Role and other configuration.

– Require Role name, you can choose existing role which has access policy to upload Lambda function. Or create new Role to upload lambda function.
– If your Lambda function accesses resources on Amazon VPC then select VPC subnets.
– Set environment variables if your lambda function require. Keys will be automatically encrypted by default service key.
– Choose “Upload

– It will upload Lambda function and automatic close when upload completes.

– After function uploads it open Function page, use left tabs to test your lambda function, add event source, and view logs.
– You can add subnet into Configuration tab.
– Event sources tab is used if other source you have used, like Dynamo DB or etc.
– Logs will display Logs for Lambda function.
– From example Request dropdown you can choose your requests, here we are selecting “hello World” and typing string because our lambda function accepts string only.
– After completing all configuration click to “invoke” and it will call our lambda function and display result into Response box and you can check log into log box.

Now your lambda function is created and tested and ready for use.


Ref –


Posted in .Net, feature, AWS, AWS Lambda, C#, Lambda Function, netcore | Tagged: , , , , , , , , , , , , | Leave a Comment »

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 »

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, 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 :

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

Check printer status in .net

Posted by Viral Sarvaiya on August 1, 2011


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");
// 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, 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  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



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


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


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:


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: