c# Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/tag/c/ Everyone can code! Thu, 16 Apr 2020 02:49:09 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 209870635 This project references NuGet package(s) that are missing on this computer. https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/ https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/#respond Thu, 16 Apr 2020 02:49:09 +0000 https://karthiktechblog.com/?p=463 Many of us have ran into issue “This project references NuGet package(s) that are missing on this computer”. There are many different reason as to why someone will get this error while you build the solution. Error Details This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download […]

The post This project references NuGet package(s) that are missing on this computer. appeared first on Learn Smart Coding.

]]>
Many of us have ran into issue “This project references NuGet package(s) that are missing on this computer”. There are many different reason as to why someone will get this error while you build the solution.

Error Details

This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props

Looking at the error, it is triggered from somewhere in the code. Let’s go to the .csproj file and this can be found at the end of the file.

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
  </Target>

A solution to “This project references NuGet package that are missing error”

The error is tied to the package Microsoft.CodeDom.Providers.DotNetCompilerPlatform. Follow the below three steps to solve the issue.

Step 1

Remove the package from package.config file.

<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net46" />

Step 2

Edit the .csproj project file and removed the below settings

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
  </Target>

Step 3

Go to package manager console and run the command Update-Package –reinstall

Step # 2 and 3 were given by other users and I appreciate those users. Point # 1, removing the Microsoft.CodeDom.Providers.DotNetCompilerPlatform from package.config file is more important. Also, after running the command mentioned in step #3, the issue resolved. All unwanted packages removed and required package reference updated

Reference

There are other similar fixes which might work for few scenarios. Take a look at this post from StackOverflow

Also Read

How to upload a file in ASP.NET Web API

Conclusion

In this post, I showed how to resolve a common error “This project references NuGet package(s) that are missing on this computer”. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post This project references NuGet package(s) that are missing on this computer. appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/feed/ 0 463
Working with optional body parameters in ASP.NET Core 2.2 https://blogs.learnsmartcoding.com/2020/04/04/working-with-optional-body-parameters-in-asp-net-core-2-2/ https://blogs.learnsmartcoding.com/2020/04/04/working-with-optional-body-parameters-in-asp-net-core-2-2/#respond Sat, 04 Apr 2020 20:33:43 +0000 https://karthiktechblog.com/?p=444 Working with optional body parameters in ASP.NET Core 2.2 is now possible and I will show how to solve the issue in this post. Optional parameter exists in .Net for a long time. Specifying the default value used to be enough to mark them as optional. However, marking a body parameter in a Web API […]

The post Working with optional body parameters in ASP.NET Core 2.2 appeared first on Learn Smart Coding.

]]>
Working with optional body parameters in ASP.NET Core 2.2 is now possible and I will show how to solve the issue in this post. Optional parameter exists in .Net for a long time. Specifying the default value used to be enough to mark them as optional. However, marking a body parameter in a Web API action method is not going to work if you are working with .NET Core 2, 2.1 and 2.2 versions.

Let me explain the problem that you might face and a solution to solve the problem.

An issue in accepting body parameter as optional

I have a model class in my action method and that reads the content from the body as shown below.

        // POST api/values
        [HttpPost]
        public IActionResult Post([FromBody]ModelClass request = null)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            return Ok();
        }

Here is the problem, as soon as you include an attribute [FromBody], MVC binding will trigger. If you did not send content in the request body, you will see an error as shown below.

{
  "": [
    "A non-empty request body is required."
  ]
}

This is an existing issue in .NET Core 2.0. Optional body parameters no longer work since upgrading to .NET Core 2.0 #6920

Solution

One of the solutions is to read the content from the request body and then process it if it was sent in the request.

 string body;
            SomeClassModel model = null;
            using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
            {
                body = reader.ReadToEnd();
            }

            if (!string.IsNullOrEmpty(body))
            {
               finalModel = JsonConvert.DeserializeObject(body);
            }

This way the body parameters can be made optional and custom validation can be implemented in case you need to validate a JSON string in the body parameter.

Related Posts

Implement create, read, update, and delete functionalities using Entity Framework Core

Conclusion

