Generate SSH Key to Connect to GitHub

If you are not sure you have an SSH key already installed on your machine, you can do a quick check by issuing the following command. I am using GitBash to do so:

$ ls  -al ~/.ssh

If you don’t see the two files in the ssh folder in c:\Users\<userName>\ssh, then you don’t have the key created just yet! See image below:

 

 

What you need now is to generate a new SSH key which can be done by using the following command with parameters:

$ ssh-keygen -t rsa -b 4096 -C “myEmail@myDomain.com”

You’ll be prompted to enter the file name to save the key to. Just hit enter to keep the suggested default file name. Do the same for passphrase and hit enter twice until you see the image below:

 

 

 

 

 

 

 

 

You can also verify by going to the Users\yourName\ssh folder to confirm the files are created.

Next, you want to ensure that the ssh-agent is running. You can do so by issuing the following command:

$ eval $(ssh-agent -s)

 

 

 

Next, add your SSH private key to the ssh-agent

$ ssh -add ~/.ssh/id_rsa

 

 

Open the id_rsa.pub file in notepad and copy its contents to the clipboard. Note: There were two files created, i.e. id_rsa and id_rsa.pub. You want to open and copy the contents  of id_rsa.pub file.

Now, go to your GitHub account. Under settings, locate the SSH and GPG keys tab and add the new SSH key from Notepad by clicking on the New SSH key button. See image below.

Finally, you can verify that your machine can communicate with GitHub by typing the following command:

$ ssh -T git@github.com

Hope you found the post useful!

Posted in Git | Tagged , , , , | Leave a comment

How to get XML data from Web API

If you’ve come this far, I can only presume that you are well versed with RESTful Services. In any case, if you are new to REST, here’s the definition.

Definition:

Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the internet. RESTful Web services allow the requesting systems to access and manipulate textual representations of Web resources by using a uniform and predefined set of stateless operations. Other kinds of Web services, such as SOAP Web services, expose their own arbitrary sets of operations.

Content Negotiation:

Content negotiation in ASP.NET Web API is an intrinsic server-driven mechanism, used to determine, based on client’s request, which media type formatter is going to be used to return an API response.

Getting XML Data:

Assuming that you are using ASP.NET Core, in order to add XML support, following are some of the considerations to get XML data from a Web API.

Be sure to register XmlDataContractSerializerFormatter in ConfigureServices of your Startup class.

Please note, I am using Visual Studio 2019 and targeting ASP.NET Core 3.1.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
                    .AddXmlDataContractSerializerFormatters();
        }

In addition to the HttpGet verb, you also need to specify the format in order to request XML data like so in your controller class:

[HttpGet(“get.{format}”), FormatFilter]

