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

European ASP.NET Core Hosting - :: 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)    
         select * from wincurd where [email protected]     

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());  
        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());  

European ASP.NET Core Hosting - :: 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 

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 

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")]   
        [EnumMember(Value = "IntentRequest")]   
        [EnumMember(Value = "SessionEndedRequest")]   
        [EnumMember(Value = "CanFulfillIntentRequest")]   
        [EnumMember(Value = "AlexaSkillEvent.SkillPermissionAccepted")]   
        [EnumMember(Value = "AlexaSkillEvent.SkillAccountLinked")]   
        [EnumMember(Value = "AlexaSkillEvent.SkillEnabled")]   
        [EnumMember(Value = "AlexaSkillEvent.SkillDisabled")]   
        [EnumMember(Value = "AlexaSkillEvent.SkillPermissionChanged")]   
        [EnumMember(Value = "Messaging.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,
    public class SamplePoco 
        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); 
    string xmlOut = output.ToString();  

This generates the following XML,
    <?xml version="1.0" encoding="utf-16"?><SamplePoco xmlns:i="" xmlns=""><RequestType>AlexaSkillEvent.SkillDisabled</RequestType> 

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() 
                    .GetCustomAttributes(typeof(EnumMemberAttribute), false) 
                    .SingleOrDefault() as EnumMemberAttribute; 
                return attribute == null ? value.ToString() : attribute.Value; 
    #if NETSTANDARD1_6 || NETSTANDARD1_3 || NET45 || NET47 
                EnumMemberAttribute attribute = value.GetType() 
                    .GetCustomAttributes(typeof(EnumMemberAttribute), false) 
                    .SingleOrDefault() as EnumMemberAttribute; 
                return attribute == null ? value.ToString() : attribute.Value; 
                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]; 
            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); 

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,
    public class SamplePoco 
        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,

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

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 - :: 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] 
    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.
    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,
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.
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 . 

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 = []; 
                    type: "POST", 
                    url: "../Home/GetText", 
                    data: "{}", 
                    contentType: "application/json; charset=utf-8", 
                    dataType: "json", 
                    async: true, 
                    success: function(result) { 
                        $.each(result, function(key, item) { 
                        loadChart(Complainletteryear, Total, concluded, N_concluded); 
                    error: function(errormessage) { 
                        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:' 
                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">{}: </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
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.

About 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.

Tag cloud

Sign in