In this post, I showed how to work with optional body parameters in ASP.NET Core 2.2. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Working with optional body parameters in ASP.NET Core 2.2 appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/04/working-with-optional-body-parameters-in-asp-net-core-2-2/feed/ 0 444
How to cast int to enum in C# https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/ https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/#respond Wed, 15 Jan 2020 03:03:36 +0000 https://karthiktechblog.com/?p=326 Introduction In this short post, I show How to cast int to enum in C#. We have used an enumeration type (or enum type) in our day to day programming. Enum is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, we used […]

The post How to cast int to enum in C# appeared first on Learn Smart Coding.

]]>
Introduction

In this short post, I show How to cast int to enum in C#. We have used an enumeration type (or enum type) in our day to day programming. Enum is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, we used the enum keyword and specified the names of enum members as shown in below example.

public enum OrderStatus
{
Received = 1,
InProgress = 2,
Processed = 3,
Shipped = 4
}

How to convert int to enum ?

Let’s take an example to demonstrate real time scenario. Consider we have a field that represents order status for a given product order.

public OrderStatus Status {get; set;}

OrderStatus is the enum that is defined with various status. E.g. Received, InProgress, Processed and Shipped.

Say you need to convert int or string to enum, it is easy to do so.

OrderStatus variableName = (OrderStatus)Enum.Parse(typeof(OrderStatus), yourStringVariable);

Yes, it is that easy to cast int to enum type.

Validate enum property in model

Say, your enum property needs to be validated in a given model, simple use the EnumDataType as shown below.

[Required]
[EnumDataType(typeof(OrderStatus), ErrorMessage = "Provide initial order status")]
public OrderStatus Status { get; set; }

Resource

Read more on Enum

Interested in Azure certification? Take a look at my post EXAM AZ-203: DEVELOPING SOLUTIONS FOR MICROSOFT AZURE

Conclusion

In this short post, I showed how to cast int or string to enum in C#. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to cast int to enum in C# appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/feed/ 0 326
Policy and Resource based authorization in ASP NET Core https://blogs.learnsmartcoding.com/2019/12/26/policy-and-resource-based-authorization-in-asp-net-core/ https://blogs.learnsmartcoding.com/2019/12/26/policy-and-resource-based-authorization-in-asp-net-core/#respond Thu, 26 Dec 2019 10:53:01 +0000 https://karthiktechblog.com/?p=250 Introduction In this post, we will see how to implement Policy and Resource based authorization in ASPNETCore. There are instance where we need to validate the incoming data model. We will see how to validate the data model and authorize. In our example, say we have two entities namely, Category and Product. Examples in this […]

The post Policy and Resource based authorization in ASP NET Core appeared first on Learn Smart Coding.

]]>
Introduction

In this post, we will see how to implement Policy and Resource based authorization in ASPNETCore. There are instance where we need to validate the incoming data model. We will see how to validate the data model and authorize.

In our example, say we have two entities namely, Category and Product. Examples in this post shows how to validate the policy requirement along with the incoming model data which is inside the request body.

Are you looking for Azure AZ-203 certifications? Learn more by visiting below link.

 public class Product
    {
        public int Id { get; set; }
        [Required]
        [MinLength(5), MaxLength(200)]
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DateTime? AvailableSince { get; set; }
        public int StockCount { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
        public List ProductImages { get; set; }
        public Status Status { get; set; }
    }

 public class Category
    {
        public int Id { get; set; }
        [Required]
        [MinLength(2), MaxLength(200)]
        public string Name { get; set; }
        public Status Status { get; set; }
    }

An authorization policy consists of one or more requirements. Policy is registered as part of the authorization service configuration, in the ConfigureServices method in the startup class.

Let us register two policy in our startup class as mentioned above.

 
services.AddAuthorization(options =>
            {
                options.AddPolicy("ProductAuthorizationPolicy", policy =>
                       policy.Requirements.Add(new ProductRequirement()));

                options.AddPolicy("CategoryAuthorizationPolicy", policy =>
                      policy.Requirements.Add(new CategoryRequirement()));

            });
Configure policy requirement in ConfigureService method

ProductRequirement and CategoryRequirement are the class which implements IAuthorizationRequirement. IAuthorizationRequirement is from the namespace Microsoft.AspNetCore.Authorization

Let’s take a look at CategoryRequirement Resource based Authorization handler.

Policy and Resource based authorization in ASPNETCore

{
    public class CategoryAuthorizationHandler :
    AuthorizationHandler
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       CategoryRequirement requirement,
                                                       Category resource)
        {
            if (context.User.Identity?.Name != null && resource.Name != null)
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }

    public class CategoryRequirement : IAuthorizationRequirement { }
}

IAuthorizationService has two AuthorizeAsync method overloads: one accepting the resource and the policy name and the other accepting the resource and a list of requirements to evaluate.

Task AuthorizeAsync(ClaimsPrincipal user,
                          object resource,
                          IEnumerable requirements);
Task AuthorizeAsync(ClaimsPrincipal user,
                          object resource,
                          string policyName);
Policy based authorization in ASP NET Core

Now, how do we call this policy from an API endpoint and validate the requirement?

We have a controller for Category and that will look as shown below. The following code sample assume authentication has run and set the User property.

  [Route("api/[controller]")]
    [ApiController]
    public class CategoryController : ControllerBase
    {
        public CategoryController(IAuthorizationService authorizationService)
        {
            AuthorizationService = authorizationService;
        }

        public IAuthorizationService AuthorizationService { get; }

        // POST api/values
        [HttpPost]     
        public async Task Post([FromBody] Category category)
        {            
            /*
             This is a way the policy is manually triggered with the resource E.g. Category in this case
             */
            AuthorizationResult authResult = await AuthorizationService.AuthorizeAsync(User,
                category, "CategoryAuthorizationPolicy");

            if (!authResult.Succeeded)
            {
                return Forbid();
            }

            return Ok();
        }
    }
policy based authorization in ASPNETCore

If you wonder how to validate data model in a HTTPost call, here is an example.

In this below sample, we have an end point which accepts Product model in the request body

{
    public class ProductAuthorizationHandler : AuthorizationHandler
    {
        public ProductAuthorizationHandler(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }
        public IHttpContextAccessor HttpContextAccessor { get; }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       ProductRequirement requirement)
        {
            Product productModel;
            using (var reader = new StreamReader(HttpContextAccessor.HttpContext.Request.Body))
            {
                var bodyContent = reader.ReadToEnd();
                productModel = JsonConvert.DeserializeObject(bodyContent);
            }

            if (context.User.Identity?.Name!=null && productModel!=null&& productModel.Price>3) 
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
    public class ProductRequirement : IAuthorizationRequirement { }
}
Policy and Resource based authorization in ASP NET Core

We have Product controller and code sample is below.

 [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {    
        // POST api/values
        [HttpPost]
        [Authorize(Policy = "ProductAuthorizationPolicy")]
        public IActionResult Post([FromBody] Product product)
        {
            return Ok();
        }        
        
    }
Resource based authorization in ASPNETCore

This is just an example of how to validate the incoming data model which is in the request body.

In order to access the request body, we need IHttpContextAccessor to be injected by DI. With the instance of IHttpContextAccessor, the request body is read and converted to the string to the required model.

Do not forget to configure the IHttpContextAccessor in the ConfigureServices method in the startup class.


services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

If you would like to learn simple authorization, here is the link to it Simple Authorization.

Conclusion

In this post, we looked at how to implement Policy and Resource based authorization in ASPNETCore. Also, this post covered how to validate the incoming data model.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Policy and Resource based authorization in ASP NET Core appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2019/12/26/policy-and-resource-based-authorization-in-asp-net-core/feed/ 0 250
How to: Create CLR stored procedure and Work with CLR database object https://blogs.learnsmartcoding.com/2019/09/17/work-with-clr-database-object-to-create-clr-stored-procedure-using-c-with-vs-2019/ https://blogs.learnsmartcoding.com/2019/09/17/work-with-clr-database-object-to-create-clr-stored-procedure-using-c-with-vs-2019/#respond Tue, 17 Sep 2019 22:25:20 +0000 https://karthiktechblog.com/?p=119 In this Article, you will learn how to work with CLR database object to create CLR stored procedure using c# with vs 2019. I have covered couple of simple examples in this article. Also, I will walk you through the errors that you might encounter while you follow this article. Also, you will learn how […]

The post How to: Create CLR stored procedure and Work with CLR database object appeared first on Learn Smart Coding.

]]>
In this Article, you will learn how to work with CLR database object to create CLR stored procedure using c# with vs 2019. I have covered couple of simple examples in this article.

Also, I will walk you through the errors that you might encounter while you follow this article. Also, you will learn how to resolve those errors.

Requirements to Create CLR Stored Procedures

  • In the common language run time (CLR), stored procedures are implemented as public static methods.
  • You can declare return type either as void, or an integer.
    • Returned integer value is treated as the return code from the procedure if the return type is an integer.
      • E.g. EXECUTE @statusReturned = procedureName

Step by step implementation to create CLR stored procedure.

Database Creation

Let’s create one new Database and one table for our examples. You can use your own database and its tables for your test case.

CREATE DATABASE SqlCLR

GO
USE SqlCLR

GO

CREATE TABLE Employers 
(
Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL, 
EmployerName NVARCHAR(250) NOT NULL,
NoOfEmployees INT,
Revenue DECIMAL(7,2)
)

GO

INSERT INTO [dbo].[Employers]([EmployerName],[NoOfEmployees],[Revenue])VALUES
('karthiktechblog',10, 100),
('orange 2',140, 76655),
('apple',10000, 10080),
('android',12990, 17760)

GO

Creating C# Project for CLR stored procedure

Creating a SQL Server CLR project is different in different version of visual studio. In this Article, you will see how to create CLR stored procedure using visual studio 2019.

To get started, open visual studio 2019 IDE and choose File => New => Project as shown in the image below.

Work with CLR database object to create CLR stored procedure
File => New => Project

SQL CLR C# Stored Procedure
SQL Server Database Project
Configure project
Configure your new project
add new item for sql clr stored procedure
SQL CLR C# Stored Procedure

When you select “SQL CLR C#” from right side menu, you can choose “SQL CLR C# Stored Procedure” from the left side menu. After you choose the required menu items, provide a stored procedure name in the “Name” filed in the bottom. E.g. PrintUTCDate. Refer the below image for your understanding.

SQL CLR C# Stored Procedure
SQL CLR C# Stored Procedure
SQL CLR C# Stored Procedure
SQL CLR C# Stored Procedure

I have created two stored procedures.

  1. “PrintUTCDate” method which do not accepts parameter.
  2. “AddDaysToCurrentDate” method which accepts one parameter. E.g. (SqlInt64 noOfDaystoAdd). Note that parameter type can be SQL DataType or C# equivalent datatype. E.g. In this case I can use int instead of SqlInt64.

Below are the code for above mentioned stored procedures.

using Microsoft.SqlServer.Server;
using System;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void PrintUTCDate ()
    {
        SqlPipe sqlPipeLine = SqlContext.Pipe;
        sqlPipeLine.Send(DateTime.UtcNow.ToString());
    }   
         
}
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void AddDaysToCurrentDate(SqlInt64 noOfDaystoAdd)
    {
        List results = new List();

        results.Add(new SqlMetaData("Current Date", SqlDbType.NVarChar, 128));
        results.Add(new SqlMetaData("Date Output", SqlDbType.NVarChar, 128));
        // Create a record object that represents an individual row, including it's metadata.  
        SqlDataRecord record = new SqlDataRecord(results.ToArray());

        record.SetSqlString(0, DateTime.UtcNow.ToString());
        record.SetSqlString(1, DateTime.UtcNow.AddDays(noOfDaystoAdd.Value).ToString());

        // Send the record to the client.  
        SqlContext.Pipe.Send(record);
    }
}

Build and Publish project

Let’s publish our project to our database “SqlCLR”

To build this SQL CLR project, go to menu Build => Build CLR.POC (your project name) or use Shift + F6

Build project
Build Project

You will be presented with a Popup then you need to choose your database connection details to deploy the project. I am using my localDb configuration for this example. E.g."LocalDb)\MSSQLLocalDB".

Feel free to use your database server details

Follow the steps specified in the below two images. Provide the database name that we created for this demo.

