European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 3.1.5 Hosting - HostForLIFE.eu :: Consume OData Feed With C# Client Application

clock August 4, 2020 13:04 by author Peter

OData represents Open Data Protocol, an OASIS standard initiated by Microsoft in  2007. This defines the best practices for the consumption of data and building with quarriable REST APIs.

The difference between Odata and REST API is, Odata is a specific protocol and REST is an architectural style and design pattern. Using REST we can request and get data using HTTP calls. OData is a technology that uses REST to consume and build data.

I expect readers of this article to have some knowledge about OData queries. But, to make it simple, this protocol gives the power to the client to query the data on the database using a query string of REST API requests. It also helps to make the data more secure by not exposing any database related information as well as limiting the data to the outside world.

In general, we need to build the Odata enabled web service using any popular programming language which takes care of building URLs, verbs, and their requests and expected responses accordingly. Now, at the client end to consume these Odata REST APIs, we need to have metadata that contains the request type as well response types to build the concrete classes or we need to create a service proxy class.

This article is about how clients can consume existing Odata REST API using C#. So, let's start.

Simple.Odata.Client is a library that supports all Odata protocol versions and can be installed from the NuGet package and supports both .NET Framework and .NET Core latest versions.

Initializing Client Instance
To communicate with Odata REST API, Simple.Odata.Client library has some predefined class called ODataClient. This class accepts service URL with some optional settings to do a seamless communication with Odata service.
var client = new ODataClient("https://services.odata.org/sferp/"); 

If you want to log all the requests and responses from this client object to the Console, we can have additional optional settings as below.
var client = new ODataClient(new ODataClientSettings("https://services.odata.org/sferp/") 

    OnTrace = (x, y) => Console.WriteLine(string.Format(x, y)) 
}); 


Building the Typed Classes
This library doesn't help you to build any Typed classes of the responses (tables/views) from the given service as we do this with the entity framework. To build the typed DTO classes, we need to fetch the metadata from the configured Odata web service by appending $metadata at the end of the base URL as follows.
https://services.odata.org/sferp/$metadata

Metadata will be displayed in XML format, we need to identify the elements for the table and their columns with datatypes to create classes accordingly for each table.

Retrieving Data Collection
As we did with initializing the communication to the service, now we need to fetch some data from the service. For example, the following statement will fetch all the data in the table Articles with the help of Odata protocol.
var articles = await client      
                    .For<Article>() 
                    .FindEntriesAsync(); 

Here, the client is an object of the ODataClient class.

There is a problem with the above statement. If this Article table has millions of records, your HTTP call will block or return a timeout exception and you cannot achieve your requirement. To avoid such situations, we need to use annotations defined in this library.

Annotations will help to minimize the load on the network by limiting the records in a single fetch. Along with records it also sends the link to fetch the next set of records so that this can be fetched until all records get fetched from the Articles table.
var annotations = new ODataFeedAnnotations(); 
var article = await client 
    .For<Article>() 
    .FindEntriesAsync(annotations) 
    .ToList(); 
while (annotations.NextPageLink != null) 

    article.AddRange(await client 
        .For<Article>() 
        .FindEntriesAsync(annotations.NextPageLink, annotations) 
    ); 


In the above code, the first call will fetch a set of 8 records (by default or it can decide as per network speed to avoid timeout exception) along with nextpagelink property. Just this property will set the URL of OData web service to fetch the next page of records.

Include Associated Data Collections

So far, we fetched the table directly but we can also have the requirement to fetch or include in terms of entity framework all their constraint key records as a response to the request. To achieve it, our library provides an Expand() method to declare all included tables' information so that the OData API will associate it and map to the response object while sending the response.
var articles = await client 
    .For<Article>() 
    .Expand(x => new { x.Ratings, x.Comments }) 
    .FindEntryAsync(); 


In the above example, the system will fetch all  information along with ratings and comment data as part of each article record by joining it accordingly at the web service end.

Authentication
So far, we have understood how to configure and consume the data from the existing Odata service API. Now, in real-time to make their data secure, API should authenticate the request as well as the requested client. To do so, we need to generate a token based on the credentials shared by API services.

The following are the codebases to prepare the ODataClient object by generating the token based on given credentials.
private ODataClient GetODataClient() 
        { 
            try 
            { 
                string url = _config.GetSection("APIDetails:URL").Value; 
                String username = _config.GetSection("APIDetails:UserName").Value; 
                String password = _config.GetSection("APIDetails:Password").Value; 
 
                String accessToken = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); 
 
                var oDataClientSettings = new ODataClientSettings(new Uri(url)); 
                oDataClientSettings.BeforeRequest += delegate (HttpRequestMessage message) 
                { 
                    message.Headers.Add("Authorization", "Basic " + accessToken); 
                }; 
 
                var client = new ODataClient(oDataClientSettings); 
 
                Simple.OData.Client.V4Adapter.Reference(); 
 
                return client; 
            } 
            catch(Exception ex) 
            { 
                LogError("", $"Failed to connect API Services : {ex.Message}"); 
            } 
 
            return null; 
        } 


In the above code, we are getting URL, Username, and password from appsettings.json file and then creating a Basic token by converting the username and password strings. Once the token is generated, we are sending this token in the Authorization header by using the ODataClientSettings object and creating the ODataClient object.

Once this ODataClient object is created, we can request the data from OData web services as discussed above.

I hope this article helped you to understand how C# based client applications can be created and used to consume existing OData API services.



ASP.NET Core 3.1.4 Hosting - HostForLIFE.eu :: How To Serialize Nonstandard Enum Values?

clock July 21, 2020 13:50 by author Peter

.NET client libraries that integrate with third-party APIs occasionally need to compromise on how enum values are represented in model classes. For example, an API that requires values to be expressed in all uppercase letters force the creation of an enum similar to:

public enum YesNoMaybeEnum  
 {  
     YES,  
     NO,  
     MAYBE   
 }  


While this will compile, it violates .NET naming conventions. In other cases, the third party may include names that include invalid characters like dashes or periods. For example, Amazon's Alexa messages include a list of potential request types that include a period in the names. These values cannot be expressed as enumation names. While this could be addressed by changing the data type of the serialized property from an enumeration to a string, the property values are no longer constrained and any suggestions from Intellisense are lost.

This article demonstrates how to eat your cake and have it, too. Using attributes and reflection, values can be serialized to and deserialized from JSON.

Serialization with EnumDescription
Let's say we need to serialize values that include periods. Creating an enum like the following generates compile time errors,

