Code Simplified – Viral Sarvaiya

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

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 »

SOLID Principles C#

Posted by Viral Sarvaiya on August 7, 2017

I know i am very very late in getting knowledge of this powerful principles but this is very nice article for getting knowledge of SOLID Principles for creating architecture of your project.

S: Single Responsibility Principle (SRP)
O: Open closed Principle (OSP)
L: Liskov substitution Principle (LSP)
I: Interface Segregation Principle (ISP)
D: Dependency Inversion Principle (DIP)

here is some nice articles which explains in simple words and with examples.

Thank you!

Posted in .Net, Architect, C#, SOLID Principles | Leave a Comment »

Refused to display url in a frame because it set ‘X-Frame-Options’ to ‘SAMEORIGIN’.

Posted by Viral Sarvaiya on July 21, 2016

Hello All,

After a very log time adding new post in my blog.

Few days before I get one problem that my MVC website is not opening in Iframe.

for eg. my URL is http://localhost/websitename/page

This URL I am opening in Iframe tab like below.

<iframe src="http://localhost/websitename/page" width="500" height="500" />

and getting error as below.

Refused to display ‘http://localhost/websitename/page’ in a frame because it set ‘X-Frame-Options’ to ‘SAMEORIGIN’.

and it is not opening my website in IFrame.


Open Global.asax.cs file, and add one method as below.

protected void Application_PreSendRequestHeaders()
 Response.AddHeader("X-Frame-Options", "AllowAll");

This will open website in Iframe.


protected void Application_Start()
 AntiForgeryConfig.SuppressXFrameOptionsHeader = true;

This will open website in IFrame

Hope this will helps you.


Posted in .Net, ASP.NET, C#, MVC | Tagged: , , , , | Leave a Comment »

LINQ expressions with javaScript!

Posted by Viral Sarvaiya on April 7, 2015

Hello All, after a long time..

I get very useful link which I like to share with you all.

Being a web developer and using javaScript everyday, Now more than ever javaScript is exploding in its usage.

we can use linq in javascipt. surprised? click here to learn more about that.


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

Using Jquery detect mobile

Posted by Viral Sarvaiya on October 22, 2013

Toay i get good script of jQuery that detect mobile.

It require to Jquery file –

Here code is.

$(document).ready(function () {
  var isMobile = {
    Android: function () {
      return navigator.userAgent.match(/Android/i) ? true : false;
    BlackBerry: function () {
      return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    iOS: function () {
      eturn navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    Windows: function () {
      return navigator.userAgent.match(/IEMobile/i) ? true : false;
    any: function () {
      return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());

Hope it helps you.


Posted in Javascript, Jquery | Tagged: , , , , | Leave a Comment »

Export to Excel using jQuery

Posted by Viral Sarvaiya on October 21, 2013

From my past posts explains how to export to excel as
1. Export GridView Data into CSVFile In
2. GridView Export to Excel

So here its 3rd type to export to excel using Jquery.

In javascript, we have function. We are using same function to export to excel using jquery.


MIMEtype : this is the optional parameter, and its for type of document. default it take as “text/html”
replace : this is also optional parameter, and its set.


$("#btn_Export").click(function(e) {'data:application/,' + $('#divData').html());

Hope its helps you.


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

Use of Cookies in jQuery

Posted by Viral Sarvaiya on September 27, 2013

I have already writen that how to use cookies in and silverlight from below post

here i am posting new post that shows how to use cookies in Jquery

Create cookie:

$.cookie('myCookie', 'CookieValue', { expires: 7, path: '/' });

Read cookie:

$.cookie('myCookie'); // => "CookieValue"

Read all available cookies:

$.cookie(); // => { "myCookie": "CookieValue", "...remaining": "cookies" }

Delete cookie:

// Returns true when cookie was found, false when no cookie was found...

// Same path as when the cookie was written...
$.removeCookie('myCookie', { path: '/' });


Posted in .Net, ASP.NET, Javascript, Jquery | 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 »

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 »

Delete multiple Procedure/Table/Trigger form sqlserver database

Posted by Viral Sarvaiya on December 14, 2012

In sql server we use one query for drop table/procedure/trigger like below

Drop table table_name
Drop procedure Procedure_name
Drop trigger Trigger_name

But if we want to delete some or all Tables/Procedure/Trigger then what?
have to delete one by one?
We can create one loop with cursor to drop table/procedure/trigger for that as like below.

we can create SP to delete perticulers of the database as passing text and type as a parameter.

For that we can use sys.objects table

For table Type = ‘U’
For procedure Type = ‘P’
For Trigger Type = ‘TR’

For more type of sys.objects please refer

Stored procedure is as below.

@Type VARCHAR(2),
@SearchText VARCHAR(50)

DECLARE @procName varchar(500)

IF (@type != '')

DECLARE cur cursor

FOR SELECT [name] FROM sys.objects WHERE TYPE = @Type AND NAME LIKE '%'+  @SearchText +'%'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
SET @StrDrop = ((CASE WHEN @Type = 'U' THEN  'drop table '
WHEN @Type = 'P' THEN 'drop Procedure '
WHEN @Type = 'TR' THEN 'Drop trigger '
END) + @procName)
IF (@StrDrop != '')
EXEC @StrDrop

fetch next from cur into @procName
close cur
deallocate cur


As like this we can also drop table constraints.

Hope this will helps you.


Posted in Sql Server | Tagged: , , , , , , | Leave a Comment »

%d bloggers like this: