Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

Creating a Lambda function in .netCore with Visual Studio and AWS Visual Studio Toolkit

AWS allows .net Core framework also while creating Lambda functions. But the AWS console doesn't have any editor for .Net Core framework. It just has the option to upload the code in a zip file. We need to create the Lambda function in our local machine and upload the package file. We can create the Lambda function easily in Visual Studio with the template given in AWS Toolkit for Visual Studio. AWS Toolkit for Visual Studio have some templates for creating AWS Lambda functions easily using .NET Core. This post will guide you to create a Lambda function in .Net core using Visual Studio

Prerequisites

Following are the prerequisites for creating and deploying Lambda functions in Visual Studio

Create a .NET Core Lambda in Visual Studio

Following are the steps to create a Lambda function in Visual Studio
1) Open Visual Studio -> File menu -> New -> Project.
2) In the New Project dialog box, Select "AWS Lambda" under Installed -> Visual C#

     It will show you two types of project.
a) AWS Lambda project: These templates are for creating a project to develop and deploy an                 individual Lambda function.
b) AWS Serverless Application: These templates are for creating Lambda functions with a server-less AWS CloudFormation template. AWS server-less applications enable you to define more than just the function. For example, you can simultaneously create a database, add IAM roles, etc., with server-less deployment. AWS server-less applications also enable you to deploy multiple functions at one time.

3) Select AWS Lambda Project (.NET Core - C#) template.
4) Enter Name and Location for the project.
5) In the next screen, select Blue print for the Lambda you want to develop. For this example, I am selecting Empty Template.
6) It will create the project with the following structure 
Here, we need to examine two files
  • Function.cs
  • aws-lambda-tools-defaults.json

Function.cs 

Following is the sample code which was created automatically in Function.cs
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 LambdaSample
{
    public class Function
    {
        
        /// 
        /// A simple function that takes a string and does a ToUpper
        /// 
        /// 
        /// 
        /// 
        public string FunctionHandler(string input, ILambdaContext context)
        {
            return input?.ToUpper();
        }
    }
}
Here FunctionHandler is the function where we need to write out Lambda function code. The above code will take a string as parameter and will return the same in UPPER Case. Here ILambdaContext object provides properties with information about the invocation, function, and execution environment(Read more about ILambdaContext here). For the time being, I am not writing any logic in the function, but I just added some logs. My FunctionHandler is as below after adding some logs to it
public string FunctionHandler(string input, ILambdaContext context)
{
 context.Logger.LogLine($"Input string:{input}");
 var upperCaseValue = input?.ToUpper();
 context.Logger.LogLine($"Upper case value:{upperCaseValue}");
 return upperCaseValue;
}

aws-lambda-tools-defaults.json

This is the file from where the Lambda function creator reads the default values while deploying the lambda function. You can set the default values like, framework, run time, memory size, timeout, function-handler etc parameters required for Lambda. Here function-handler defines the starting functionof the Lambda. For our sample it is "LambdaSample::LambdaSample.Function::FunctionHandler". In this, first part indicates the NameSpace(LambdaSample), second part indicates the ClassName with namespace(LambdaSample.Function) and third part indicates the Function name in the class(FunctionHandler).

Following is the aws-lambda-tools-defaults.json file created automatically by Visual Studio
{
  "Information" : [
    "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
    "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",

    "dotnet lambda help",

    "All the command line options for the Lambda command can be specified in this file."
  ],

  "profile":"default",
  "region" : "us-east-1",
  "configuration" : "Release",
  "framework" : "netcoreapp2.1",
  "function-runtime":"dotnetcore2.1",
  "function-memory-size" : 256,
  "function-timeout" : 30,
  "function-handler" : "LambdaSample::LambdaSample.Function::FunctionHandler"
}

Note: If you change the class name or function name, you need to update function-handler in the above file

Publish the Lambda Function

1) In Solution Explorer, right-click the project, and then choose Publish to AWS Lambda.

2) On the Upload Lambda Function page, in Function Name, type a name for the function or select a previously published function to republish -> Choose Next.

3) In the Advanced Function Details page,
  • Select Existing role: Select any role assoicated with your role. The role is used to provide credentials for any AWS service calls made by the code in the function. Your account should have IAM:ListPolicies action, or the Role Name list will be empty and you will be unable to continue.
  • Change Memory & Timeout values if required. 
  • Assign VPC and its Subnets if those are required by your Lambda
  • Add any Environment variable that your Lambda function needs

4) Click on Upload
5) This will open Uploading function page as shown below and the screen will automatically closes after Lambda function uploaded to AWS account

6) After function uploaded successfully, it will opens the following screen which allows you to execute the lambda function, change the Configuration,Event Sources and check the logs from Visual Studio. 

Note: You can also open the above screen for any existing Lambda function by Opening "AWS Explorer" -> AWS Lambda -> Double click on the required function.

Invoke the Function from Visual Studio

We can invoke the Lambda function from Visual Studio directly by the screen shown in the above image

1) Select any Example Request to choose any predefined request. But for our sample, it is just accepting a string as input, I have given "gopiportal_test" in the Request box


2) Click on "Invoke" button
3) This will execute the Lambda function automatically and will show the Response and the function logs

That's it...
Happy Coding !😊

Disable "Based on your project, we have identified extensions you may find helpful" message

With the latest update of the Visual Studio 2015, you can get the "Based on your project, we have identified extensions you may find helpful" message if you open .html or .cshtml files.






It may slows down the file open process as it searches for the extensions for that page.
Clicking "Don't ask again" disables the notification only until the Visual Studio restarted.
It is the issue with the Visual Studio (https://github.com/aspnet/Tooling/issues/305).
So to turn off it permanently do the following steps

1) Go to Tools > Options > Text Editor > HTML > Advance
2) Set Identify Helpful Extensions to False
3) Click on OK.

Note: It will be "False" already if you dismissed the yellow bar in the current VS session. In this case just the action of showing the options dialog and closing it with "OK" will be enough to persist the setting.

Error installing Azure SDK in Visual Studio 2015 Community Edition.

Today I tried to install azure SDK in Visual Studio 2015 community edition through Web platform installer and I am getting the following error.

"Azure Storage Emulator requires LocalDb to be installed. You must enable the Microsoft SQL Server Data Tools (SSDT) feature in Visual Studio 2015 to install Local Db before proceeding."










The reason for this issue is SSDT tools are not installed at the time of installing Visual studio.

The solution is
  • Open Control panel -> Programs and features
  • Select Microsoft Visual Studio
  • Right click on it and Select Change
  • Click on Modify
  • Check "Microsoft SQL Server Data Tool" under "Windows and Web Development"
  • Click Update
That's it :) Happy Coding.

Create Code Snippet in Visual Studio 2010

IntelliSense Code Snippets provide a way for you to insert ready-made snippets of code into your projects.IntelliSense Code Snippets are XML files with a .snippet file name extension that adhere to the  IntelliSense Code Snippet XML schema (see Code Snippets Schema Reference).

Creating a Snippet File

1) To create a snippet file, you must create an XML file with .snippent extension
2) Open the file
3) Right-click on the editor window and select "Insert Snippet" to create a basic snippet template.
4) In the header section, like web page we need to give meta information for the snippet. We have the following elementes in header section
  a) Title - Title of the snippet.
  b) Author - Author of the snippet.
  c) Description - Description for the snippet
  d) Shortcut - It is the trigger word that activates your snippet (for example "gopisnippet")
  e) SnippetType
        The text value must one of the folllowing values.
         SurroundsWith: Allows the code snippet to be placed around a selected piece of code.
         Expansion: Allows the code snippet to be inserted at the cursor.
         Refactoring: Specifies that the code snippet is used during Visual C# refactoring. Refactoring cannot           be used in custom code snippets.
      Since we are creating an Expansion Snippet, remove the tag
< SnippetType >SurroundsWith < /SnippetType>
5) Snippet section:
    a) Code :Provides a container the short code blocks of IntelliSense Code Snippets."Language" is the required attribute for this. Since we are creating a snippet for C# so change it to CSharp.
     <Code Language=”CSharp”>
    b) The Code section contains the code block to be added.


The final version of the snippet is

<xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    < Header>
      < Title >Test Snippet  <  /Title>
      < Author  > Gopi  < /Author>
     < Shortcut  > gopisnippet  < /Shortcut>
      < Description  > Gopi Snippet description  < /Description>
     < SnippetTypes>
        < SnippetType > Expansion  < /SnippetType>
     </SnippetTypes>
    </Header>
    < Snippet>
      <Declarations>
        <Literal>
          <ID >  name  </ID>
          <Default >  value  < /Default>
        </Literal>
      < /Declarations>
      < Code Language="CSharp">
        < ![CDATA[using (SqlConnection oCon = new SqlConnection(DBHelper.CONN_STRING_SQL))
            {
             
            }]]>
      < /Code>
    < /Snippet>
</CodeSnippet>

Note: Inside the Snippet element, add the References element and all of the required child elements that add a reference to the project when the snippet is inserted. But it is now supports only for Visual Basic Code Snippets.

Load Snippets into Visual Studio:

To use a code snippet, first it will need to be loaded in Visual Studio. Follow the below steps to load your snippets in Visual studio.
1) Naviagate to "Tools -> Code Snippets Manager" in visual studio.
2) Select Import
3) Locate your snippet file
4) Visual Studio will then prompt you to where you want to place your snippet. By default "My Code Snippets" folder is checked. Click on Finish.

Now your snippet is ready for use.

To use code snippets through the Insert Code Snippet Menu:

1) In the Code Editor, put the cursor where you want to insert the code snippet.
2) Launch the Insert Code Snippet menu in one of three ways:
    a)Press CTRL+K, CTRL+X.
    b) On the Edit menu, point to IntelliSense, and then click Insert Snippet.
    c) Right-click the mouse and then select the Insert Snippet command on the shortcut menu.
3)Select the code snippet from the code snippet inserter and then press TAB or ENTER, or double-click the snippet.

To use code snippets through the snippet’s shortcut:

1)In the Code Editor, put the cursor where you want to insert the code snippet.
2) Type the shortcut for the code snippet that you want to add to your code.

OR

Type the first few letters of the shortcut and then press either CTRL+SPACE (C#) or a question mark followed by the TAB key (VB) to view the completion list, and then select the snippet shortcut from the list.

3) Press the TAB key once for Visual Basic or twice for C Sharp to invoke the code snippet.

Visual Studio Keyboard Shortcut Posters

Here is a collection of .NET Framework and Visual Studio Posters available for free. The .NET Framework posters can be used to find important class library details and relationships in the .NET Framework.

Visual C# Shortcut Posters
Visual Studio 2005 Shortcuts
Visual Studio 2008 Shortcuts
Visual Studio 2010 Shortcuts

Visual Basic Shortcut Posters
Visual Studio 2005 Shortcuts
Visual Studio 2008 Shortcuts
Visual Studio 2010 Shortcuts


Visual C++ Shortcut Posters

.NET Framework 3.5 Common Namespaces and Types Poster: The .NET Framework 3.5 Common Namespaces and Types Poster is downloadable as XPS or PDF format.

C# Language Specification 4.0: It is the Word document containing all the basic specifications of C# Language.


Thanks!..