public enum RequestTypeEnum  
{  
    LaunchRequest,  
    IntentRequest,  
    SessionEndedRequest,  
    CanFulfillIntentRequest,  
    AlexaSkillEvent.SkillPermissionAccepted,  
    AlexaSkillEvent.SkillAccountLinked,  
    AlexaSkillEvent.SkillEnabled,  
    AlexaSkillEvent.SkillDisabled,  
    AlexaSkillEvent.SkillPermissionChanged,  
    Messaging.MessageReceived  
}  

The EnumMember attribute defines the value to serialize when dealing with data contracts. Samples on Stack Overflow that show enumeration serialization tend to use the Description attribute. Either attribute can be used or you can create your own. The EnumMember attribute is more tightly bound to data contract serialization while the Description attribute is for use with design time and runtime environments, the serialization approach in this article opts for the EnumMember. After applying the EnumMember and Data Contract attributes, the enum now looks like,

[DataContract(Name = "RequestType")]    
public enum RequestTypeEnum    
{    
    [EnumMember(Value = "LaunchRequest")]    
    LaunchRequest,    
    [EnumMember(Value = "IntentRequest")]    
    IntentRequest,    
    [EnumMember(Value = "SessionEndedRequest")]    
    SessionEndedRequest,    
    [EnumMember(Value = "CanFulfillIntentRequest")]    
    CanFulfillIntentRequest,    
    [EnumMember(Value = "AlexaSkillEvent.SkillPermissionAccepted")]    
    SkillPermissionAccepted,    
    [EnumMember(Value = "AlexaSkillEvent.SkillAccountLinked")]    
    SkillAccountLinked,    
    [EnumMember(Value = "AlexaSkillEvent.SkillEnabled")]    
    SkillEnabled,    
    [EnumMember(Value = "AlexaSkillEvent.SkillDisabled")]    
    SkillDisabled,    
    [EnumMember(Value = "AlexaSkillEvent.SkillPermissionChanged")]    
    SkillPermissionChanged,    
    [EnumMember(Value = "Messaging.MessageReceived")]    
    MessageReceived    
}    

The EnumMember attribute is also applied to enum members without periods. Otherwise, the DataContractSerilizer would serializes the numeric representation of the enumeration value. Now we can define a DataContract with,
[DataContract]  
public class SamplePoco  
{  
    [DataMember]  
    public RequestTypeEnum RequestType { get; set; }  
}
 

And serialize it to XML with,
SamplePoco enumPoco = new SamplePoco();  
enumPoco.RequestType = RequestTypeEnum.SkillDisabled;  
DataContractSerializer serializer = new DataContractSerializer(typeof(SamplePoco));  
 
var output = new StringBuilder();  
using (var xmlWriter = XmlWriter.Create(output))  
{  
    serializer.WriteObject(xmlWriter, enumPoco);  
    xmlWriter.Close();  
}  
string xmlOut = output.ToString();   


This generates the following XML,
<?xml version="1.0" encoding="utf-16"?><SamplePoco xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/EnumSerializationSample"><RequestType>AlexaSkillEvent.SkillDisabled</RequestType>  
</SamplePoco>  


DataContract serialization is sorted out, but doesn't yet address JSON serialization.

JSON Serialization

If you need to work with any REST API endpoints, then you'll need to support JSON. The NewtonSoft JSON has its own serialization strategy, and so the EnumMember attribute needs to be leveraged to integrate with it using a custom JsonConverter, but before taking that step, the enumation value must be read from the attribute.

This method accepts an enum value and returns the string value in the EnumMember attribute.
private string GetDescriptionFromEnumValue(Enum value)  
        {  
 
#if NETSTANDARD2_0  
            EnumMemberAttribute attribute = value.GetType()  
                .GetField(value.ToString())  
                .GetCustomAttributes(typeof(EnumMemberAttribute), false)  
                .SingleOrDefault() as EnumMemberAttribute;  
 
            return attribute == null ? value.ToString() : attribute.Value;  
#endif  
 
#if NETSTANDARD1_6 || NETSTANDARD1_3 || NET45 || NET47  
 
            EnumMemberAttribute attribute = value.GetType()  
                .GetRuntimeField(value.ToString())  
                .GetCustomAttributes(typeof(EnumMemberAttribute), false)  
                .SingleOrDefault() as EnumMemberAttribute;  
 
            return attribute == null ? value.ToString() : attribute.Value;  
            
#endif  
              throw new NotImplementedException("Unsupported version of .NET in use");  
        }  


There's a subtle difference between the .NET Standard 2.0 implementation and the others. In .NET Standard 1.6 and prior versions, use the GetRuntimeField method to get a property from a type. In .NET Standard 2.0, use the GetField method to return the property of a type. The compile-time constants and checks in the GetDescriptionFromEnumValue abstract away that complexity.  

Coming the other way, a method needs to take a string and convert it to the associated enumeration.
public T GetEnumValue(string enumMemberText)   
{  
 
    T retVal = default(T);  
 
    if (Enum.TryParse<T>(enumMemberText, out retVal))  
        return retVal;  
 
      var enumVals = Enum.GetValues(typeof(T)).Cast<T>();  
 
    Dictionary<string, T> enumMemberNameMappings = new Dictionary<string, T>();  
 
    foreach (T enumVal in enumVals)  
    {  
        string enumMember = enumVal.GetDescriptionFromEnumValue();  
        enumMemberNameMappings.Add(enumMember, enumVal);  
    }  
 
    if (enumMemberNameMappings.ContainsKey(enumMemberText))  
    {  
        retVal = enumMemberNameMappings[enumMemberText];  
    }  
    else  
        throw new SerializationException($"Could not resolve value {enumMemberText} in enum {typeof(T).FullName}");  
 
    return retVal;  
}  

The values expressed in the EnumMember attributes are loaded into a dictionary. The value of the attribute serves as the key and the associated enum is the value. The dictionary keys are compared to the string value passed to the parameter and if a matching EnumMember value is found, then the related enum is returned and so "AlexaSkillEvent.Enabled" returns RequestTypeEnum.SkillEnabled.
Using this method in a JSON Converter, the WriteJson method looks like the following,
public class JsonEnumConverter<T> : JsonConverter where T : struct, Enum, IComparable, IConvertible, IFormattable
{  
 
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)  
    {  
        if (value != null)  
        {  
            Enum sourceEnum = value as Enum;  
 
            if (sourceEnum != null)    
            {  

                string enumText = GetDescriptionFromEnumValue(sourceEnum);  
                writer.WriteValue(enumText);  
            }  
        }  
    }  


Please note that an enum constraint is applied to the generic type class declaration. This wasn't possible until C# version 7.3. If you cannot upgrade to use C# version 7.3, just remove this constraint.

The corresponding ReadJson method is,
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)  
{  
      object val = reader.Value;  
      if (val != null)  
    {  
        var enumString = (string)reader.Value;  
          return GetEnumValue(enumString);  
    }  
      return null;  
}  


Now the class definition needs to apply the JsonConverter class to the RequestType property,
[DataContract]  
public class SamplePoco  
{  
    [DataMember]  
    [JsonConverter(typeof(JsonEnumConverter<RequestTypeEnum>))]  
    public RequestTypeEnum RequestType { get; set; }  
 
 

Finally, the SamplePoco class is serialized to JSON,
SamplePoco enumPoco = new SamplePoco();  
enumPoco.RequestType = RequestTypeEnum.SkillEnabled;  
string samplePocoText = JsonConvert.SerializeObject(enumPoco);  
This generates the following JSON,
{  
"RequestType":"AlexaSkillEvent.SkillEnabled"  
}  

And deserialing the JSON yields the RequestTypeEnum.SkillEnabled value on the sample class.

string jsonText = "{\"RequestType\":\"AlexaSkillEvent.SkillEnabled\"}";  
SamplePoco sample = JsonConvert.DeserializeObject<SamplePoco>(jsonText); 

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.




ASP.NET Core Hosting - HostForLIFE.eu :: How .NET Support Multiple Languages?

clock July 6, 2020 13:38 by author Peter

An application is said to be multilingual if it can be deployed in many different languages. With .NET, all of the languages including Visual Basic, .NET, C#, and J# compile to a common Intermediate language (IL). This makes all languages interoperable. Microsoft has created Java bytecode, which is a low-level language with a simple syntax, which can be very quickly translated into native machine code.

CLR
.NET Framework is a multilingual application because of CLR. CLR is the key of .NET Framework. The code running under the control of the CLR is often termed as managed code.

The main task of CLR is to convert compiled code into the native code.
.NET Framework has one or more compilers; for e.g., VB .NET, C#, C++, JScript or any third party compiler such as COBOL. Anyone of these compilers will convert your source code into Microsoft Intermediate Language (MSIL). The main reason for .NET to be multilingual is that you can compile your code from IL and this compiled code will be interoperable with the code that has been compiled to IL from another language.

It simply means that you can create pages in different languages (like C#, VB .NET, J# etc.) and once all of these pages are compiled they all can be used in a single application. Let us understand this point clearly with an example.

Let us consider a situation where a customer needs an application to be ready in 20 days. For completing the application in 20 days we want 30 developers who all know the specific language but we have 15 developers who know C# and 15 developers who know VB .NET. In this situation, if we don’t use .NET then we need to hire 15 more developers of C# or VB .NET which is a difficult and costly solution. Now, if we use .NET then we can use C# and VB .NET language in the same application. This is possible because once C# code is compiled from IL it becomes interoperable with VB .NET code which is compiled from IL.

Then JIT (Just In Time) of CLR converts this MSIL code into native code using metadata which is then executed by OS.

CLR stands for common language runtime. Common language runtime provides other services like memory management, thread management, remoting, and other security such as CTS and CLS.

CLR is a layer between an operating system and .NET language, which uses CTS and CLS to create code.

CTS
CTS stands for the common type system. CTS defines rules that common language runtime follows when we are declaring, using and managing type. CTS deals with the data type. .NET supports many languages and every language has its own data type. One language cannot understand data types of another language.

For example: When we are creating an application in C#, we have int and when we are creating an application in VB .NET, we have an integer. Here CTS comes into play --  after the compilation, CTS converts int and integer into the int32 structure.

CLS
CLS stands for common language specification.
CLS is a subset of CTS and it declares all the rules and restrictions that all languages under .NET Framework must follow. The language which follows these rules is known as CLS compliant.
For example, we can use multiple inheritances in c++ but when we use the same code in C# it creates a problem because C# does not support multiple inheritances. Therefore, CLS restricts multiple inheritances for all language.

One other rule is that you cannot have a member with the same name and a different case. In C# add() and Add() are different because it is case sensitive but a problem arises when we use this code in VB .NET because it is not case-sensitive and it considers add() and Add() as the same.


HostForLIFE.eu ASP.NET Core 3.1.4 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core Hosting - HostForLIFE.eu :: SQL Store Procedure Call Function In .NET Core Console Application

clock June 29, 2020 13:09 by author Peter

In this function, the SQL procedure table reads a procedure call method in the .NET Core application for the basic console write to get the input value to the search result. The SQL procedure calls to select the statement from the database.

SQL Procedure
    CREATE PROCEDURE  procselect  @username nchar(10)    
    AS    
         select * from wincurd where username=@username     
    go      


Basic string console values get functionality:
    string val;  
    Console.Write("Enter value: ");  
    val = Console.ReadLine();  
    string a = Convert.ToString(val);  
    Console.WriteLine("Your input: {0}", a);  


SQL Connection string functionality:
    SqlConnection dc = new SqlConnection("Data Source=.;Initial Catalog=databasename;Integrated Security=True");   

Command Execution Functionality
    using(SqlCommand cmd = new SqlCommand("procselect", dc)) {  
        cmd.CommandType = CommandType.StoredProcedure;  
        cmd.Parameters.AddWithValue("@username", a.ToString());  
        dc.Open();  
        SqlDataReader dr;  
        dr = cmd.ExecuteReader();  
        if (!dr.Read()) {  
            Console.Write("Record not found ");  
        } else {  
            string b = Convert.ToString(val);  
            b = dr[1].ToString();  
            Console.WriteLine("Your PASSWORD: {0}", b.ToString());  
            Console.ReadLine();  
        }  
        dc.Close();  
    }  





European ASP.NET Core Hosting - HostForLIFE.eu :: How To Serialize Nonstandard Enum Values?

clock June 22, 2020 12:50 by author Peter

.NET client libraries that integrate with third-party APIs occasionally need to compromise on how enum values are represented in model classes. For example, an API that requires values to be expressed in all uppercase letters force the creation of an enum similar to:
    public enum YesNoMaybeEnum 
     { 
         YES, 
         NO, 
         MAYBE  
     } 

While this will compile, it violates .NET naming conventions. In other cases, the third party may include names that include invalid characters like dashes or periods. For example, Amazon's Alexa messages include a list of potential request types that include a period in the names. These values cannot be expressed as enumation names. While this could be addressed by changing the data type of the serialized property from an enumeration to a string, the property values are no longer constrained and any suggestions from Intellisense are lost.
 
This article demonstrates how to eat your cake and have it, too. Using attributes and reflection, values can be serialized to and deserialized from JSON.
 
Serialization with EnumDescription
Let's say we need to serialize values that include periods. Creating an enum like the following generates compile time errors,
    public enum RequestTypeEnum 
    { 
        LaunchRequest, 
        IntentRequest, 
        SessionEndedRequest, 
        CanFulfillIntentRequest, 
        AlexaSkillEvent.SkillPermissionAccepted, 
        AlexaSkillEvent.SkillAccountLinked, 
        AlexaSkillEvent.SkillEnabled, 
        AlexaSkillEvent.SkillDisabled, 
        AlexaSkillEvent.SkillPermissionChanged, 
        Messaging.MessageReceived 
    } 

The EnumMember attribute defines the value to serialize when dealing with data contracts. Samples on Stack Overflow that show enumeration serialization tend to use the Description attribute. Either attribute can be used or you can create your own. The EnumMember attribute is more tightly bound to data contract serialization while the Description attribute is for use with design time and runtime environments, the serialization approach in this article opts for the EnumMember. After applying the EnumMember and Data Contract attributes, the enum now looks like,
    [DataContract(Name = "RequestType")]   
    public enum RequestTypeEnum   
    {   
        [EnumMember(Value = "LaunchRequest")]   
        LaunchRequest,   
        [EnumMember(Value = "IntentRequest")]   
        IntentRequest,   
        [EnumMember(Value = "SessionEndedRequest")]   
        SessionEndedRequest,   
        [EnumMember(Value = "CanFulfillIntentRequest")]   
        CanFulfillIntentRequest,   
        [EnumMember(Value = "AlexaSkillEvent.SkillPermissionAccepted")]   
        SkillPermissionAccepted,   
        [EnumMember(Value = "AlexaSkillEvent.SkillAccountLinked")]   
        SkillAccountLinked,   
        [EnumMember(Value = "AlexaSkillEvent.SkillEnabled")]   
        SkillEnabled,   
        [EnumMember(Value = "AlexaSkillEvent.SkillDisabled")]   
        SkillDisabled,   
        [EnumMember(Value = "AlexaSkillEvent.SkillPermissionChanged")]   
        SkillPermissionChanged,   
        [EnumMember(Value = "Messaging.MessageReceived")]   
        MessageReceived   
    }   


The EnumMember attribute is also applied to enum members without periods. Otherwise, the DataContractSerilizer would serializes the numeric representation of the enumeration value. Now we can define a DataContract with,
    [DataContract] 
    public class SamplePoco 
    { 
        [DataMember] 
        public RequestTypeEnum RequestType { get; set; } 
    } 

And serialize it to XML with,
    SamplePoco enumPoco = new SamplePoco(); 
     
    enumPoco.RequestType = RequestTypeEnum.SkillDisabled; 
     
    DataContractSerializer serializer = new DataContractSerializer(typeof(SamplePoco)); 
     
    var output = new StringBuilder(); 
    using (var xmlWriter = XmlWriter.Create(output)) 
    { 
     
        serializer.WriteObject(xmlWriter, enumPoco); 
        xmlWriter.Close(); 
    } 
     
    string xmlOut = output.ToString();  


This generates the following XML,
    <?xml version="1.0" encoding="utf-16"?><SamplePoco xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/EnumSerializationSample"><RequestType>AlexaSkillEvent.SkillDisabled</RequestType> 
    </SamplePoco> 


DataContract serialization is sorted out, but doesn't yet address JSON serialization.
 
JSON Serialization
If you need to work with any REST API endpoints, then you'll need to support JSON. The NewtonSoft JSON has its own serialization strategy, and so the EnumMember attribute needs to be leveraged to integrate with it using a custom JsonConverter, but before taking that step, the enumation value must be read from the attribute.
 
This method accepts an enum value and returns the string value in the EnumMember attribute.
    private string GetDescriptionFromEnumValue(Enum value) 
            { 
    
    #if NETSTANDARD2_0 
                EnumMemberAttribute attribute = value.GetType() 
                    .GetField(value.ToString()) 
                    .GetCustomAttributes(typeof(EnumMemberAttribute), false) 
                    .SingleOrDefault() as EnumMemberAttribute; 
     
                return attribute == null ? value.ToString() : attribute.Value; 
    #endif 
    
    #if NETSTANDARD1_6 || NETSTANDARD1_3 || NET45 || NET47 
     
                EnumMemberAttribute attribute = value.GetType() 
                    .GetRuntimeField(value.ToString()) 
                    .GetCustomAttributes(typeof(EnumMemberAttribute), false) 
                    .SingleOrDefault() as EnumMemberAttribute; 
     
                return attribute == null ? value.ToString() : attribute.Value; 
               
    #endif 
     
     
                throw new NotImplementedException("Unsupported version of .NET in use"); 
            } 


There's a subtle difference between the .NET Standard 2.0 implementation and the others. In .NET Standard 1.6 and prior versions, use the GetRuntimeField method to get a property from a type. In .NET Standard 2.0, use the GetField method to return the property of a type. The compile-time constants and checks in the GetDescriptionFromEnumValue abstract away that complexity. 
 
Coming the other way, a method needs to take a string and convert it to the associated enumeration.
    public T GetEnumValue(string enumMemberText)  
    { 
     
        T retVal = default(T); 
     
        if (Enum.TryParse<T>(enumMemberText, out retVal)) 
            return retVal; 
     
     
        var enumVals = Enum.GetValues(typeof(T)).Cast<T>(); 
     
        Dictionary<string, T> enumMemberNameMappings = new Dictionary<string, T>(); 
     
        foreach (T enumVal in enumVals) 
        { 
            string enumMember = enumVal.GetDescriptionFromEnumValue(); 
            enumMemberNameMappings.Add(enumMember, enumVal); 
        } 
     
        if (enumMemberNameMappings.ContainsKey(enumMemberText)) 
        { 
            retVal = enumMemberNameMappings[enumMemberText]; 
        } 
        else 
            throw new SerializationException($"Could not resolve value {enumMemberText} in enum {typeof(T).FullName}"); 
     
        return retVal; 
    } 


The values expressed in the EnumMember attributes are loaded into a dictionary. The value of the attribute serves as the key and the associated enum is the value. The dictionary keys are compared to the string value passed to the parameter and if a matching EnumMember value is found, then the related enum is returned and so "AlexaSkillEvent.Enabled" returns RequestTypeEnum.SkillEnabled.
 
Using this method in a JSON Converter, the WriteJson method looks like the following,
    public class JsonEnumConverter<T> : JsonConverter where T : struct, Enum, IComparable, IConvertible, IFormattable
    { 
     
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
        { 
            if (value != null) 
            { 
                Enum sourceEnum = value as Enum; 
     
                if (sourceEnum != null)   
                { 

                    string enumText = GetDescriptionFromEnumValue(sourceEnum); 
                    writer.WriteValue(enumText); 
                } 
            } 
        } 


Please note that an enum constraint is applied to the generic type class declaration. This wasn't possible until C# version 7.3. If you cannot upgrade to use C# version 7.3, just remove this constraint.
 
The corresponding ReadJson method is,
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     
        object val = reader.Value; 
     
        if (val != null) 
        { 
            var enumString = (string)reader.Value; 
     
            return GetEnumValue(enumString); 
        } 
     
        return null; 
    } 


Now the class definition needs to apply the JsonConverter class to the RequestType property,
    [DataContract] 
    public class SamplePoco 
    { 
        [DataMember] 
        [JsonConverter(typeof(JsonEnumConverter<RequestTypeEnum>))] 
        public RequestTypeEnum RequestType { get; set; } 
     
    }  


Finally, the SamplePoco class is serialized to JSON,
    SamplePoco enumPoco = new SamplePoco(); 
     
    enumPoco.RequestType = RequestTypeEnum.SkillEnabled; 
     
    string samplePocoText = JsonConvert.SerializeObject(enumPoco); 


This generates the following JSON,
    { 
      "RequestType":"AlexaSkillEvent.SkillEnabled" 
    } 


And deserialing the JSON yields the RequestTypeEnum.SkillEnabled value on the sample class.
    string jsonText = "{\"RequestType\":\"AlexaSkillEvent.SkillEnabled\"}"; 
     
    SamplePoco sample = JsonConvert.DeserializeObject<SamplePoco>(jsonText); 

Summary
The EnumMember attribute is used to drive serializing of non-standard enum values using both DataContract serialization and Newtonsoft JSON serialization. Attached sample code shows other examples and unit tests. The Whetstone.Alexa NuGet package makes use of this technique and is also available for reference on GitHub.



European ASP.NET Core Hosting - HostForLIFE.eu :: Graphs In ASP.NET MVC Using HighCharts

clock June 17, 2020 13:13 by author Peter

Firstly, we will learn how to fetch your data from a database (here we will use MsSql ) and then present it in the View using HighCharts. To understand the complete article, you must have basic knowledge/understanding about the below mentioned technologies/ methods,

  • Asp.Net MVC.
  • MSSQL Server.
  • JavaScript
  • JSON (JavaScript Object Notation).
  • ADO.Net
  • Entity Framework

We will be using HighCharts for representing our record as chart/graph (given at the end of the article).
 
What is HighCharts?
Highcharts is a charting library written in pure JavaScript, offering an easy way of adding interactive charts to your web site or web application. In the vast majority of charts we will be using a basic column chart here to represent our data.
 
You can visit here to check more variety and select which is best for your scenario.
 
Steps 1 - Creating a basic Asp.Net MVC Web Based Application.
Create an Application in ASP.NET MVC web application using Visual Studio.
 
Go to File Menu > New > Project.
 
Select ASP.NET Web Application ( .NET Framework ) and change the application name:
 
e.g. : HighCharts, and then click OK
 
Choose MVC>
 
Now, the MVC web application project is created with the default ASP.NET MVC template.
 
Step 2 - Create/Step up your DataBase and Table.
Here, we are using an existing MsSql Database of a “Grievance Portal” and a table (T_Complaint) which stores the data of the person from whom the Complaint has been received and we will show the same number of applications which are received by year,  by grouping them by years of application received and then sorting them by year.
 
The Structure of the table (T_Complaint) is as Below,

There will be many more columns like address, district, state, father’s name, complaint description, but as of now the above-mentioned columns are enough for our task.
 
Since the data that we will fetch could be huge here we are using “Stored Procedure” to retrieve it by just calling it from the controller as Stored Procedures take less time to fetch a huge amount of data as compared to SQL queries.
 
The below code will help you to create a Stored procedure.
    Create PROCEDURE [dbo].[SP_YearlyRec] 
    AS 
     
    select sum(Total)as 'Total',max(t1.concluded)as concluded,MAX(t1.Not_concluded)as Not_concluded,Complainletteryear from ( 
    select count(Complainletterdate) as 'Total',case when Conclusion=1 then count(year(Complainletterdate))end as concluded, 
    case when Conclusion=0 then count(year(Complainletterdate)) else 0 end as Not_concluded,YEAR(Complainletterdate) as [Complainletteryear] from T_Complaint 
    where Complainletterdate is not null 
    group by year(Complainletterdate),Conclusion 
    )t1 group by t1.Complainletteryear order by t1.Complainletteryear. 


Step 3 - Working on Controller
 
Here we will use the default HomeController that is created automatically when we create a new MVC application.
In the HomeController we will use default Index() ActionMethod and modify it as per our need or you can also create a new ActionMethod for yourself.
    public ActionResult Index() 
    { 
       return View(); 
    } 


Now create a view for your ActionMethod and give it the same name as your ActionMethod.
<view code is given below>
 
Next, we will create the WebMethod where we will call the Stored procedure which we have created previously.
    [WebMethod] 
    public JsonResult GetText() { 
        var db1 = new Grievance_Entities1(); 
        var list = db1.SP_YearlyRec(); 
        return Json(list.ToList(), JsonRequestBehavior.AllowGet); 
    } 


In the above code, Grievance_Entities1 is the entity we have created of our database which has a Stored Procedure “SP_YearlyRec” using Entity Framework.
 
Once it is created, open the index view and write the below code in the view.
 
We are dividing the View/HTML Code in 3 parts, Which are,
 
Head
The Head Will contain the links to HighCharts important Library as well as the styling of the complete graph inside a style tag . Every change in our design of our HighCharts need to be done here only in the Style tag itself.
 
Body
The body tag will contain the body of our HTML page which is HighCharts Graph in this Case.
    <div class="container"> 
        <h2 id="h2">Index</h2> 
        <figure class="highcharts-figure container" > 
            <div id="container-fluid" class="container-fluid"></div> 
            <p class="highcharts-description"> 
                A basic column chart . 
            </p> 
        </figure> 
    </div> 


Script
The Script tag will be the functioning body of our View as here we will use Ajax to fetch our data from the database by calling the WebMethod which is in our HomeController and will return Json Result as an output.
 
As this is the most important part of our module so I will be explaining the working of this module.
 
The javascript here has two parts first is the $(document).ready() ,and the other is a function which we have created that is LoadChart().
 
$(document).ready() is automatically triggered when the document is loaded. Whatever code we write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
 
So, here we will call the WebMethod in our controller using Ajax which is GetText using URL format “../{ControllerName}/{MethodName}”. And if the data is fetched correctly then we will call the LoadChart() function to Load the HighCharts with the fetched data.
 
Below is the code that will be placed in $(document ). ready() method.
    $(document).ready(function() { 
                var Complainletteryear = []; 
                var Total = []; 
                var concluded = []; 
                var N_concluded = []; 
                $.ajax({ 
                    type: "POST", 
                    url: "../Home/GetText", 
                    data: "{}", 
                    contentType: "application/json; charset=utf-8", 
                    dataType: "json", 
                    async: true, 
                    success: function(result) { 
                        $.each(result, function(key, item) { 
                            Complainletteryear.push(item.Complainletteryear); 
                            Total.push(item.Total); 
                            concluded.push(item.concluded); 
                            N_concluded.push(item.Not_concluded); 
                        }); 
                        loadChart(Complainletteryear, Total, concluded, N_concluded); 
                    }, 
                    error: function(errormessage) { 
                        $('#h2').html(errormessage.responseText); 
                        return false; 
                    } 
                }); 

In the above code, after the data is fetched we are selecting each Row using the foreach loop and putting every column in a specific array as the data accepted by HighCharts is either in the form of Array or Objects. In our case we need our data in the form of array. Refer to foreach loop in the above code.
 
Below we can see the Code where we will be working with HighCharts.
    function loadChart(category, val2, val3, val4) { 
        Highcharts.chart('container-fluid', { 
                chart: { 
                    type: 'column', 
                }, 
                title: { 
                    text: 'No. of Application Received yearly ' 
                }, 
                subtitle: { 
                    text: 'Source: LocalDb.com' 
                }, 
                xAxis: { 
                    categories: category, 
                    crosshair: true 
                }, 
                yAxis: { 
                    min: 0, 
                    title: { 
                        text: 'Number of Application' 
                    } 
                }, 
                tooltip: { 
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>', 
                    pointFormat: '<tr href="#"><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y} </b></td></tr>', 
                    footerFormat: '</table>' 
                }, 
                shared: true, 
                useHTML: true 
            }, series: [{ 
                name: 'Total', 
                data: val2, 
                color: '#ccb1fc', 
            }, { 
                name: 'Concluded', 
                data: val3, 
                color: '#b0ceff', 
            }, { 
                name: 'Not Concluded', 
                data: val4, 
                color: '#fcb1f0' 
            }] 
        }); 
    } 


In the above code, we have 4 input parameters which are category, val2,val3,val4.
Each variable is of array type which represents each column provided as an output from our stored procedure.
 
The variable category here defines X-Axis Categories which will be shown in the chart as a category for each column. The remaining three arrays consist of data which is to be represented as a vertical bar in each column.
 
The title here defines the  title of the Chart/Graph.
Chart Type tells what chart we will be using in the module.
 
Below is the figure which shows the output after implementing the above HighCharts code in Asp.Net MVC
 
Graphs In ASP.NET MVC Using HighCharts
 
Conclusion
To conclude , HighCharts are a user friendly graphical representation of data which can easily be represented using the above implementation in Asp.Net MVC application.




European ASP.NET Core Hosting - HostForLIFE.eu :: Using The IComparable And IComparer Interface In C#

clock May 19, 2020 07:54 by author Peter

One of the most used functionalities in our C# classes is the ability to sort the different instances of a class. This is mostly done when we create a generic List of our class type and next, we want to sort our class based on some condition. Today, we will see how this is done in our C# classes

Creating the Class

We will create a .NET core console application using Visual Studio 2019 Community edition as below,

Next, we create a Student Class inside the “Program.cs” file as below,
  public class Student : IComparable<Student> 
  { 
   
      public int ID { get; set; } 
      public string Name { get; set; } 
      public string Program { get; set; } 
      public int Year { get; set; } 
      public float GPA { get; set; } 
   
      public int CompareTo(Student otherItem) 
      { 
          var status = (this.GPA > otherItem.GPA) ? 1 : ((this.GPA == otherItem.GPA) ? 0 : -1);  
          return status; 
      } 
  } 


Let us look at the code in detail. To make the class sortable we need to implement the IComparable<T> interface. In this interface we need to code the “CompareTo” function. In this function another instance of the same class is passed in and then we compare the two to order them. We base this on the GPA field and hence when we sort a List<Student> list, we will get the class items sorted by GPA in ascending order. Note that if the return value is zero, this means that the classes are equal in sort order, if the return value is 1 (positive number), then the current class is higher in the sort and if the value is -1 (negative number) then the input class is higher in the sort order.

To test this out, we write the following code in the Main function as below,
  class Program 
      { 
          static void Main(string[] args) 
          { 
   
              var students = new List<Student>(); 
   
              var studentA = new Student() { ID = 1, Name = "John Doe", Program = "BCS", Year = 2020, GPA = 2.75F }; 
              var studentB = new Student() { ID = 1, Name = "Jane Doe", Program = "BCS", Year = 2020, GPA = 3.4F }; 
              var studentC = new Student() { ID = 1, Name = "Mary Jane", Program = "BCS", Year = 2020, GPA = 2.71F }; 
   
              students.Add(studentA); 
              students.Add(studentB); 
              students.Add(studentC); 
   
              Console.WriteLine($"Items not in any order"); 
              foreach(var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.WriteLine(); 
   
              students.Sort(); 
   
              Console.WriteLine($"Items in ascending order"); 
              foreach (var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.WriteLine(); 
   
              students.Sort(new DescendingComparer()); 
   
              Console.WriteLine($"Items in descending order"); 
              foreach (var student in students) 
              { 
                  Console.WriteLine($"Student ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); 
              } 
   
              Console.ReadKey(); 
          } 
      } 
   
      public class DescendingComparer : IComparer<Student> 
      { 
          public int Compare(Student a, Student b) 
          { 
              var status = (a.GPA > b.GPA) ? -1 : ((a.GPA == b.GPA) ? 0 : 1); 
              return status; 
          } 
      } 


In the first case, we print the list of student classes as entered in the list. Then, we sort the list which will list the students in ascending order based on the GPA field. Finally, if we want to reverse the order and sort the student classes in descending order by GPA field we create a new DescendingComparer class which implements the IComparer<Student> interface and sort the records in the reverse order of what we did before.



European ASP.NET Core Hosting - HostForLIFE.eu :: Action Result in ASP.NET Core API

clock May 5, 2020 10:12 by author Peter

This article overview action result which are used in ASP.NET Core and Core API. We will understand both, which are available in two different assemblies of ASP.NET Core Microsoft.AspNetCore.Mvc and System.Web.Http.

ObjectResult
ObjectResult primary role is content negotiation. It has some variation of a method called SelectFormatter on its ObjectResultExecutor. You can return an object with it, and it formats the response based on what the user requested in the Accept header. If the header didn’t exist, it returns the default format configured for the app. It’s important to note that if the request is issued through a browser, the Accept header will be ignored, unless we set the RespectBrowserAcceptHeader to true when we configure the MVC options in Startup.cs. Also, it doesn’t set the status code, which causes the status code to be null. ObjectResult is the super type of following:

AcceptedResult

AcceptedAtActionResult
AcceptedAtRouteResult
BadRequestObjectResult
CreatedResult
CreatedAtActionResult
CreatedAtRouteResult
NotFoundObjectResult
OkObjectResult

AcceptedResult

An AcceptedResultthat returns an Accepted (202) response with a Location header. It indicates that the request is successfully accepted for processing, but it might or might not acted upon. In this case, we should redirect the user to a location that provides some kind of monitor on the current state of the process. For this purpose, we pass a URI.
public AcceptedResult AcceptedActionResult() 
    { 
        return Accepted(new Uri("/Home/Index", UriKind.Relative), new { FirstName = "Peter",LastName="Scott" }); 
    } 


AcceptedAtActionResult
An AcceptedAtActionResult action result returns an accepted 202 response with a location header.
public AcceptedAtActionResult AcceptedAtActionActionResult() 

return AcceptedAtAction("IndexWithId", "Home", new { Id = 2, area = "" }, new { FirstName = "Peter",LastName="Scott" }); 


AcceptedAtRouteResult
An AcceptedAtRouteResult returns an Accepted (202) response with a Location header. It's the same as AcceptedResult, with the only difference being that it takes a route name and route value instead of URI.
public AcceptedAtRouteResult AcceptedAtRouteActionResult() 

return AcceptedAtRoute("default", new { Id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 


BadRequestResult
An ObjectResult, when executed. will produce a Bad Request (400) response. It indicates a bad request by user. It does not take any argument.
public BadRequestResult BadRequestActionResult() 

  return BadRequest(); 


BadRequestObjectResult
This is similar to BadRequestResult, with the difference that it can pass an object or a ModelStateDictionary containing the details regarding the error.
public BadRequestObjectResult BadRequestObjectActionResult() 

        var modelState = new ModelStateDictionary(); 
        modelState.AddModelError("Name", "Name is required."); 
        return BadRequest(modelState); 


CreatedResult

CreatedResult returns a Created (201) response with a Location header. This indicates the request has been fulfilled and has resulted in one or more new resources being created.
public CreatedResult CreatedActionResult() 
    { 
        return Created(new Uri("/Home/Index", UriKind.Relative), new { FirstName = "Peter", LastName = "Scott" }); 
    } 


CreatedAtActionResult
CreatedAtActionResult that returns a Created (201) response with a Location header.
public CreatedAtActionResult CreatedAtActionActionResult() 
    { 
        return CreatedAtAction("IndexWithId", "Home", new { id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 
    } 


CreatedAtRouteResult
CreatedAtRouteResult that returns a Created (201) response with a Location header.
public CreatedAtRouteResult CreatedAtRouteActionResult() 
    { 
        return CreatedAtRoute("default", new { Id = 2, area = "" }, new { FirstName = "Peter", LastName = "Scott" }); 
    } 


NotFoundResult
This represents a StatusCodeResult that when executed, will produce a Not Found (404) response.
public NotFoundResult NotFoundActionResult() 
    { 
        return NotFound(); 
    } 

NotFoundObjectResult
This is similar to NotFoundResult, with the difference being that you can pass an object with the 404 response.
public NotFoundObjectResult NotFoundObjectActionResult() 
    { 
        return NotFound(new { Id = 1, error = "There was no customer with an id of 1." }); 
    } 


OkResult
This is a StatusCodeResult. When executed, it will produce an empty Status200OK response.
public OkResult OkEmptyWithoutObject() 

return Ok(); 


OkObjectResult

An ObjectResult, when executed, performs content negotiation, formats the entity body, and will produce a Status200OK response if negotiation and formatting succeed.
public OkObjectResult OkObjectResult() 
    { 
        return new OkObjectResult(new { Message="Hello World !"}); 
    } 


NoContentResult

The action result returns 204 status code. It’s different from EmptyResult in that EmptyResult returns an empty 200 status code, but NoContentResult returns 204. Use EmptyResult in normal controllers and NoContentResult in API controllers.
public NoContentResult NoContentActionResult() 
    { 
        return NoContent(); 
    } 


StatusCodeResult

StatusCodeResult accepts a status code number and sets that status code for the current request. One thing to point is that you can return an ObjectResult with and status code and object. There is a method on ControllerBase called StatusCode (404, new {Name = "Peter Scott”}), which can take a status code and an object and return an ObjectResult.
public StatusCodeResult StatusCodeActionResult() 
    { 
        return StatusCode(404); 
    } 



European ASP.NET Core Hosting - HostForLIFE.eu :: Dependency Injection in ASP.NET Core

clock April 28, 2020 08:21 by author Peter

Dependency injection is a software design pattern that enables users to create an application with loosely coupled code. The term 'loosely coupled' means objects that should only have as many dependencies as required to complete their job by decreasing the tight coupling between the software components. Object's dependencies should be on interfaces as opposed to the concrete object. An object is concrete in the sense that it is created with the "new" keyword.

Advantages of Dependency Injection
Easier Maintainability
Greater re-usability

Code is more easily testable with different mock implementation.

Code is cleaner and more readable

There are basically 3 types of Dependency injection in ASP.NET Core:

  • Constructor Injection
  • Method Injection
  • Property Injection

Constructor Injection
Constructor injection is the most common dependency injection used in an application. Constructor injection uses parameters to inject the dependency. It accepts the dependency at the constructor level. It means when instantiating the class, their dependency pass through the constructor of the class.

Implementing Constructor Injection

In the below code, HomeController has a dependency on IEmployeeRepository. We are not creating an object of EmployeeRepository using the new Keyword but we are injecting IEmployeeRepository in Home Controller class using its constructor. This is called constructor injection.
using DependencyInjectionTech.Models; 
using Microsoft.AspNetCore.Mvc; 
namespace DependencyInjectionTech.Controllers { 
    [Route("api/[controller]")] 
    [ApiController] 
    public class HomeController: ControllerBase { 
        private IEmployeeRepository _employeeRepository; 
        // Constructor Injection 
        public HomeController(IEmployeeRepository employeeRepository) { 
                _employeeRepository = employeeRepository; 
            } 
            [HttpGet] 
            [Produces("application/json")] 
        public Employee GetEmployee() { 
            return _employeeRepository.GetEmployee(1); 
        } 
    } 


While running the application, we will get the below error because we have to manually register the interface IEmployeeRepository and its implementation class in the Asp.Net Core dependency injection container. Unless we won't do that process, we will get the below error:

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'DependencyInjectionTech.Models.IEmployeeRepository' while attempting to activate 'DependencyInjectionTech.Controllers.HomeController'.

For registering the interface and its implementation, we have a startup class where we configure the service methods. We make use of the ConfigureServices method to configure the required service for our application. We can use this method to configure in both the ASP.NET Framework Service as well as our application-related custom service. We can make use of the incoming parameter type IServiceCollection of the Configure service method to configure the service.

There are basically 3 methods to register our custom service in the configure service method:
Add Singleton
Add Transient
Add Scoped

The below code in the startup file indicates if any controller (for example HomeController) requests IEmployeeRepository. Then it will automatically create an instance of MockEmployeeRepository class and then inject the instance.
// This method gets called by the runtime. Use this method to add services to the container. 
public void ConfigureServices(IServiceCollection services) { 
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 
    //Registering the interface and its implementation in asp.net core dependency injection container. 
    services.AddSingleton < IEmployeeRepository, MockEmployeeRepository > (); 


Method Injection
Method Injection enables you to inject the dependency into a single method to be only used by that method. We make use of the [FromService] attribute for the method Injection.

Implementing the Method Injection

In the below code, we are implementing the method injection in a single method.
namespace DependencyInjectionTech.Controllers { 
    [Route("api/[controller]")] 
    [ApiController] 
    public class HomeController: ControllerBase { 
        public HomeController() {} 
        //Method Injection 
        [HttpGet] 
        [Produces("application/json")] 
        public Employee GetEmployee([FromServices] IEmployeeRepository _employeeRepository) { 
            return _employeeRepository.GetEmployee(1); 
        } 
    } 
}



European ASP.NET Core Hosting - HostForLIFE.eu :: Flyweight Design Pattern

clock April 21, 2020 07:46 by author Peter

In this post, we will talk about Flyweight design pattern. We will see when one should use this design pattern and how we can implement it. In the below example, we will use C# language to implement the example.

In early days of computing, memory was very costly, but nowadays, it's getting cheaper on a daily basis. Usually, in software application, memory is needed to create and hold objects. Sometimes, some objects stay in memory for a longer period of time. It's the developer’s responsibility to remove the object from memory whenever it's not needed to save memory. Another way to save memory is to use a created object instead of creating a new object each time. This will definitely save memory and improve the performance of the application.
 
To achieve this, we should have a pool of objects where we will keep all newly created objects. Whenever we need the same object, we will query to pool and get that object. After query, if the needed object doesn’t exist in the pool, we will create new one and store it in the pool. In a higher language like C# or Java, we can use Dictionary<Key,Value> or HashTable<Key,Value> to create a pool.
 
Example

Let's add new project. You can give any name you want to it.
Lets create a contract called “IShape” which will be implemented by different shapes.
    internal interface IShape 
        { 
            void Print(); 
        } 


Lets add a “Rectangle” shape.
    internal class Rectangle : IShape 
        { 
            public void Print() 
            { 
                Console.WriteLine("Printing Rectangle"); 
            } 
        } 


Lets add a “Circle” shape.
    internal class Circle : IShape 
        { 
            public void Print() 
            { 
                Console.WriteLine("Printing Circle"); 
            } 
        } 


Lets add “Shapes” enum.
    public enum Shapes 
        { 
            Rectangle, 
            Circle 
        } 


Here's a factory class which will hold all objects in dictionary (hashtable). If the requested object doesn't exist in this list, then it will create it, or else it will return the already created one.
internal class ShapeObjectFactory 

    private readonly Dictionary<Shapes, IShape> shapes = new Dictionary<Shapes, IShape>(); 

    public int TotalObjectsCreated 
    { 
        get { return shapes.Count; } 
    } 

    public IShape GetShape(Shapes shapeType) 
    { 
        IShape shape = null; 
        if (shapes.ContainsKey(shapeType)) 
        { 
            shape = shapes[shapeType]; 
        } 
        else 
        { 
            switch (shapeType) 
            { 
                case Shapes.Rectangle: 
                    shape = new Rectangle(); 
                    shapes.Add(Shapes.Rectangle, shape); 
                    break; 

                case Shapes.Circle: 
                    shape = new Circle(); 
                    shapes.Add(Shapes.Circle, shape); 
                    break; 

                default: 
                    throw new Exception("Factory cannot create the object specified"); 
            } 
        } 
        return shape; 
    } 


Client program
internal class Program 

    private static void Main(string[] args) 
    { 
        var factoryObject = new ShapeObjectFactory(); 

        IShape shape = factoryObject.GetShape(Shapes.Rectangle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Rectangle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Rectangle); 
        shape.Print(); 

        shape = factoryObject.GetShape(Shapes.Circle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Circle); 
        shape.Print(); 
        shape = factoryObject.GetShape(Shapes.Circle); 
        shape.Print(); 

        int NumObjs = factoryObject.TotalObjectsCreated; 
        Console.WriteLine("\nTotal No of Objects created = {0}", NumObjs); 
        Console.ReadKey(); 
    } 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in