Skip to main content

4 posts tagged with "dotnet"

View All Tags

· 8 min read

Azure CosmosDB (Azure Cosmos DB – Globally Distributed Database Service (formerly DocumentDB) | Microsoft Azure) is a super set of the service once known as “Azure Document Db”. In short: “Azure CosmosDB ” = “Azure Document Db” + new data types + new APIs.

You can try CosmosDB  for free on Azure or you can setup the CosmosDB on your local environment by following my previous blog. I am becoming a fan of .NET Core with all the features and it is getting better day by day . In this blog post i just wanted to take that initial steps of how to work with CosmosDB from .NET Core Client context. After reading this blog, you should be able to do the following with CosmosDB programmatically,

  • Create Database
  • Create Collection
  • Create Documents
  • Query a Document
  • Delete Database

Pre-Requisities Needed:

I have the following in my local environment , hope you guys have already have😊, if not start setting up.

  • Windows 10 OS
  • Azure CosmosDB Emulator
  • Visual Studio Code editor with C# plugin
  • .NET Core 2.0

Ok folks, lets get started.

Step 1: Create .Net Core Console Application :  As other tutorials, to make it simple I will be creating a dotnetcore console app to work with CosmosDB . With Net Core , we now  have a CLI. Lets create the new app with the following steps. (I’ve mentioned in the previous blog)

  1. Open command prompt or poweshell (Administrator Mode)
  2. Navigate to your folder where you need to create the app
  3. Execute the following command
dotnet new console -n CosmosCoreClient -o CosmosCoreClient

here -n denotes the name of the application, and -o tells the CLI to create a folder with that name and create the application inside the folder

Open the newly created project in Visual Studio Code. Execute the following command

Code.

Here is a screenshot of how it should look on your end:

I am using C# 7.1 feature to create a async Main method in my console app. For that, we will need to make a small change in our project file a little. Open CosmosDBClient.csproj file to edit. Add the following XML node to PropertyGroup node.

<LangVersion>latest</LangVersion>

After changes, your csproj file should look like below:

Lets move to the core part of integrating CosmosDB with .netCore application and start building the features.

Step 2: Add CosmosDB Nuget Package

If you have followed the above steps, we have successfully created the application, next is to add reference to CosmosDB nuget package to get the client libraries. Advantage of these packages/libraries are, they make it easy to work with Cosmosdb.

  1. Open a command prompt and navigate to root of your project.
  2. Execute the following command
dotnet add package Microsoft.Azure.DocumentDB.Core

You might wonder the namespace has DocumentDB in it. In fact DocumetDB is where the whole journey started and hence the name sticks in Cosmos world too. If you now look at the project file a new reference for DocumentDB would have been added. Here is the screenshot of my project file.

Step 3: Creating Model for CosmosDB

Lets build the database. If you are new to CosmosDB you should know that CosmosDB has a query playground here https://www.documentdb.com/sql/demo. It is a sandboxed environment with couple of databases and you can try around with different queries you can write against the database. For this post, lets create the database named Course locally.

Since we our application is to deal with the Courses we need 4 Models here.

  1. Course
  2. Session
  3. Teacher
  4. Student

Here are the Models of the above 4.

Course.cs

using Microsoft.Azure.Documents;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class Course : Document
{
[JsonProperty(PropertyName = "CourseId")]
public Guid CourseId { get; set; }

[JsonProperty(PropertyName = "Name")]
public string Name
{
get
{
return GetPropertyValue<string>("Name");
}
set
{
SetPropertyValue("Name", value);
}
}

[JsonProperty(PropertyName = "Sessions")]
public List<Session> Sessions { get; set; }

[JsonProperty(PropertyName = "Teacher")]
public Teacher Teacher { get; set; }

[JsonProperty(PropertyName = "Students")]
public List<Student> Students { get; set; }
}

Session.cs

using System;

public class Session
{
public Guid SessionId { get; set; }

public string Name { get; set; }

public int MaterialsCount { get; set; }
}

Teacher.cs

using System;

public class Teacher
{
public Guid TeacherId { get; set; }

public string FullName { get; set; }

public int Age { get; set; }
}

Student.cs

using System;

public class Student
{
public Guid StudentId { get; set; }
public string FullName { get; set; }

}

Lets create the Client as the next step.

Step 4: Creating the Client

Next step you will need to instantiate the CosmosDb client before we do anything with the database. In order to connect to the local instance of the cosmosDb, we need to configure 2 things,

  1. URL of the CosmosDb instane
  2. Authentication key needed to authenticate.

As stated above, When you start the CosmosDb  local emulator, the db instance is available at https://localhost:8081. The authkey for local emulator is a static key and you can find it here in this article(https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator#authenticating-requests). This key works only with the local emulator and wont work with your Azure instance, you can find the key if you are using azure instance from the portal as mentioned in the answer. Here is the code snippet to instantiate the client:

        static string endpointUri = "https://localhost:8081";
static string authKey = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
string dbName = "CourseDB";
string collectionName = "Courses";
static void Main(string[] args)
{
Console.WriteLine("Press any key to run");
Console.ReadLine();

Run();

Console.ReadLine();

}
private static async void Run()
{
DocumentClient documentClient = new DocumentClient(new Uri(endpointUri),
authKey);
}

When the method Run is exectued the Client is instantiated with the local CosmosDB emulator.

Step 5: Lets start building the features

Next step is to build the features as listed above. Lets add the methods inside the Async method.

Creating Database:

To create a new database programmatically, we make use of CreateDatabaseAsync() or CreateDatabaseIfNotExistsAsync(). When creating the database we pass the database name. Here is the code snippet:

private static async Task<Database> CreateDatabase(DocumentClient documentClient)
{
Database database = documentClient.CreateDatabaseQuery().Where(c => c.Id == "courseDatabase").AsEnumerable().FirstOrDefault();
if (database == null)
{
database = await documentClient.CreateDatabaseAsync(new Database()
{
Id = "courseDatabase"
});
}
return database;
}

When you refresh the URL of local CosmosDB emulator, You should see the database created in your local db emulator as follows,

Creating Collection:

Once the database is created, we can then create a collection. We make use of CreateDocumentCollectionAsync() or CreateDocumentCollectionIfNotExistsAsync().

We will need to provide what is known as the database link (basically the URI at which the db can be reached) and the collection name to the create method. Here is the code snippet.

private static async Task<DocumentCollection> CreateDocumentCollection(DocumentClient documentClient, Database database)

{
DocumentCollection documentCollection = documentClient.CreateDocumentCollectionQuery(database.CollectionsLink).Where(c => c.Id == "courseDocumentCollection").AsEnumerable().FirstOrDefault();

if (documentCollection == null)
{
documentCollection = await documentClient.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection()
{
Id = "courseDocumentCollection"
});
}

return documentCollection;
}

Now you should the the Collection for Course is created as follows,

Creating Document :  After creating the database and collection, we can now create the documents. We make use of CreateDocumentAsync() for this purpose. We will need to pass the URI of the collection under which we want to create the document and the document data itself. In this example we make use of the Course data mode i showed earlier and pass it to the create method. Here is the code snippet:

private static async Task CreateCourse(DocumentClient documentClient, DocumentCollection documentCollection)
{
Course course = new Course()
{
CourseId = Guid.NewGuid(),
Name = "En",
Teacher = new Teacher()
{
TeacherId = Guid.NewGuid(),
FullName = "Scott Hanselman",
Age = 44
},
Students = new List<Student>()
{
new Student(){
FullName = "Trump",
StudentId = Guid.NewGuid()
}
},
Sessions = new List<Session>(){
new Session(){
SessionId = Guid.NewGuid(),
Name = "CosmosDB",
MaterialsCount = 10
},
new Session(){
SessionId = Guid.NewGuid(),
Name = "Ch1",
MaterialsCount = 3
}
}
};
Document document = await documentClient.CreateDocumentAsync(documentCollection.DocumentsLink, course);
}

You should see the document inserted in localdb Emulator as follows.

Querying Document:

Now that we have created a document, we can see how to query it. We can make use of CreateDocumentQuery() method for this purpose. We will need to pass the collection link on which we need to query. We can then build the query as a LINQ expression and the client library does the rest. This is the best part of the client library. It has the ability to translate your LINQ expression to cosmos REST URIs without me having to crack my head in constructing those URIs. Here is the code snippet:

private Course QueryCourse(Guid guid, String dbName, DocumentClient documentClient, string collectionName)
{
Course selectedCourse = documentClient.CreateDocumentQuery<Course>(
UriFactory.CreateDocumentCollectionUri(dbName, collectionName))
.Where(v => v.Name == "CosmosDB")
.AsEnumerable()
.FirstOrDefault();
return selectedCourse;
}

Note that you will need to import System.Linq for the LINQ expression to work.

Deleting Database:

Finally, we can make use of DeleteDatabaseAsync() method to delete the database programmatically. We will need to provide the database link to the delete method. We can use the UriFactory.CreateDatabaseUri() helper method to create the database link. Here is the code snippet:

await documentClient.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(dbName));

Well, those are the main features that Azure CosmosDB client provides and if you are stuck with any of the steps above , you can check out the repository i have added with the samples.

Happy Coding! Lets spread Azure's CosmosDB to the world.

· 2 min read

In this blog i will start with an introduction to .NET Core CLI tools with an example of how to create a web API using the CLI tools provided with .NET Core. At the end we will set up a solution grouping an API project and a test project. Let's dive into the steps,

Step 1 :  Installing the tools

Need to install .NET Core and Visual Studio Code that are supported on Mac, Unix and Windows. You can read more on how it works on multi-platform/framework.

Step 2 :  Creating the solution

Let's open the terminal/Powershell as a administrator to create our solution. Lets create a solution named DotNetCoreDemoApi

  dotnet new sln -o DotNetCoreDemoApi  

The above command will create a new folder and DotNetCoreDemoApi a solution file with the  name DotNetCoreDemoApi sln .

Lets get into that folder.

Step 3: Creating the web API project

Run the following command,

 cd DotNetCoreDemoApi 

Now that the solution is here, we can create our API project. Lets name the web API as DotNetCoreDemoApi. Run the following command to create the project.

dotnet new webapi -o DotNetCoreDemoApi  

That command will create a sub folder named DotNetCoreDemoApi  inside the solution DotNetCoreDemoApi and the ouput is as follows.

The web API folder should contain a few files generated as above  but what we require right now is DotNetCoreDemoApi.csproj. We will add a reference to it in our solution. To do so, run the following command:

 dotnet sln add ./DotNetCoreDemoApi/DotNetCoreDemoApi.csproj

 

 

Step 4: Run the Web API After getting a confirmation message as above , lets start the API by running that command:

 dotnet run --project DotNetCoreDemoApi  

 

After a few seconds, it should display a message  that the API is now running locally as above. You may access it at http://localhost:5000/api/values which is the Values API default endpoint.

That's all , API is ready and it is up and running locally. I will continue setting up the TestProject in the same solution in the upcoming blog. With the DotNet core it is very feasible to get your web api setup and running in 5 minutes.

· 4 min read

This is my first blog and Azure and i am inspired to write this one after attending the Microsoft's workshop "App innovation day".There was a cool technology "Windows Workflow Foundation" provided by Microsoft with dot net framework to create workflows to cater business logic in dot net applications. With Azure, The Logic Apps service fulfill the purpose to have business processes or workflows take shape of an app.

It required no coding just simple logic that needs to placed in a right way to have right business flow. It was also meant for the purpose of integrating 3rd party apps like Facebook,YouTube, Twitter and Evernote etc. All we need to have is the dynamic work flow.There are different benefits and different use cases in which we can apply azure logic apps. Let's discuss some of the benefits when using logic apps!

Rapid development

Logic Apps is great for rapid development.With ever growing list of connectors, we can easily create a workflow to monitor invoice, send for approval to a admin, upload to dropbox and send email notification in matter of few seconds.

Solutions with Hybrid cloud

5 years back ,Lot of businesses have invested heavily in on premises solutions and hardware, so it’s not possible to move everything to the cloud. With Logic Apps, it’s easy to have a hybrid cloud during this transition. With its on premises data gateway, you can easily connect your on premises database, file share, BizTalk server to Azure cloud.

It is the new way of Automating business process. You can build long running business process, that orchestrate data and services across all cloud services and not just Azure. It's not only for the developers but for everyone. The best bit you need to write code , you can use Visual editor to build your orchestration.

Lets Dive into Simple Demo Use Case: Filter twitter feeds with specific hashtags and post the specific tweets on the Facebook wall. In this example , i just created a process that repeats every few minutes to pull some data from twitter feed and post it on your Facebook wall. Even though this feature is already supported with Facebook, here its slightly different since it is filtering only the specific keywords which is a custom filtering.

The entire flow i described about is composted of 3 simple steps , that you can build using a Visual UI.

Step 1: Select Logic App click "Create" and give a specific name ,resource 

 

 Step 2: There are number of workflow templates will be shown as below and select the appropriate one , in this case i will use "when a new tweet is posted"

also authorize with your twitter account from which you want to fetch the feeds

Also configure the conditions by mentioning the filters and the timeline you want to trigger the action.

 

Step 3: Next step is to post on facebook wall , click "Add step"  

Search for Facebook and authenticate will your Facebook account as follows,

Click post to my timeline

Also you can map the fields that you want to fetch from the feed and post it on the wall as below,

 

That's it folks, once all fields are mapped you need to save the Logic app with the save button.

With the above 3 steps posting a filtered tweet on Facebook wall is configured and can be scheduled as you need. If the above particular feature needs to be developed without azure means it will need a huge development time and cost, which can be avoided using the Logic app as shown above.

That's the demo. You can explore several steps and several templates provided in the portal without writing a single line of code. I will be writing a separate blog on how to configure custom logic app in the upcoming blog posts. Happy connecting with app logic!

· 2 min read

I've been a .Net developer since the beta days of .Net 3.0, Now i find myself doing less and less coding related with .Net related stuffs. However, the new strategy from Microsoft  encouraged all the developers including me to once again start doing some .Net work from time to time. One of the highlighting tool among them was the Visual Studio Code.

Sublime text has been my favorite text editor all these time.When i downloaded it and looked at the first time my impression was nothing more than a plain editor with very little added value. Before VS code I have tried all popular editors - Sublime, Atom, Brackets etc. After trying it for few weeks now I feel developers  have everything they need .

Some of the highlights of VS Code are as follows,

  • Default integrated git system is really awesome.
  • Powerful debugging option.
  • Very smart code completion.
  • Huge list of Languages Support
  • Multi panel for side by side editing
  • Always-On IntelliSense
  • Debugging support
  • Peek Information like grammer correction
  • Command Palette

Choice of editor is a personal preference. If you like an lightweight IDE environment that's cross platform, you might enjoy VS Code. Give it a try, you will definitely love it.