Talent without working hard is nothing.


Google Charts with ASP.NET MVC5

How to use Google Chart in your ASP.net MVC Project.

I will explain 2 ways .

1- return data with ViewBag .

2- Using JSON .

Code with ViewBag .

C# Code :

 public ActionResult GetChart()        {                       var result =// here Your Data From SQLServer As List                       var datachart = new object[result.Count ];                     int j = 0;            foreach(var i in result)            {                              datachart[j] = new object[] { i.CategoryName.ToString(), i.Frequence };                j++;            }            string datastr = JsonConvert.SerializeObject(datachart, Formatting.None);            ViewBag.dataj =new HtmlString(datastr);                                                          return View();        }


HTML Code:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><script>    var data1 = '@ViewBag.dataj';    var datass = JSON.parse(data1);   </script><script type="text/javascript">      // Load the Visualization API and the corechart package.      google.charts.load('current', {'packages':['corechart']});      // Set a callback to run when the Google Visualization API is loaded.      google.charts.setOnLoadCallback(drawChart);      // Callback that creates and populates a data table,      // instantiates the pie chart, passes in the data and      // draws it.      function drawChart() {          // Create the data table.        var data = new google.visualization.DataTable();        data.addColumn('string', 'CategoryName');        data.addColumn('number', 'Frequence');        data.addRows(datass);        // Set chart options        var options = {'title':'Categories',                       'width':400,                       'height':300};        // Instantiate and draw our chart, passing in some options.        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));        chart.draw(data, options);      }</script><div id="chart_div"></div>



Second one , With Ajax :

   [WebMethod]        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]        public  JsonResult GetChartData()        {            var result = //Your Data From SQL Server as List             var chartData = new object[result.Count + 1];            chartData[0] = new object[]{                    "CategoryName",                    "Frequence"                };            int j = 0;            foreach (var i in result)            {                j++;                chartData[j] = new object[] { i.CategoryName.ToString(), i.Frequence };            }            // return chartData;            return Json(chartData,JsonRequestBehavior.AllowGet);        }

HTML Code :

<script src="~/scripts/jquery-3.1.1.js"></script> <%-- Here We need to write some js code for load google chart with database data --%><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><script>                var chartData; // globar variable for hold chart data              //  google.load("visualization", "1", { packages: ["corechart"] });                google.charts.load('current', { 'packages': ['corechart'] });                // Here We will fill chartData                $(document).ready(function () {                    $.ajax({                        url: "GetChartData",                        data: "",                        dataType: "json",                        type: "POST",                        contentType: "application/json; chartset=utf-8",                        success: function (data) {                                                       chartData = data;                        },                        error: function () {                            alert("Error loading data! Please try again.");                        }                    }).done(function () {                        // after complete loading data                        google.setOnLoadCallback(drawChart);                        drawChart();                    });                });                    function drawChart() {                    var data = google.visualization.arrayToDataTable(chartData);                    var options = {                        title: "Categories",                        pointSize: 5                    };                    var pieChart = new google.visualization.Bar(document.getElementById('chart_div'));                    pieChart.draw(data, options);                }</script><div id="chart_div" style="width:500px;height:400px">    <%-- Here Chart Will Load --%></div>



You can find more in my Youtube Channal .





Read more..


How to write Text over Image Using HTML and CSS.

It's very simple , just you need a bit of CSS  coding .

our HTML Code will be Image and text 

<div class="imagestyle">    <img src="Your Image Path" />    <div class="textstyle">You Text</div></div>

as we see in the code first dive is the continner for both of the Image and Text .

CSS code :

.imagestyle {       position: relative;}.textstyle {   position: absolute;   top: 45%;   text-align:center;   width: 100%;   margin: 0 auto;   width: 100%;   height: auto;   color: white;    font-size: 1.6vw;}



Example :


Read more..

Methods are very useful in C#. Since any code is to be used at many places, we can define that in a method and can use the code only by calling that method .

Method signature

A method signature contains various things, which are stated below.

[Attributes]    (e.g.: [WebMethod],[HttpPost],[HttpGet])Public void TestMethod(string parameters)


       In the method shown above, Public signature defines the Access modifier.

       Void defines the no return type (in case of void, No return type is there and In case of string, its string) of the method.

       If the return type is defined as string, then the method must return some string as its output. If we do not want a method to return anything, we can define it as void.


It defines the name of that method.

The string parameters defines the parameter that this method will expect during a call. 


 class Program      {  public static void Main(string[] args)          {    InstanceMethodClass  p = new InstanceMethodClass();              p.InstanceMethod();  }    }    public class InstanceMethodClass      {  //This is an Instance method.  public void InstanceMethod()          {              Console.WriteLine("This is a test instance method.");          }  } 

Static Method

We do not need to create the object of the class in which method is defined. We can invoke the method by using it directly.

class Program      {          public static void Main(string[] args)          {              ClassForStaticMethod.StaticMethod();          }  }     public class ClassForStaticMethod      {             public static void StaticMethod()          {               Console.WriteLine("This is a test static method.");          }      }  

Let's take an example of method with the parameters.

In the example shown above, we need to pass a string argument because "PrintParameter" method expects the string as parameter.

Let's take an example of return type method.

class Program      {          public static void Main(string[] args)          {  InstanceMethodClass i=new InstanceMethodClass();  i.PrintParameter("Argument passed.");  }  }   public class InstanceMethodClass{      public void PrintParameter(string parameter)          {              Console.WriteLine(parameter);          }  }  

In the example shown above, we need to pass a string argument because "PrintParameter" method expects the string as parameter.

Let's take an example of return type method.

class Program      {          public static void Main(string[] args)          {  InstanceMethodClass i=InstanceMethodClass();   int sum=i.ReturnSum(2,6);              Console.WriteLine(sum);    }  }     public class InstanceMethodClass      {  public  int ReturnSum(int a,int b)          {              int sum = a + b;              return sum;          }  }  

In the example shown above, we used int as return type instead of void. Thus, the method must return an integer. When we invoke this method, we can get the returned result in an Int variable.

In the two examples stated above, it will remain the same for static method but the only difference is the method needs to be defined as static and invoked without using a class instance. 

Thank you.

Source c-sharpcorner , MSDN

Read more..

Triming String in C# , some times we need it for white speaces or

cut some characters from our text.

there is 3 methods :




Removes trailing punctuation and white-space characters from the current String object.




The following example uses the TrimStart method to trim white space.

string str="ABC  ";

string trimedStr=str.TrimEnd();

Result will be : "ABC".

Same we can use TrimStart() method to trim and characters  we dont need .

one more Example :

I we need to trim two characters in the same time :

string lines="// This code displays a simple greetingsring newLine=line.TrimStart(' ', '/');


Example with Array:


string[] items = new string[] { "MyBlog?", "Hi..." };

// Loop and call TrimEnd.

foreach (string item in items)

{ string trimmed = item.TrimEnd('?', '.');    //Here will remove (?  and . ) 



Result :




I wish this simple code is useful 

Read more..

Web.config File - ASP.NET MVC

I am going to explain about  Add/Update appSettings  in the Web.config file and how you can configure them to use in the application.

The simple following method from MDSN help you to read  any Key you sent it .

 public string  ReadSetting(string key)
          var appSettings = ConfigurationManager.AppSettings;
           string result = appSettings[key] ?? "Not Found";
           return result;

Last code ReadSetting , Just give your Key As String , will return the Value , if your key not exist will return to you "Not Found" String .


Add Key:

the next code will Add new Key with Value you give , but if there is any key is exist same as you add , just will Update the Value .

 static void AddUpdateAppSettings(string key, string value)
             var configFile = WebConfigurationManager.OpenWebConfiguration("~/");
              var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                    settings.Add(key, value);
                    settings[key].Value = value;


After Add/Update your key , late say you need to use the Value some where in you C# code ,

Just use  it like the following Code :

String Str =ReadSetting(YourKey);

The question , how to read it  at Razor ??

Same way how we wrote it ReadSetting Method with some change ,

First add  System.Configuration to your References ,add it to your page :

 @using System.Configuration;

    string  _YourValue = ConfigurationManager.AppSettings["YourKey"];

I wish you find this post useful .

Read more..