[Route("api/[controller]")]
    [ApiController]
    [FormatFilter]
    public class EmployeesController : ControllerBase
    {
        private readonly SSRSWebApiContext _context;

        public EmployeesController(SSRSWebApiContext context)
        {
            _context = context;
        }

        // GET: api/<EmployeesController>
        [HttpGet("get.{format}"), FormatFilter]
        public IEnumerable<Employee> Get()
        {
            return _context.Employees.ToList();
        }

        // GET api/<EmployeesController>/5
        [HttpGet("{id}/get.{format}"), FormatFilter]
        public Employee Get(int id)
        {
            var emp = _context.Employees.FirstOrDefault(e => e.ID == id);
            return emp;
        }

Content-Type: XML:

Gets all Employees with XML as the return data. In the URL below, right after the base address, we have defined the Route, i.e. api/employees followed by the Content-Type i.e. “get.xml”.

Content-Type: JSON:

Gets all Employees with JSON as return data. In the URL below, right after the base address, we have the Route, i.e. api/employees followed by the Content-Type i.e. “get.json”.

 

As you can see; through the power of content negotiation, you can easily toggle between JSON and XML format based on client’s needs.

Do I need XML?:

You probably don’t! Majority of the clients rely on JSON data for most of their daily needs. However, recently, I had a requirement where I needed to bind XML data to an SSRS report. I am sure, there are other reasons why the client might need XML over JSON content.

Conclusion:

As you saw, to request content-type of XML requires minimal development effort on your side, which in essence, requires configuring the middleware without the need to write a new functionality.

Posted in .NET, Web API | Tagged , , , , , , | Leave a comment

EF Core 5.0 is round the corner

EF Core 5.0 is in flux and is slated to be released along with .NET 5.0. One thing to note is that EF Core 5.0 will not run on .NET Framework, unlike its predecessors. I personally think, this is good news as it is time to step up the ante and move out of the .NET legacy Framework  and onto the .NET Core ecosystem. That said, the plan is to maintain .NET Standard 2.1 compatibility through the final release.

Those of you who jumped on the EF Core bandwagon know full well that EF Core has come a long way from the time of its inception back in June 2016. Since then, there have been numerous incremental updates by the development team currently led by Arthur Wickers (formerly Diego Vega and Rowan Miller) along with the support of Andriy Svyryd, Brice Lambson, Jeremy Likness, Ia Jones, Maurycy Markowski, Shay Rojansky, Smit Patel, Erik Jensen and numerous OSS contributors around the globe who have worked diligently to completely transform this ORM. The capabilities and ease of use of EF Core has made its adoption compelling enough in modern software development ranging from desktop, web, mobile and UWP environments and across platforms.

What’s new in EF Core 5.0

  • Split Queries for related Collections

The following query will retrieve two levels of related collections using the Include like so:

var artists = context.Artists
    .Include(e => e.Albums).ThenInclude(e => e.Tags)
    .ToList();

The following SQL gets generated by default:

SELECT "a"."Id", "a"."Name", "t0"."Id", "t0"."ArtistId", "t0"."Title", "t0"."Id0", "t0"."AlbumId", "t0"."Name"
FROM "Artists" AS "a"
LEFT JOIN (
    SELECT "a0"."Id", "a0"."ArtistId", "a0"."Title", "t"."Id" AS "Id0", "t"."AlbumId", "t"."Name"
    FROM "Album" AS "a0"
    LEFT JOIN "Tag" AS "t" ON "a0"."Id" = "t"."AlbumId"
) AS "t0" ON "a"."Id" = "t0"."ArtistId"
ORDER BY "a"."Id", "t0"."Id", "t0"."Id0"

With the new AsSplitQuery API, the behavior can be altered as follows:

var artists = context.Artists
    .AsSplitQuery()
    .Include(e => e.Albums).ThenInclude(e => e.Tags)
    .ToList();

EF Core will generate the following SQL queries:

SELECT "a"."Id", "a"."Name"
FROM "Artists" AS "a"
ORDER BY "a"."Id"

SELECT "a0"."Id", "a0"."ArtistId", "a0"."Title", "a"."Id"
FROM "Artists" AS "a"
INNER JOIN "Album" AS "a0" ON "a"."Id" = "a0"."ArtistId"
ORDER BY "a"."Id", "a0"."Id"

SELECT "t"."Id", "t"."AlbumId", "t"."Name", "a"."Id", "a0"."Id"
FROM "Artists" AS "a"
INNER JOIN "Album" AS "a0" ON "a"."Id" = "a0"."ArtistId"
INNER JOIN "Tag" AS "t" ON "a0"."Id" = "t"."AlbumId"
ORDER BY "a"."Id", "a0"."Id"
  • Index Attribute
  • Improved Query Translation Exceptions
  • Exclude OnConfiguring when scaffolding
  • Translations for FirstOrDefault on strings

C#

context.Customers.Where(c => c.ContactName.FirstOrDefault() == 'A').ToList();

SQL

SELECT [c].[Id], [c].[ContactName]
FROM [Customer] AS [c]
WHERE SUBSTRING([c].[ContactName], 1, 1) = N'A'
  • Simplification of Case blocks
  • Database collations

For a detailed description of new features/announcements, please refer to the following resources below:

Posted in Uncategorized | Leave a comment

How to add multiple rows to a table at once

Let’s face it, most of the apps in the galaxy we live in are data bound. I don’t write apps that use sockets and presumably most of you don’t either, correct?

Now, in our day to day lives, we generally use a database of sorts, may it be SQL Server, MySQL, Oracle, PostgreSQL etc. all of which are relational. You have heard the famous cliche, “There are multiple ways to skin a cat”. Well, let’s not go there…suffice it to say, there are many solutions to a problem.

Without rambling too much, let’s get to the point. What I have below is a simple Entity Relational Diagram. To illustrate my point, I am attempting to add records into the Composite table from Magazine, Article and Author tables like so.

INSERT INTO Composite (Magazine, Title, PublishedDate, AuthorName)
    (SELECT 
        m.[Name], 
        a.Title,
        a.PublishDate,
        au.[Name]
    FROM
        Magazine m 
        INNER JOIN Article a ON m.MagazineId = a.MagazineId
        INNER JOIN Author au ON a.AuthorId = au.AuthorId)

As you can see without repeating Insert Into…statement multiple times just like you would typically do, one can accomplish the same by using the Select statement to select the columns belonging to one or more tables.

 

 

 

 

 

 

 

 

Output from the newly inserted records in the Composite table:

Posted in SQL Server | Leave a comment

How to Extend Session in ASP.NET

If you are building a web app using “Forms” as a mode of authentication, there’s really not much to it when it comes to extending a session automatically.

What I am suggesting is that your web session will extend on its own so long as you have defined slidingExpiration attribute in your web.config file like so:

<authentication mode="Forms"> 
    <forms name=".ASPXAUTH" loginUrl="~/Login.aspx" timeout="20" slidingExpiration="true"></forms> 
</authentication>

Now, if you are using the authentication mode as “Windows“, there’s no support for the slidingExpiration attribute. For that, you can implement a solution in jQuery by simply creating a dummy HTML file and calling it anything you like. In the example below, I’ve named it AjaxDemo.html. See code below.

One thing to note here is that I am concatenating Date and Time when making an asynchronous call to AjaxDemo.html. This is done to ensure that a unique value is returned from the server. This step is crucial in extending the session timeout beyond its default threshold of 20 minutes.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

    <title>Session Timeout</title>
    <script type="text/javascript">
        var sessionDelay = 5000; // 5 seconds

        $(function () {
            $("#btnExtendSession").click( function () {
                keepAlive();              
            });
        });

        function keepAlive() {
            var d = new Date();
            $.get('AjaxDemo.html?=' + d.getTime(), function () {
                timer = setTimeout(keepAlive, sessionDelay);
                clearTimeout(timer);
            });
        }

    </script>
</head>
<body>
    <button id="btnExtendSession">Extend Session</button>
</body>
</html>

When you click on the button “Extend Session” and open dev tools,  inside the Network tab, you would notice a unique value appended to AjaxDemo.html’s query string. See below:

Hope you found the post useful.

Posted in jQuery | Leave a comment

What is Blazor and Why should you Use it!

Introduction:
According to Microsoft Docs, Blazor is a framework for building client-side web UI with .NET. It’s a feature of ASP.NET, the popular web development framework that extends the .NET developer platform with tools and libraries for building web apps.

Blazor lets you build interactive web UIs using C# instead of JavaScript. Blazor apps are composed of reusable web UI components implemented using C#, HTML and CSS. Both client and server code is written in C#, allowing  you to share code and libraries across projects.

If you’ve done any client-side development, I’m assuming you are familiar with Vue, Angular, React or Aurelia. Each one of these technologies is built on top of JavaScript. Blazor is different, in that it allows a developer to build compelling UIs by leveraging your existing C#, HTML and CSS skills without writing a single line of JavaScript code. This sounds pretty amazing, correct?

What Browsers can my Blazor code run on?
All modern browsers have Web Assembly baked in on which your code runs. The browsers range from Chrome, IE, Edge, Safari including browsers on mobile devices.

Flavour of Blazor:
Blazor comes with two architectures:

  • Client-side Blazor (WebAssembly)
  •  Server-side Blazor

As of this writing, Server-side Blazor is the most stable release and can be used in production.

Client-side Blazor (WebAssembly) is still in preview and is likely to RTM mid-2020. The way it works is that when the application runs, it loads all assets such as static files, assemblies including the run-time which is later converted to WebAssembly bytecode without requiring a connection to the server. While it offers some advantages such as the non-dependence on the server for your hosting needs and also be able to work in offline scenarios. However, when it comes to jobs that require compute-intensive operation, then this architecture may not be suitable for your needs.

Server-side Blazor in my opinion does foot the bill easily as it conforms to the lowest common denominator. In another words, you are not restricted to just the latest modern browsers to run your server-side blazor code, but you can also have your code run on some of the older browsers that don’t have web assembly on them.

Furthermore, the server-side Blazor app runs inside ASP.NET runtime. Any changes to the app are copied using a WebSocket connection through SignalR. As a result, all updates are streamed from the server in real-time.

Does Blazor have Plugins?
Unlike Blazor’s predecessor technologies such as Flash and Silverlight that required plugins to be installed on the client’s machine, Blazor on the other hand does not require any plugins due to the fact that it runs in Web Assembly which is baked in every modern browser.

Advantages of Blazor:
Following are some of the advantages of Blazor:

  • Leverage your C# skills to build full-stack Web app
  • Reuse libraries that are .NET Standard compliant
  • Runs on .NET runtime
  • Runs on any browser
  • Doesn’t require any plugins
  • Download razor components from NuGet
  • Highly performant
  •  Runs at near-native speed inside the browser on WebAssembly
  • Allows interoperability between Blazor and JavaScript code

What Tools can I use to create Blazor Apps:
Blazor apps can be developed using Visual Studio 2019 (all versions) with .NET Core 3.1 SDK or alternatively you can use a free online tool called Visual Studio Code (with latest C# extension).
Blazor Code Snippet:

The above is a plain vanilla code that you get out of the box. It illustrates the use of C# and HTML. Although, when building an enterprise app, you would want to decouple your business logic in a separate class and restrict the razor component to HTML and CSS just to keep it clean and maintain a separation of concerns.

If you want to know more about Blazor, please use the following resources from Microsoft.

Resources:

Posted in UI Framework | Leave a comment

How to Call a UDF using ADO.NET

Let’s face it, most of us typically work with Stored Procedures with modest complexity using JOINS and such. Some of us embed Common Table Expressions (CTE) in the stored procs.

If you are already using Entity Framework 2.2, you would know that stored procedures containing multiple joins is not fully supported unless it’s a SQL View in which case you would have to use DbQuery type in your DbContext class.

But, what if you have a UDF (scalar-valued function) and want to use it with ADO.NET!

Let’s see how it’s done. For the purposes of demonstration, let’s assume you have two tables: Department and Employee. Department has a one-to-many relationship with Employee, i.e. A Department can have one or more employees. This is illustrated in the Entity Relationship Diagram (ERD) below:

 

 

 

 

 

 

 

 

 

 

Next, let’s write a simple User Defined Function (UDF) which accepts @DepartmentID as an input parameter and returns the Employee Name.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION udf_GetEmployeeByID
(
	-- Add the parameters for the function here
	@DepartmentId INT
)
RETURNS NVARCHAR(50)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @EmployeeName NVARCHAR(50)

	-- Add the T-SQL statements to compute the return value here
	SELECT @EmployeeName = TRIM(FirstName) + ',' + TRIM(LastName)  
	FROM 
		Employee 
	WHERE 
		DepartmentID = (SELECT DepartmentID 
						FROM Department 
						WHERE DepartmentID = @DepartmentId)

	-- Return the result of the function
	RETURN @EmployeeName

END
GO

As a quick test, let’s test this function in SQL Management Studio. We can see when the function is invoked, it returns the Employee Name which is precisely what we want.

 

 

 

 

 

 

Now, let’s open Visual Studio and create a console application and write the following method. There are a couple of things that are worth noting.

  • Since this is not a stored procedure, the command type is defined as “CommandType.Text”. If you change it to “CommandType.StoredProcedure”, the program will compile. However, it will return a null value.
  • When newing up a Sql Command object, you must use the SELECT clause when declaring the function name and passing the required parameter to it i.e. “SELECT dbo.udf_GetEmployeeByID(@DepartmentId)”
  • Don’t forget to bring in the System.Data.SqlClient namespace. You can use NuGet for this.
  • Lastly, when invoking the ExecuteScalar() command, be sure to cast it to a string (in our case).
private static string GetEmployeeNameByID(int DepID)
        {
            string retVal = string.Empty;
            using (SqlConnection connection = new SqlConnection(connStr))
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT dbo.udf_GetEmployeeByID(@DepartmentId)", connection))
                    {
                        connection.Open();
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@DepartmentID", DepID);
                        retVal = (string)cmd.ExecuteScalar();
                    }
                }
                catch (SqlException ex)
                {
                    ex.Message.ToString();
                }
                return retVal;
                
            }
        }

And now let’s put the code to test, by writing it out to a console.

static void Main(string[] args)
        {

            string name = GetEmployeeNameByID(1);
            Console.WriteLine(name);
            Console.ReadLine();
        }

Output:

 

 

 

Hope, you found this segment useful!

Posted in .NET, ADO.NET, SQL Server | Leave a comment

How to Enable .NET Core 3.0 Preview in VS2019

If you are in the process of creating a Blazor app in Visual Studio 2019 that you installed right after its launch (around April 2019 timeframe), chances are you’ll find the checkbox titled “Use previews of the .NET Core SDK” in the following location:

Tools -> Options -> Projects and Solutions -> .NET Core

However, if you’ve installed Visual Studio 2019 recently (as of this writing), the option has moved to the following location:

Tools -> Options -> Environment -> Preview Features.NET Core 3 Preview

 

 

 

 

Once the above is done, close Visual Studio IDE and open it again.

Now, Create a New Project and select ASP.NET Core Web Application template and hit ‘Next’, give a project name and hit ‘Next’ again and you’ll be presented with dialog with the option to select ASP.NET Core 3.0. Make sure you also select .NET Core on the LHS. This is a requirement for the successful creation of a Blazor app. (see image below).

 

Hope you found this post useful!

Obi

Posted in .NET | Leave a comment

Migrate SQL data to Azure Cosmos DB

Azure Cosmos DB

Azure Cosmos DB is a planet scale, JSON based schema free, No SQL database with multi-API support.

Microsoft defines it as a globally distributed, multi-model database service that supports document, key-value, wide-column and graph databases.

In this column, I’ll attempt to demonstrate what a cinch it is to import SQL data into Cosmos DB. Please note, the two are not the same. The analogy to describe the two is akin to a hammer vs. an axe. Just like you cannot use a hammer to chop down a tree, similarly, you cannot use an axe to drill a nail into the wall.

What do I need:

  • SQL Server Management Studio (SSMS)
  • Azure Cosmos DB Data Migration Tool
  •  Azure Cosmos DB Emulator

Azure Cosmos DB Data Migration Tool (DTUI)

DTUI is a data migration tool that is an open source solution used to import data to Azure Cosmos DB from a variety of sources that include the following:

  1.  JSON files
  2.  Mongo DB
  3.  SQL Server
  4.  CSV files
  5.  Azure Table Storage
  6.  Dynamo DB
  7.  HBase

Azure Cosmos DB Emulator

According to Microsoft docs, the Azure Cosmos Emulator provides a high-fidelity emulation of the Azure Cosmos DB service. It supports identical functionality as Azure Cosmos DB, including support for creating and querying data, provisioning and scaling containers, and executing stored procedures and triggers. You can develop and test applications using the Azure Cosmos Emulator, and deploy them to Azure at global scale by just making a single configuration change to the connection endpoint for Azure Cosmos DB.

To download and install the Azure Cosmos Emulator, you can use this link.

Migrating Data

To migrate SQL data, we would need data. For the purposes of demonstration, I am using Adventure Works database, a Microsoft sample database that you can download here.

The Process

Let’s open SSMS and use one of the Views. A typical View is created by joining multiple related tables together. The View that is being used in this example is Purchasing.vVendorWithAddresses, where Purchasing is the name of the schema.

This View contains information about Vendor with Addresses in each row such that each of these rows can be mapped to a self-contained JSON document once the migration completes. Notice the column names that are defined as aliases. There’s also a “.” which is used as a separator to split address into address type, city, location etc. In other words, this will help shape the JSON document to transform each row into a complex JSON document instead of a flat document containing simple properties.

Although the “.” is irrelevant to SQL, however, it is used to tell the migration tool how to shape the documents that are being imported.

SELECT        
	CAST(BusinessEntityID AS VARCHAR) AS [id], 
	[Name] AS [name],
	AddressType AS [address.addressType], 
	AddressLine1 AS [address.addressLine1], 
	AddressLine2 AS [address.addressLine2], 
	City AS [address.city], 
	StateProvinceName AS [address.location.stateProvinceName], 
	PostalCode AS [address.postalCode], 
	CountryRegionName AS [address.countryRegionName]
