Code Simplified – Viral Sarvaiya

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

Archive for the ‘ feature’ Category

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 »

String.Split – by Multiple Character Delimiter in C#.Net

Posted by Viral Sarvaiya on October 31, 2012


Basically String Split function split the string with the single character delimiter;
we take one example of single string of the multiple emails.
If we have comma separated emails then we can use Split function as like below

string strEmailText = ",,";
string[] strSplitText = strEmailText.Split(",");

this will give us string array of the Emails.

But what if we want to use split with 2 or more than one character?
Means what if i have string as like below

string strEmailText = ",;,";

at this time above split function will not work with this string. so for that below solution works well.

string strEmailText = ",;,";
string[] strSplitText = strEmailText.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

this will give you string array of the Emails.


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

Difference Between LINQ to SQL and Entity Framework

Posted by Viral Sarvaiya on August 14, 2012

In my current company we have discussion about what is the difference between LINQ to SQL Vs Entity Framework and I get following conclusion from the surfing from internet (off course from google. 🙂 )

LINQ to SQL supports one to one mapping of database table or views or procedures or functions
Entity Framework map single class to multiple tables of database. Means you can map one table to multiple entities or multiple table to one entities.

LINQ to SQL does not support the creation of complex types
Entity Framework support the creation of complex types.

LINQ to SQL is easy to use
Entity framework is more complex compared to LINQ to SQL.

While introduction of LINQ to SQL it supports only sql server and letter on “DBLINQ” that can use with mysql, sqllite or other DBs
Entity Framework  plug with any database server like DB2, Sybase, Oracle, SQL Azure and other.

In LINQ to SQL, inheritance is difficult.
Entity Framework is simple to apply because it supports Table per class and table per Type.

LINQ to SQL file type is DBML
Entity Framework File type is EDMX.

LINQ to SQL has DataContext object which we can query the database,
Entity Framework, we can query database using LINQ To Entities through the ObjectContext object and ESQL(provides SQL like query language). In addition, Entity Framework has ObjectQuery class(used with Object Services for dynamically constructing queries at runtime) and EntityClient provider(runs query against conceptual model).

LINQ to SQL is slow for the first time run, after first run acceptable performance.
Entity Framework is also slow for the first but  performance is good then LINQ to SQL after first run.

LINQ to SQL has not capability to generate database from Model
Entity Framework has capability to generate database from Model.


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

LINQ: Compare two Sequences

Posted by Viral Sarvaiya on April 4, 2012

Today i get very good and very simple way to compare two arrays.

.Net provide very simple way to compare sequences with Enumerable.SequenceEqual()

Function SequenceEqual() compare target and source sequence and return Boolean value, so we  can know that sequence is similar or not.

for ex.

var ar1 = new[] {1, 2, 3, 4, 5, 6, 7 };
var ar2 = new[] {1, 3, 4, 6 };

var result = ar1.SequenceEqual(ar2);


Result : False

Now we want to get that element that is different, for that LINQ gives us best function Except() which works as like below.

var differ = ar1.Except(ar2);
Array.ForEach(differ.ToArray(), a => Console.WriteLine(a));

Out Put:

Hope this will helps you,

Posted in .Net, ASP.NET, feature, LINQ | Tagged: , , , , , , , | 4 Comments »

Send Email Attachment Using A Memory Stream

Posted by Viral Sarvaiya on December 12, 2011

mainly we send attachment as a file which is already in the server, but from memory stream we can also send as a attachment in email, below is code for that,

Dim strMailServer As String = "SMTPServerName"

Dim fs As New FileStream("FilePath\FileName.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)

Dim sReader As New StreamReader(fs)

Dim objMemoryStream As New MemoryStream()

Dim sb As New System.Text.StringBuilder("")
Dim str As String

'--read through template form, replace variables and add lines to string builder

Do While sReader.Peek() >= 0

str = sReader.ReadLine()

'--replace [Date_Time]
'Replace string here



Dim Encoding As New UTF8Encoding

Dim arrByt() As Byte = Encoding.GetBytes(sb.ToString())

objMemoryStream.Write(arrByt, 0, arrByt.Length)

objMemoryStream.Position = 0

'--release file system resources





Dim objMailMessage As New MailMessage

Dim objSMTP As New SmtpClient

Dim toAddress As New MailAddress("ToEmailAddress", "ToEmailName")


Dim fromAddress As New MailAddress("FromEmailAddress", "FromEmailName")

objMailMessage.From = fromAddress

objMailMessage.IsBodyHtml = False
objMailMessage.Priority = MailPriority.Normal

objMailMessage.Subject = "EmailSubject"

objMailMessage.Body = "Email Body"

' add fax cover page as first file attachment

objMailMessage.Attachments.Add(New Attachment(objMemoryStream, "FileName.txt"))


objSMTP.Host = strMailServer


Catch ex As Exception

Throw ex

End Try


Posted in ASP.NET, feature | 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 »

Interop type cannot be embedded. Use the applicable interface instead

Posted by Viral Sarvaiya on August 2, 2011

Today i face one more difficulty in my current project,

i am useing .net 4.0 framework with WPF application.

In this application i am adding one dll file that communicate with COM port and i get error “Interop type cannot be embedded. Use the applicable interface instead.”.

this code is perfactly run with .net 3.5 framework but not in 4.0.

and i get the solution for that as below.

Common Language Runtime in .Net 4.0 supports embedding of COM types information directly into managed assemblies in order to simplify deployment process. Managed assemblies need not have to read type information from interop assemblies any more.

In the managed assembly  you can embaded only COM type metadata so it will only works with interfaces, structures, enums and delegates

so what to do for this problem? the solution is “use interfaces instead of classes” or “simply copy constant values from the class definition locally and use them instead.”

hope this will helps you..


Posted in .Net, feature | Tagged: , , , , , | 5 Comments »

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 »

Understanding the Dynamic Keyword in C# 4

Posted by Viral Sarvaiya on June 13, 2011

The dynamic keyword and the Dynamic Language Runtime (DLR) are major new features in C# 4 and the Microsoft .NET Framework 4. These features generated a lot of interest when announced—along with a lot of questions. There were a number of answers as well, but they’re now spread throughout documentation and on various technical blogs and articles. So people continue asking the same questions again and again on forums and at conferences.

This article provides a general overview of the new dynamic features in C# 4 and also delves into some more in-depth information about how they work with other language and framework features, such as reflection or implicitly typed variables. Given there’s a lot of information available already, I’ll sometimes reuse classic examples with links to the original sources. I’ll also provide plenty of links for further reading.

For More Details Click Here

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

%d bloggers like this: