ErrorCode = ‘0x80004005 : 80008083: .Net Core 2.0 + IIS exception

We all know that .Net Core has been announced so people started implementing with .Net core.

One exception which people are getting while frequently while deploying .Net Core application(created by Visual Studio 2017) on IIS is as below:

Application ‘<IIS path>’ with physical root ‘<Application path>’ failed to start process with commandline ‘”dotnet” .\MyApp.dll’, ErrorCode = ‘0x80004005 : 80008083.

Reason of the exception?

This exception comes when runtime required is not deployed on the server and web application was lately moved to Visual Studio 2017. Because VS2017 RC is shipped with the new version of .NET Core SDK and your server has some other .net version than Core.

Meaning of error code:

  • 0x80008083 – code for version conflict.
  • 0x80004005 – file is missing or cannot be accessed

So the error means a different version of dotnet needs to be installed on the server.

Solution:

.Net Core 1.0 needs to be installed on the server.

Steps are as below:

  • Stop IIS
  • Install .Net core 1.0 on the server which you can find here.
  • Start IIS again

Above error will not come after this.

Note:

I have explained for .Net Core 1.0 but it depends on the version. For example, if you are deploying .Net Core 2.0 then need to install the sdk accordingly.

Hope it helps.

 

 

Advertisements

Microsoft Cognitive Services for AI : Vision API

microsoft-cognitive

Recently I took part into a Hackathon in which we were required to submit some innovative ideas for a well-known bank.

I registered and after few days I got an email from the Hackathon event team that they have arranged some webinars to help people to think about some innovative ideas.

I got impressed with the agenda of the webinar which included below points:

  • Microsoft Vision API
  • Microsoft Speech API
  • Microsoft Language API
  • Microsoft Knowledge API
  • Microsoft Search API

This was the first time I got to know about Microsoft Cognitive Services and when I learned more about this, I got to know that Microsoft Cognitive Services are very powerful.

Let us first see what is Microsoft Cognitive Services?

Microsoft Cognitive Services (formerly Project Oxford) are a set of APIs, SDKs and services available to developers to make their applications more intelligent, engaging and discoverable. Microsoft Cognitive Services expands on Microsoft’s evolving portfolio of machine learning APIs and enables developers to easily add intelligent features – such as emotion and video detection; facial, speech and vision recognition; and speech and language understanding – into their applications. Our vision is for more personal computing experiences and enhanced productivity aided by systems that increasingly can see, hear, speak, understand and even begin to reason.

It has basically 5 main features:

  • Vision
  • Knowledge
  • Language
  • Search
  • Speech

ai1

Let us see how Vision API works

Follow below steps which are required:

Also if you want to have Bot Application as a template then as a workaround just download this project and put the extracted folder into below location:

C:\Users\YourName\Documents\Visual Studio 2015\Templates\ProjectTemplates\Visual C#

Once this is done, you can see Bot Application template as shown below:

ai2

Click on Bot Application and then it will create a sample project which has the structure as below:

ai3

Here MessagesController is created by default and it is the main entry point of the application.

MessagesController will call the service which will handle the interaction with the Microsoft APIs. Replace the code into MessagesController with below code:

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.Bot.Connector;
using Newtonsoft.Json;
using NeelTestApplication.Vision;

namespace NeelTestApplication
{
    [BotAuthentication]
    public class MessagesController : ApiController
    {
        public IImageRecognition imageRecognition;

        public MessagesController()  {
            imageRecognition = new IImageRecognition();
        }

        ///
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        ///
        public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {

            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            if (activity.Type == ActivityTypes.Message)
            {

                var analysisResult =await imageRecognition.AnalizeImage(activity);
                Activity reply = activity.CreateReply("Did you upload an image? I'm more of a visual person. " +
                                      "Try sending me an image or an image url"); //default reply

                if (analysisResult != null)
                {
                    string imageCaption = analysisResult.Description.Captions[0].Text;
                    reply = activity.CreateReply("I think it's " + imageCaption);
                }
                await connector.Conversations.ReplyToActivityAsync(reply);
                return new HttpResponseMessage(HttpStatusCode.Accepted);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }

        private Activity HandleSystemMessage(Activity message)
        {

            if (message.Type == ActivityTypes.DeleteUserData)
            {
                // Implement user deletion here
                // If we handle user deletion, return a real message
            }
            else if (message.Type == ActivityTypes.ConversationUpdate)
            {
                // Handle conversation state changes, like members being added and removed
                // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
                // Not available in all channels
            }
            else if (message.Type == ActivityTypes.ContactRelationUpdate)
            {
                // Handle add/remove from contact lists
                // Activity.From + Activity.Action represent what happened
            }
            else if (message.Type == ActivityTypes.Typing)
            {
                // Handle knowing tha the user is typing
            }
            else if (message.Type == ActivityTypes.Ping)
            {
            }

            return null;
        }
    }
}

In above code, you can find an interface called IImageRecognition. This interface includes the methods which will interact with the Microsoft APIs.

So now we will add an interface IImageRecognition and replace the code with below code:

using Microsoft.Bot.Connector;
using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
using System.Threading.Tasks;

namespace NeelTestApplication.Vision
{
    public interface IImageRecognition
    {
        Task<AnalysisResult> AnalizeImage(Activity activity);    
    }
}

Once this is done, let us add ImageRecognition class which will inherit from IImageRecognition:

using Microsoft.Bot.Connector;
using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace NeelTestApplication.Vision
{
    public class ImageRecognition : IImageRecognition
    {
        private   VisualFeature[] visualFeatures = new VisualFeature[] {
                                        VisualFeature.Adult, //recognize adult content
                                        VisualFeature.Categories, //recognize image features
                                        VisualFeature.Description //generate image caption
                                        };

        private VisionServiceClient visionClient = new VisionServiceClient(" https://www.microsoft.com/cognitive-services/en-us/sign-up");

        public async Task<AnalysisResult> AnalizeImage(Activity activity)  {
            //If the user uploaded an image, read it, and send it to the Vision API
            if (activity.Attachments.Any() && activity.Attachments.First().ContentType.Contains("image"))
            {
                //stores image url (parsed from attachment or message)
                string uploadedImageUrl = activity.Attachments.First().ContentUrl; ;
                uploadedImageUrl = HttpUtility.UrlDecode(uploadedImageUrl.Substring(uploadedImageUrl.IndexOf("file=") + 5));

                using (Stream imageFileStream = File.OpenRead(uploadedImageUrl))
                {
                    try
                    {
                        return  await this.visionClient.AnalyzeImageAsync(imageFileStream, visualFeatures);
                    }
                    catch (Exception e)
                    {
                           return null; //on error, reset analysis result to null
                    }
                }
            }
            //Else, if the user did not upload an image, determine if the message contains a url, and send it to the Vision API
            else
            {
                try
                {
                   return await visionClient.AnalyzeImageAsync(activity.Text, visualFeatures);
                }
                catch (Exception e)
                {
                   return null; //on error, reset analysis result to null
                }
            }
        }
    }
}

Note that you will be required to add an API key which you can get from the Cognitive Service page of Azure here.

ImageRecognition class has an important method named AnalizeImage which basically reads the image from the location and transfers it into the stream. Then it calls below API method and passes the image stream:

this.visionClient.AnalyzeImageAsync(imageFileStream, visualFeatures);

Above method will return AnalysisResult which can be extracted as below:

var imageCaption = analysisResult.Description.Captions[0].Text

So basically Image caption is the text it will return after analyzing the image.

Let us try this out.

If we want to test our bots locally then Bot emulator is the best option.

The Bot Framework Emulator is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.

As we mentioned on top of the post, you can download the Bot emulator from here.

The only important thing it requires is the URL of your API. For example in our case it would be:

http://localhost:PortNumber/api/messages

Now when we upload the image on Bot emulator, it will give the result as below:

ai4

It is awesome. Hope it helps.

C# 7.0 feature Part I : Pattern matching

pattern

In this series of posts, I will explain the new features of C# 7.0

Let us see the Pattern Matching feature in the current post.

There are currently 2 existing language constructs which has been enhanced with patterns by Microsoft team:

  1. with the keyword is
  2. With Switch case

Before starting let us see some advantages of Pattern matching:

  • To match patterns on any data type, even on custom data types
  • Built-in pattern matching
  • Pattern matching can extract values from your expression

Okay so let us see the switch case first.

Assume we have a class called Customer which has been implemented by 2 classes, Agent and DirectCosumer as shown below:

 class Customer
 {
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
 }

 class Agent : Customer
 {}

class DirectConsumer : Customer
 {}

With C# 7.0 pattern matching feature, we can:

  • write additional conditions in case statements
  • switch on any type
  • use patterns in case statement

So we can write switch case statements as below:

 switch(customer)
 {
   case Agent a when (a.CustomerId == 11):
   Console.WriteLine($"Customer is an agent and Name: {a.Name}");
   break;

   case DirectConsumer b when ((b.CustomerId == 21) & (b.City == "Pune"):
   Console.WriteLine($"Customer is a consumer(Pune location) and Name: {b.Name}");
   break;

   default:
   Console.WriteLine("Customer Not found");
   break;

   case Null:
   throw new ArgumentNullException(nameof(shape));
 }

There are few points which are very important:

  • Now the sequence of the case statement matters as the first which satisfies the condition will be processed just like catch clauses
  • Even though you put default first before null case, it will first check whether it fits with null and if it does not then only it goes for default case so default will be executed at the last
  • If customer object is null, processing will fall into the Null case, even if it is an Agent or DirectConsumer null instance

Now let us see keyword is:

You might be wondering that is keyword is there in C# since the beginning then why it is called as a new feature?

Well till now we could use is keyword either to check if a specified interface is implemented, or if the type of the object derives from a base class.

From C# 7.0 onwards, we can use is with:

  • Type pattern:

With type pattern, we can check whether the object is compatible or not:

  1. if (a is Agent p) Console.WriteLine($"it's an agent: {p.Name}");
  2. if (d is DirectConsumer b && (b.City == "Pune")) Console.WriteLine($"it's a direct cosumer lives in {b.City}");
  • Const pattern:

It can be used to verify any constant numbers or Null:

  1. if (a is null) throw new ArgumentNullException(nameof(a));
  2. if (a is 10) Console.WriteLine("it is 10");

 

Let us take some example to check whether the object is a string:

object obj = "Hello, World!";
if (obj is string str)
{
 Console.WriteLine(str);
}
One more example where we want to check whether an object is equal to some constants:
object obj = 1; 

if (obj is 1)
{
  Console.WriteLine(true);
}

Hope it helps 🙂

 

 

 

C# 8.0 Expected Features Part – II : Implementation of method in the Interface

C8

In my previous post, I have explained about one of the first four features of C# 8.0 which has been announced by Microsoft recently.

In this post, I will explain one more future feature which is Default Interface Methods.

This feature will allow interfaces to fully define methods just like abstract classes. However,  interfaces will still not be able to declare constructors or fields.

Let us see what it is:

Let us take one example of an interface, like IMessage and it has one method named Message as shown below:

interface IMessage {
   void Message();
}

And a class will implement it as below:

Class Test : IMessage
{
}

Now imagine we want to add a new method to the interface, it will result in lots of errors in all the classes which have inherited IMessage interface.

Here comes the new feature which changes some basic functionalities of C# language.

We will create a method with the implementation in the interface. Yes, you read it right, we will be able to write the implementation of the method into the interface as below:

interface IMessage {
    void Message();

    void MessageAll(IEnumberable<MyClass> myClass){ 
       foreach(var i in myClass)
       {
              //// Your code
       }
   }
}

So no need to write newly added method into all the classes which inherit IMessage interface.

It is cool, isn’t it?

One basic question would come in the mind is, what is the difference between this and the abstract class?

They are bit similar but there are some major differences.

One of the difference is:

  • The interface can be used for multiple inheritances but Abstract class can not be used
  • Interfaces will still not be able to declare constructors or fields.

Some useful points for Default Methods feature:

  • “Full abstraction” where we used to have plain interfaces and all classes were forced to have its own implementation. Now we are polluting classes with some default implementation for methods which they don’t even know those exist.
  • It also breaks interface segregation principle, if we have to change an interface in future and it should not break all the classes but some of the classes need to have the new method added means, the interface is not granular enough and it’s time to introduce new interface and implement for the required classes.

Java announced almost similar feature with 8.0 version earlier and it is becoming so famous among Java developers and it will soon become famous between .Net developers as well 🙂

 

Step by step installation of .Net Core 2.0

core26

In my previous post, I have explained how to set up for .Net Core 2.0 which you can find here.

But in that post, it mainly focuses on how to do the setup if you already have .Net Core. So in this post, I will explain how to install .Net core 2.0(Without having Core 1.0) on your machine.

First of all, you need to install .Net Core 2.0 sdk from here.

Once you double click on the exe, it will start the process as below:

core21

Once the process is done, it will show below window:

core22

Once this is done, Open Visual Studio command prompt as below and run the command:

dotnet new console -o console-app

core23

It shows that .Net Core 2.0 has been installed on your machine. For more information, you can go through the documents by clicking on the links shown in the console.

Now we will run a console application from the command prompt.

One sample application is already provided which resides on below path(It may change):

C:\Windows\System32\console-app

Now run the command:

dotnet run

core25

Which will return “Hello World”, it shows your installation is successful.

You can even run below command to verify the version:

dotnet –version

It should return 2.0

You can open this sample project on Visual Studio 2017.

To Create new Core 2.0 project, you need to select the version in the drop down as shown below:

core27

 

 

 

 

 

Razor pages compilation on Publish: Now default with .Net Core 2.0

core5

.Net Core 2.0 is announced last week and it came up with some awesome features.

I am going to explain its one of the best features which is the compilation of views and pages on Publish.

Till now(before .Net core 2.0) whenever we publish any MVC application, Razor files are published as .cshtml files and they get compiled at runtime.

Which means:

  • It takes a bit more time just to compile all those cshtml files
  • Publish output size increases

.Net Core 2.0 has one inbuilt functionality which compiles page and views on publish.

It means:

  • Our Razor pages and views would get published with our app as a compiled assembly instead of being published as .cshtml source files that get compiled at runtime

So it has advantages as:

  • Reduces application startup time
  • Reduces Publish output size

So the conclusion is, our .Net Core 2.0 applications are faster than the older applications.

Please note that we can disable this feature if we do not require this.

It can be done by simply updating below property in csproj file:

<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>

Have a look here if you require more details.

 

C# 8.0 expected features Part – I

c#8

We all know that Microsoft always delivers awesome features in all the releases and they are already planning for the features of C# 8.0

As per a video on Channel 9, Mads Torgersen has explained about the possible features of C# 8.0

There are possibly 4 features till now which are as below:

  • Nullable reference types
  • Async Streams(Foreach Async)
  • Default Interface Implementations
  • Extension Everything

In this post, I will explain about the Async Streams.

For normal Async methods we write it as below:

async Task(int) Test()
{
    return x;
}

and we call it by:

await Test();

What it does is, it waits until the things returned from Test method and after that only, it goes to the next step.

But it works with only one resource.

Now imagine we want to work with some live stream where we get data in the continuous live stream. For example, some IoT where data comes every moment. But we want to process them in our own time like one at a time.

Here comes the Async version of IEnumerable:

IAsyncEnumerable<T>

So basically, it is just like an enumerable except that when you move next in an enumerable way, that is Async.

It is kind of a way of Lay loading enumerability in Async way.

When defining an async iterator, you would use this function signature:

async IAsyncEnumerable<string> MethodName()
{
   yield return "Test";
}

And can be used as:

foreach await (string s in asyncStream)

Above is nothing but the combination of Async and Enumerable, you wait inside it and you return inside it.

Though it looks like IObersable but it is different. The benefit of using this instead of IObservable<T> from Reactive Extensions is that the consumer controls the flow rate. This is referred to as a “pull model” and IObservable<T> is a “push model”.

In Foreach Async, consumers tell when it is ready and then it processes the next one.

I hope you liked this future feature of C#.