FROM            
	Purchasing.vVendorWithAddresses

The next thing you want to do is to open the Migration Tool utility and start configuring.

Source Info

Here you will specify the API to import from, i.e. connection string, query and the nesting separator. See image below:

Target Info

Use the Azure Cosmos DB Emulator to copy the connection string (circled in red above).

One of the things you ought to keep in mind when creating a container is to define its partition key. Typically, this is a property you choose that will help scale your data both in terms of storage and throughput.

In our case, we have chosen “/address/postalCode” as the partition key.

Note: It may be noted that the name of the column defined in SQL query is case-sensitive in order for it to be recognized when transforming the query results into Cosmos DB documents.

When you click Next, you’ll be presented with an Advanced tab. Skip this section by clicking Next. 

Now you will be on the Summary page where you can review all that you have configured in the previous steps. Once you are sure, click the Import button.

The tool will import the records and transform them to documents. In this case 104 of them. See below:

 

Now, let’s flip over to Azure Cosmos DB Emulator. Refresh the page and you’ll see the newly Created Database, Collection and Documents. See below:

 

Query the Data:

With the power of SQL API that Cosmos DB supports, you can query your data just as you would if you were in SSMS. See the query below:

Output:

 

 

 

 

 

 

 

 

 

 

Summary

Here, we saw the use of SQL API and how it can be used to model data as JSON documents. We made use of a view in SQL database, massaged it and transformed the SQL records into Cosmos DB documents following some easy steps.

Resources

  1.  Azure Cosmos DB
  2. Azure Cosmos DB Data Migration Tool

 

 

Posted in NoSQL | Leave a comment

Entity Framework Core 3.0 Preview 4

Diego Vega, the Program Manager of the Entity Framework team recently announced on his blog some of the breaking changes in ASP.NET Core 3.0 Preview 4.

Some of these changes include the following:

  • LINQ queries are no longer evaluated on the client
  • EF Core runtime no longer part of the ASP.NET Core shared framework. In other words, they have to be obtained via NuGet package
  • DotNet EF Tool is no longer part of the .NET Core SDK. It has to be downloaded separately
  • Automatic key generation (reset) after in-memory database is deleted
  • Database connection no longer remains open until a TransactionScope is disposed
  • The concept of query types has been renamed to entities without keys
  • New preview of the Cosmos DB provider for EF Core.  Some of the changes include the usage of deterministic appraoch to key generation and allowing developer to specify Azure region to us. Fantastic!!!
  • EF 6.3 to target .NET Standard 2.1, in addition to already supported .NET Framework versions.

 

Posted in ORM | Leave a comment