setup database connection
Setup database connection
Publish database connection
Publish database connection

When publish runs, there will be script generated by the project. Publish script will look like below.

-- Only for reference, do not run this script as it will not work.
/*

Deployment script for SqlCLR

This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/

GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;

SET NUMERIC_ROUNDABORT OFF;


GO
:setvar DatabaseName "SqlCLR"
:setvar DefaultFilePrefix "SqlCLR"
:setvar DefaultDataPath "C:\Users\Kkannan\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB"
:setvar DefaultLogPath "C:\Users\Kkannan\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB"

GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF; 
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
    BEGIN
        PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
        SET NOEXEC ON;
    END

GO
USE [$(DatabaseName)];

GO
PRINT N'Altering [CLR.POC]...';

GO
ALTER ASSEMBLY [CLR.POC]
    DROP FILE ALL;

GO
ALTER ASSEMBLY [CLR.POC]
    FROM 01100.....; (ignored data )

GO
ALTER ASSEMBLY [CLR.POC]
    DROP FILE ALL
    ADD FILE FROM 0x4D6963726F736F667420432F432B2B204D534620372E30300D0A1A4450000...... AS N'CLR.POC.pdb'; (ignored data )

GO
PRINT N'Update complete.';

GO

Note: If you get error similar to “Execution of user code in the .NET Framework is disabled. Enable “clr enabled” configuration option” then run the below script to resolve.

use SqlCLR;

sp_configure 'clr enabled', 1
go
RECONFIGURE
go
sp_configure 'clr enabled'
go

This is how our database looks after publish was successful.

Database structure after deployment
Database structure after deployment

Verifying Results

Executing Stored Procedure

First, let’s take our first CLR stored procedure and run. Below is the script to run CLR stored procedure. After you execute the stored procedure, you can check the results that is shown below.

USE [SqlCLR]
GO

DECLARE	@return_value int

EXEC	@return_value = [dbo].[PrintUTCDate]

SELECT	'Return Value' = @return_value

GO

Output

clr stored procedure output
Output

If you notice carefully, the output of the CLR stored procedure is shown in the Message tab as highlighted in the image. In next example, we will see how to display the result data in Result.

Now, let’s execute our second CLR stored procedure. Below is the script to run CLR stored procedure.

USE [SqlCLR]
GO
DECLARE	@return_value int

EXEC	@return_value = [dbo].[AddDaysToCurrentDate]
		@noOfDaystoAdd = 1

SELECT	'Return Value' = @return_value
GO

Output

clr stored procedure output
Output

Bonus example

We can also send a record set using CLR stored procedure. I have created a CLR stored procedure “GetEmployers” that queries and returns all the records from the table in the database.

Use below c# code that creates a stored procedure named GetEmployers. This step is similar to the above mentioned steps.

using Microsoft.SqlServer.Server;
using System.Data.SqlClient;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void GetEmployers ()
    {
        using (SqlConnection connection = new SqlConnection("context connection=true"))
        {
            connection.Open();
            SqlCommand command = new SqlCommand("SELECT Id, EmployerName, NoOfEmployees, Revenue FROM SqlCLR.dbo.Employers", connection);
            SqlDataReader reader = command.ExecuteReader();
            SqlContext.Pipe.Send(reader);
        }
    }
}

Now, build and Publish the project. Once you build, your newly created clr stored procedure will be available in your database.

Script to run in SQL to test this clr stored procedure.

USE [SqlCLR]
GO

DECLARE	@return_value int

EXEC	@return_value = [dbo].[GetEmployers]

SELECT	'Return Value' = @return_value

GO

Output

clr stored procedure output
Output

Reference Links: MSDN Docs

Conclusion

In this Article, you learned how to work with CLR database object to create CLR stored procedure using c# with vs 2019.

That’s all from this article. If you have any questions or just want to chat with me, feel free to leave a comment below. If you want to get continuous update about my blog, make sure to follow me on Facebook and Twitter.

The post How to: Create CLR stored procedure and Work with CLR database object appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2019/09/17/work-with-clr-database-object-to-create-clr-stored-procedure-using-c-with-vs-2019/feed/ 0 119