Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, 18 September 2020

Convert C# Object to JSON string

Hi Everyone,

Check this post for Convert JSON object to C# Object.

Here is the easy way to convert C# to JSON String without using external references.

[DataContract]
        public class MyClass
        {
            [DataMember]
            public string Firstname { get; set; }
            [DataMember]
            public string Lastname { get; set; }
        }

        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.Firstname = "Dynamcis 365";
            myClass.Lastname = "Customer Engagement";

            var memoryStream = new MemoryStream();
            var serializer = new DataContractJsonSerializer(typeof(MyClass));
            serializer.WriteObject(memoryStream, myClass);
            memoryStream.Position = 0;
            StreamReader streamReader = new StreamReader(memoryStream);
            string objectInJSONString = streamReader.ReadToEnd();

            Console.Write(objectInJSONString);
            Console.Read();

        }

You have to add below references from .net framework to your project.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json; 

Hope this helps.

--
Happy Coding
Gopinath

Monday, 31 August 2020

Convert JSON to Object using C# Code

Hi Everyone,

Many times we get a requirement to convert JSON string to C# Object and most of the times, we go with Newtonsoft Dll. In Dynamics 365 Plugins, we all know it is not recommended to use Newtonsoft as we have to use ILMerge to merge the dlls and deploy.

Here is the easy way to convert JSON string to C# object without using external references.

You have to add below references from .net framework to your project.

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

        [DataContract]
        public class MyClass
        {  
            [DataMember]
            public string Firstname { get; set; }
            [DataMember]
            public string Lastname { get; set; }
        }

        static void Main(string[] args)
        {
            // string strJSONstring = Console.ReadLine();
            string strJSON = "{\"Firstname\":\"Dynamics 365\", \"Lastname\":\"Customer Engagement\"}";
            MyClass objMyClass = null;
            using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(strJSON)))
            {
                DataContractJsonSerializer deSerializer = new DataContractJsonSerializer(typeof(MyClass));
                objMyClass = (MyClass)deSerializer.ReadObject(stream);
            }
        }

Hope this helps.

--
Happy Coding
Gopinath.

Wednesday, 17 June 2020

Cool feature in Visual Studio - Generate Class from JSON or XML

Hi Everyone,

Today I was asked a question by one of my friends on if I know any easy way which can generate C# Class if we give JSON as an input. And I don't know anyway but certainly there should be an easy way to do the same.

To my surprise, it turned to be a very easy one. Visual Studio has cool feature, copy JSON or XML to the clipboard  --> Open any class file  --> Edit --> Paste Special.

Hope this helps.

--
Happy Coding
Gopinath

Wednesday, 22 May 2019

Logging in Azure Web APP

Hi,

Today I was developing an Web APP and it was giving an error after I host it on Azure. To understand the error I have log the traces. Here is the way that explains that how we can do that.

We can directly use Trace class (System.Diagnostics.Trace) for write the logs. I have written the below piece of the code as a first line in the method.


System.Diagnostics.Trace.WriteLine("I am getting called...");

Now navigate to your Azure Account --> The app service where you have deployed the Web APP --> Diagnostics Logs.


You have something called "Application Logging (Filesystem)" and you can switch it on. There are four options available there.

Error - Error, Critical
Warning - Warning, Error, Critical
Information - Info, Warning, Error, Critical
Verbose - Trace, Debug, Info, Warning, Error, Critical (all categories)

I normally prefer Verbose as it gives everything.

Now, browse the URL for hitting the action where you have written the tracing.

Navigate to Advance Tools under you AppService and Click on Go


It opens a new tab as below - Click on Debug console and then CMD.


You will see the below screen, click on LogFiles --> Application, you will see the .txt file. Click on Edit icon to see the logs.


Note : For Application logging, you can turn on the file system option temporarily for debugging purposes. This option turns off automatically in 12 hours

--
Happy Coding
Gopinath

Monday, 20 May 2019

Multiple actions were found that match the request

Hi,

I had written a new HTTPGet method and it worked well. After sometime, I got a requirement to write one more new HTTPGet method and I had troubles. The code started failing by throwing the below error.

"Multiple actions were found that match the request"

After some search I was able to identify the issue as we have to specify which action(method) we need send your HTTP request. For fixing it, we have to add routes in the WebApiConfig in the below order. The order plays important rule here. 

        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
            name: "ControllerAndActionOnly",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { },
            constraints: new { action = @"^[a-zA-Z]+([\s][a-zA-Z]+)*$" });

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        }

Hope this helps.

--
Happy Coding
Gopinath

The return type of an async method must be void, Task or Task

Hi,

Today I was working on the some work related to KeyVault and I have written async method. The code was error as below. 

"The return type of an async method must be void, Task or Task<T>"



I tried internet and not able to get any answer for it and I was so worried :( as I was not able to understand the issue. It was in the early morning with half sleep I tried this and I thought, this needs some deep understanding and went for a coffee.

After sometime, I just opened the laptop and understood that I didn't the System.Threaing.Tasks namespace in the class file and it fixed the issue.

Moral - You need to take a small break when things are not working and start again if something is failing. Coffee helps :)

Hope this helps.

--
Happy Coding
Gopinath

Tuesday, 16 April 2019

The underlying connection was closed an unexpected error occurred on a send

Hi,

Today I was working on calling some external url via C# code using HttpRequest and I was continuously getting the below error.

The underlying connection was closed an unexpected error occurred on a send.

There could be multiple reasons for this but adding the below line before sending the request helped to fix the issue.


ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

Hope this helps.

--
Happy Coding
Gopinath

Tuesday, 27 September 2016

“The type or namespace name 'Route' could not be found” using attribute routing”

Hi,

I was working on Web Api and I gave all the references and I am getting an error saying

“The type or namespace name 'Route' could not be found” using attribute routing”

I downloaded the solution from TFS and using Nuget, it seems that there is a problem in the referencing of assemblies.

Executed the below command in the Package Console and things started working.

Update-Package Microsoft.AspNet.WebApi.WebHost -reinstall

Hope this helps.
--
Happy Coding
Gopinath

Thursday, 16 June 2016

Class Vs Interface in C#

Hi,

We all hear Class and Interface words through our IT Career. Here are some important notes about.
An Interface is a Contract - We specify methods and properties in it and a class implements it. Interface doesn't have any implementations.

In a very simple words we can say Interfaces are used to enforce certain Methods/Properties. In a nutshell- an interface is a set of rules. Using the interface clearly states my intent to only use members of the interface. A class can be used to inherit/override base functionality.

For example, an Animal is a class of living things, and a Lion is a class of animals. Inheritance expresses this relationship: an Lion is an Animal where Giraffe inherits from Animal. It can do anything an animal can do and more.

We cannot create an instance of Interface. The only way to "Create an instance of a interface in c#" is to create an instance of a type implementing the interface. The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.

Here is the small example

We can call DoSomeThing using objClass1 or objClass2 objects like below.
Complete Program

Output

I would prefer to write the same code like below. We can pass Interface as a type like below
Depending the object you pass you get the different behavior.
In the above example, ThisMethodShowsHowItWorks the parameter it expects is of type IIamInterface. This can take anything that implements the variable.

Hope this helps.
--
Happy Coding
Gopinath

Tuesday, 31 May 2016

Get the list of all properties of a class in C#

Hi,

Today we got a requirement to get the list of all the properties of a class including the values.

Here is a C# code for it.

class Customer
{
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string MiddleName { get; set; }
}

class Program
{
     static void Main(string[] args)
     {
         // Creating an object for a class
         Customer objCustomer = new Customer();
         objCustomer.FirstName = "John";
         objCustomer.LastName = "Hung";
         objCustomer.MiddleName = "Maro";

         // Reading the properties and displaying the Name and Value.
         foreach (var prop in objCustomer.GetType().GetProperties())
         {
             Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(objCustomer, null));
         }
         Console.Read();
      }
}

Hope this helps.

--
Happy Coding

Gopinath

Tuesday, 15 March 2016

Spaces in Enums

Hi,
 
Today when I was working with Enums and was blocked by a scenario where I need a Space in between the words of Enum. We all know that in Enums we cannot have a space. I was searching for solution and came to know that we can have a desciption as an annotation to the Enum item and read by reflections.
 
Here is the code for reading the description.
 
I have the below enum
 
public enum Date
{
   /// <remarks/>
   [Description("Created Date")]
   CreatedDate,
}
Below is the code which gets the description of Enum

public static string GetEnumDescription(Enum value)
{
     FieldInfo fi = value.GetType().GetField(value.ToString());
     DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
     if (attributes != null && attributes.Length > 0)
     {
           return attributes[0].Description;
     }
     else
     {
           return value.ToString();
     }
}
 
Output

static void Main(string[] args)
{
    string strValueWithOutSpace = Date.CreatedDate.ToString();
    string strValueWithSpace = GetEnumDescription(Date.CreatedDate);
    Console.WriteLine("Without Space : " + strValueWithOutSpace);
    Console.WriteLine("With Space : " + strValueWithSpace);
    Console.Read();
}

 
Hope this helps.
 
--
Happy Coding

Gopinath

Monday, 9 November 2015

Double Versus Decimal in C#

Double is useful for scientific computations (such as computing spatial coordinates). Decimal is useful for financial computations and values that are “man-made” rather than the result of real-world measurements. Here’s a summary of the differences.
  

CategoryDoubleDecimal
Internal RepresentationBase 2 Base 10
Decimal Precision15-16 Significant Figures28-29 Significant figures
Range±(~10−324 to ~10308) ±(~10−28 to ~1028) 
Special Values+0, −0, +∞, −∞, and NaNNone 
SpeedNative to processor Non-native to processor
(about 10 times slower than double)

Most business applications should probably be using decimal rather than float or double. Our thumb rule should be manmade values such as currency are usually better represented with decimal floating point.
 
Hope this helps.
 
--
Happy Coding
Gopinath