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

Thursday

URL Access: How to Prevent Direct URL Access In MVC

Introduction

Here is writing another article to make more secure of your MVC application. I’ll explore all aspects here, how to prevent direct URL access in MVC application. Before to go through this article, you are required to detail about these articles as given below.
  1. Asp.net mvc session management example
  2. Prevent Cross-Site Request Forgery using AntiForgeryToken() in MVC

Namespace Used

To apply this feature into your MVC application is used System.Web.Routing namespace to prevent direct URL access in MVC.
How to Prevent Direct URL Access In MVC

using System.Web.Routing

Apply this feature in FilterConfig.cs file

We have to call this feature under OnActionExecuting of Action filter. We have to apply filter as below written lines to prevent direct URL access in MVC. If we are tempering URL in browser then it will forcibly throw you to Logout action of Home Controller lying under Main area.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class NoDirectAccessAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.UrlReferrer == null ||
 filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
        {
     filterContext.Result = new RedirectToRouteResult(new
                               RouteValueDictionary(new { controller = "Home", action = "Logout", area = "Main" }));
        }
    }
}

Prevent Direct Access to Class (Apply on Controller Class)

We can apply NoDirectAccess Attribute to Class and it will follow to all containing methods, if any methods accessed directly under the whole controller. It will throw you specified action (here’s throwing Logout action) like MyWebsiteURL.com/Main/PersonalDetail/Index

[NoDirectAccess]
public class PersonalDetailController : Controller
{
      //
      // GET: /Main/PersonalDetail/
      public ActionResult Index()
      {
          return View();
      }
}

Apply NoDirectAccess Attribute to Action

Alternatively, we can apply NoDirectAccess Attribute to specific Action rather than to whole Controller class. Suppose, we are accessing directly like MyWebsiteURL.com/Main/Home/login

[NoDirectAccess]
public ActionResult Login()
{
   return View();
}

Conclusion

I have here demonstrated all necessary steps to prevent direct URL access in MVC to make our MVC application more secured and robust over internet. These are the healthy features to make our MVC application more reliable across the internet.

Tuesday

MVC Session: Asp.net mvc session management example

Introduction

In this example, showing how to use and validate session (HttpContext.Current.Session) in MVC application. In my earlier article, one of more secured feature to keep up your website healthy cross-site request forgery explained. MVC application has provided us facility to apply filter like
  1.  Authorization 
  2.  Action Filter 
  3.  Result Filter 
  4.  On Error Filter
I am here applying OnActionExecuting filter helps us to manage ASP.net MVC session management whether session is preserving or not, if session is expired, it will not let you access your authorised area and throw away to login area or someone page.
Asp.net mvc session management example

Add below code in FilterConfig.cs under App_Start folder

This code is written under OnActionExecuting in FilterConfig.cs file
public class UserSessionActionFilter : ActionFilterAttribute, IActionFilter
{
    public override void OnActionExecuting(ActionExecutingContext filterContextORG)
    {
        HttpContext ctx = HttpContext.Current;
        if (HttpContext.Current.Session["User"] == null)
        {
            /// this handles session when data is requested through Ajax json
            if (filterContextORG.HttpContext.Request.IsAjaxRequest())
            {
                JsonResult result = new JsonResult { Data = "Session Timeout!" };
                filterContextORG.Result = result;
            }
            else
            {
                /// If session is expired then redirected to logout page which further redirect to login page. 
            filterContextORG.Result = new RedirectResult("~/Main/Home/Logout");
                return;
            }
        }
}

In Global.asax Should register FilterConfig.cs

protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();
 WebApiConfig.Register(GlobalConfiguration.Configuration);
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
}

Checking Session is expired or not

We have to call action attribute [UserSessionActionFilter] in MVC controller to check whether session is preserving or not. If session is expired it will throw to other page.
[UserSessionActionFilter]
public ActionResult ContactDetail()
{
 return View();
}

Conclusion

This example is showing how to handle session in ASP.net MVC application. This example helps us to asp.net MVC session management example with all required steps.

Suggested Reading

Thursday

MVC Areas: Organizing an Application using Areas

Introduction

MVC architecture is inherently separated into three separate layers like Model (database), Presentation (UI, View), and Controller (Business layer). Releasing of MVC 2 introduces new feature of Area which provide solid capability to further separate files of file structure. Using with Area, we can define same controller in different areas to make our application more modular, manageable and robust. In this demonstration, I have used two areas Main (Public website) and blog area. In my earlier article, how to stop cross-site request forgery. I am explaining all steps how to organizing an application using areas in MVC.
mvc area

Why We Need MVC Areas

When we need multiple departments to maintain with different controllers even having with the same name in different areas. It makes our application more manageable, easy and maintainable to make our development faster.

Create a New MVC Project

First of all, create a new fresh project of MVC

create new project mvc area

New Project Crated

New project created for playing MVC feature of Area.

new project created

Create a New Area

Let’s now start to create a new area. Right click on project then move to Add >>> Area then provide a new relevant name of area.
Create mvc area

Creating Blog Area

Here typing relevant new area name like “Blog”.
type blog area name

Blog Area Created

Now you can see new created area “Blog” under the project.
Area Blog Created

Blog Area File Registration

You can see a new file crated of Blog Area Registration (BlogAreaRegistration.cs) under blog area.

public override string AreaName
{
    get
    {
 return "Blog";
    }
}

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute("Blog_default",
        "Blog/{controller}/{action}/{id}",
 new { action = "Index", id = UrlParameter.Optional }
    );
}

Area Registration in Global.asax

Area registration is also done in Global.asax file.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
} 

Main Area Creation

Next one new main area is crating in this section.
Main blog area created
Area Registration File Created
In the same way, as in blog area a registration file (MainAreaRegistration.cs) is also created.

public class MainAreaRegistration : AreaRegistration
{
 public override string AreaName
        {
        get
        {
            return "Main";
        }
    }

public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Main_default",
            "Main/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }

Create Home Controller for Main Area

Creating home controller under main area.
Home controller for main area

Create Home Controller For Blog

Alike main area, Home controller is also creating under blog area. Area feature let allow us to create same controller name to make our development more lucrative.
Home controller for blog area

Create View for Both Home controllers of Main & Blog

Here is creating view for Blog and main area.

@{
ViewBag.Title = "Index";
}
<h2>Welcome to Blog Area</h2>
<div> @Html.ActionLink("Back to Main", "Index", "Home", new { area = "Main" }, new { }) </div>
 Main Area View
@{ ViewBag.Title = "Index"; }
<h2>Welcome to Main Area</h2>
<div>
    @Html.ActionLink("Go to Blog", "Index", "Home", new { area = "Blog" }, new { })
</div>

Set Default Area/Controller/Action

Here, you can set your default area, controller and method to launch your application (landing page of your application). Before to set, you need to right click on project and click on properties to navigate on Web tab to set application default page (Area/controller/action).

Area Default Page

or Alternatively can set in RouteConfig.cs

Routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { "slnMvcArea.Areas.Main.Controllers" }
            ).DataTokens.Add("area","Main");

Now Run your MVC area application

Finally run your MVC app to see how works MVC area feature.

welcome to main area

Navigate to Blog Area

Click on “Go to Blog” to navigate blog area.

welcome to blog area
Now you are on blog area, here is also a link to navigate “Back to Main”.

Conclusion

MVC areas helps us to make more manageable our MVC application to further divides into different files. In each area, we can define same controller like Main area contain “Home” Controller then also other areas can contain same area name “Home”, this code will compile perfectly even we have same controller name in different areas. Thus, it will help us to make large volume of applications with multiple departments so that can build awesome MVC apps with area feature. I tried here to demonstrates all necessary steps to organize an application using areas in MVC app.

Video: This video also demonostrates about Organizing an Application using Areas.

Saturday

Text to Speech: Download free Text to Speech Software

Introduction

Free Text to Speech software is empowered with rich functionality to read any text format into speech/voice.

Free Text to Speech Software Version (1.8.0.0)

Most Popular Supporting Windows Environment

Windows 10

  • Windows 10 Home
  • Windows 10 Pro
  • Windows 10 Enterprise
  • Windows 10 Enterprise LTSB
  • Windows 10 Education

Windows 8

  • Windows 8.1
  • Windows 8.1 Pro
  • Windows 8.1 Enterprise
  • Windows 8
  • Windows 8 Pro
  • Windows 8 Enterprise
  • Windows 8 OEM

Windows 7

  • Windows 7 Home Basic
  • Windows 7 Home Premium
  • Windows 7 Professional
  • Windows 7 Enterprise
  • Windows 7 Ultimate
  • Windows Thin PC
  • Windows Vista Home Basic
  • Windows Vista Home Premium
  • Windows Vista Business
  • Windows Vista Enterprise
  • Windows Vista Ultimate

Windows XP

Text to Speech/Voice Supporting Languages

  • English
  • Spanish
  • French and other European languages.

System Requirements

This is light weight programming it will keep running at any PC with least prerequisites with taking after segments Processor, RAM, Hard Drive Space, Graphics card, Sound Card, PC Speakers, Display and so forth.

Feedback

Your input is essential for me with the goal that continue sending your profitable criticism to include new usefulness in this product. In not so distant future, you will see more usefulness in this product.
Download Free Text to Speech

Dependency

Download Free Microsoft .NET Framework 4.5 if not already installed on your computer.

Pros


  • It is very lightweight software.
  • It consumes very little storage of your computer.
  • It is one click software to install on your computer.

Cons


  • It covers only Windows Operating system.

Steps to Install Free Text to Speech Software

Step #1: First of all download Setup from given link here and end of the article. Now unzip folder and start setup  on click Setup_Speech_Text
text to speech setup file

Step #2: Now you can see progress installing your free text to speech software.
text to speech installing progress

Step #3: Once finished installing process. Finally hit Finish button to complete your installation process.
install text to speech finish

Step #4: Now check your Windows desktop icon where your fee text to speech software already installed.
text to speech desktop icons in windows 10

Step #5: From very left, click on first icon, a new window will open where you can write or copy/paste text to read from text to voice. Finally click on Read Now button to start reading your text.
text to speech read now button

Step #6: Next icon will open a new window where you can send your suggestions to make this software more powerful.
text to speech suggestions box

Step #7: Last icon will open this software basic information.
text to speech info software


Download Free Text to Speech Software
Download

Suggested Reading

.Net OOPS: OOPS interview questions

Introduction (OOPS)

OOPS Programming allows us to develop smaller to smaller logical modules, later we can integrate into one form of software. OOPS includes classes under that methods, entities, events, properties, modules etc. By creating objects can access data in OOPS programming. .Net framework supports only OOPS languages such as vb.net, c#, asp.net, C++ etc. In my earlier example, I have covered almost all MVC ASP.Net Interview Questions And Answers.

1) What is class in .Net OOPS Programming?

Access modifiers allows us to access its class members in different types like Public, Private, Protected, Internal, Protected internal, Static.
Class Inheritance allow us to do to access its base class information and behaviour. Colon image permits us to inherit its base class from derive class.
public class Furniture
    {
        //Fields, properties, methods, members, events, constructors, destructors etc.
    }

2) What is Class and Class Inheritance in OOPS Programming?

public class Furniture
    {
        //Fields, properties, methods, members, events, constructors, destructors etc.
    }
 Public class Sandal:Furniture
    {
        //Fields, properties, methods, members, events, constructors, destructors etc.
    }

3) What are objects in OOPS?

Objects are like variable those who enable to encapsulate data and behaviour
Furniture _obj = new Furniture();

4) What are the basic concepts of OOPS ?

Main top four main features of OOPS are as follows:
I) Abstraction:- In .net framework, abstraction enable to use multiple inheritance, with the access of abstraction can hide important data and show only important data to show user.
II) Polymorphism: It capable to use one form into multiple forms.
II) Encapsulation: We can say encapsulation is subset of abstraction. We can restrict user to show data with the use of encapsulation.
IV) Inheritance: While we are using inheritance there are two main parts one is derived class and other one is base class. Inheritance provides to capable our application to reuse our code and reduce code size.
oops main components
OOPS main components

5). Which of the following type of class allows only one object of it to be created?

  • Virtual class
  • Abstract class
  • Singleton class
  • Friend class

6). Which of the following statements is correct?

  • Base class pointer cannot point to derived class.
  • Derived class pointer cannot point to base class.
  • Pointer to derived class cannot be created.
  • Pointer to base class cannot be created.

7). Which of the following is not the member of class?

  • Static function
  • Friend function
  • Const function
  • Virtual function

8). Which of the following concepts means determining at run time what method to invoke?

  • Data hiding
  • Dynamic Typing
  • Dynamic binding
  • Dynamic loading

9). Which of the class’s instances themselves are classes?

  • Subclass
  • Abstarct Class
  • Metaclass
  • Object Class

10). Which of the following concept of oops allows compiler to insert arguments in a function call if it is not specified?

  • Call by value
  • Call by reference
  • Default arguments
  • Call by pointer

11). Which of the following cannot be friend?

  • Function
  • Class
  • Object
  • Operator function

12). Which of the following concepts of OOPS means exposing only necessary information to client?

  • Encapsulation
  • Abstraction
  • Data hiding
  • Data binding

13). Why reference is not same as a pointer?

  • A reference can never be null.
  • A reference once established cannot be changed.
  • Reference doesn't need an explicit dereferencing mechanism.
  • All of the above.

14) Initialise var to null in C# ?

  • var _myVal = (dynamic)null; 
  • var _myVal = (int32)null; 
  • var _myVal = (int)null; 
  • var _myVal = (string)null; 
  • None;

15) What is Mutable string in .Net framework OOPS? 

  • A mutable string state can't be change 
  • A mutable string state can be change 
  • None 

16) What is Immutable string in .Net framework OOPS?

  • A Immutable string state can't be change 
  • A Immutable string state can be change
  • None
Read More: Difference between mutable and immutable string in .Net framework

17) What is boxing ?

  • Object to value 
  • Value to object 
  • Both A and B 
  • None
int a = 123;
object o = a;  //boxing

18) What is unboxing ? 

  • Object to value 
  • Value to object 
  • Both A and B 
  • None
o = 123;
a = (int)o;  // unboxing
Read More: What is Boxing and Unboxing in .Net Framework

19) Which modifier is used to class as a sealed class? 

  • Protected 
  • Private 
  • Sealed 
  • None 

20) A sealed class cannot be used as a base class? 

  • Yes 
  • No 
  • None 

21) Can be use sealed class as an abstract class? 

  • Yes 
  • No 
  • None 

22) Can be use sealed class for inheritance?

  • No 
  • Yes 
  • None 

23) Can be structs considered like sealed class? 

  • No 
  • Yes 
  • None
public sealed class Csharp
{
    // Class members here.
}

24) Can we instantiate Interface class ? 

  • Interface can be instantiated 
  • Interface cannot be instantiated 
  • Both A and B 
  • None 

25) Does Interface class require inheriting ?

  • No 
  • Yes 
  • None 

26) Which keyword is used to class as a sealed class?

  • Protected 
  • Private 
  • Sealed 
  • None 

 27) Does Interface class support inheriting?

  • Yes 
  • No 
  • None 

28) Can Interfaces contain only the declaration of the members?

  • Yes 
  • No 
  • None 

29) Which keyword is required to make Interface class?

  • Keyword
  • Sealed 
  • Interface
  • None

30) Interface class can contains only properties, indexers, methods, delegates and events signature?

  • No 
  • Yes 
  • None 

31) Can we instantiate abstract class?

  • No 
  • Yes 
  • None 

32) Can be an abstract class as a sealed class?

  • No
  • Yes
  • None

33) Can be an abstract class inherited from more than one class?

  • No 
  • Yes 
  • None 

34) An abstract class can contain constructors and destructor?

  • No 
  • Yes 
  • None 

35) Can it an abstract method likely implicitly virtual method?

  • No 
  • Yes 
  • None

Conclusion (OOPS)

OOPS provides great capability with Re-usability, Inheritance, Data Hiding, Reduced complexity of a problem, Easy to Maintain and Upgrade, Modifiable and Message Passing to develop high quality software with cost cutting.

OOPS, IIS and Other ASP.Net Interview Questions and Answers:

MVC Charts: How to create charts using MVC

Introduction

Already explained how to send SMS using C# in my previous article, here explaining about MVC Charts. Chart Helper is an outstanding option to show your data in graphical representation. The Chart Helper shows data in image in different chart types like Funnel, Bar Chart, Pie, Column, Candlestick, Doughnut, StackedBar100, BoxPlot, Pyramid, Polar, Radar, RangeBar etc. Chart Helper can show more than 30 chart types in MVC C#. Here, I are explaining main properties of Charts like Height, Weight, Title, Series and then finally write charts into output bmp file. In this sample, I will show how to create charts using MVC.

Database Script

CREATE TABLE [dbo].[tblMVCCharts](
 [ChartID] [int] IDENTITY(1,1) NOT NULL,
 [Growth_Year] [int] NULL,
 [Growth_Value] [float] NULL
) ON [PRIMARY]


insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2008,50)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2009,70)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2010,80)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2011,90)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2012,120)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2013,150)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2014,100)
insert into [dbo].[tblMVCCharts] (Growth_Year, Growth_Value) values (2015,300)

Namespace

using System.Web.Helpers;

Height-Weight

We can increase-decrease chart height and weight as per your customisation requirements

Title

Here we can put title of the chart.

Series

In series property, Series is very required property to provide data (X & Y series) to generate into graphical form. We need to provide data for X (Horizontal) and Y (Vertical) series to show data in graphical representation, that is what we need to extract from our data into chart in MVC.

Write

Write properties is finally convert our data into image form to output in to BMP file.
Every chart necessarily requires values for x and y for similar collection of information. Here are showing growth overs years values for X and Y.

Controller Action Column Chart

public ActionResult CharterColumn()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Column Chart]")
   .AddSeries("Default", chartType: "column", xValue: xValue, yValues: yValue)
          .Write("bmp");

    return null;
}

Razor View Column Chart

<img src="@Url.Action("CharterColumn")" alt="Chart" />

Column Chart Output

Column Chart

Controller Action Bar Chart

public ActionResult ChartBar()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Bar Chart]")
            .AddSeries("Default", chartType: "Bar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Bar Chart

<img src="@Url.Action("ChartBar")" alt="Chart" />

Bar Chart Output

Bar Chart

Controller Action Pie Chart

public ActionResult ChartPie()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Pie Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Pie", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Pie Chart

<img src="@Url.Action("ChartPie")" alt="Chart" />

Pie Chart Output

Pie Chart

Controller Action Three Line Break Chart

public ActionResult ChartThreelinebreak()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    /// SeriesChartType.Candlestick
    new Chart(width: 600, height: 400, theme: ChartTheme.Vanilla3D)
    .AddTitle("Chart for Growth [Three Line Break Chart]")
            .AddSeries("Default", chartType: "Candlestick", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Three Line Break Chart

<img src="@Url.Action("ChartThreelinebreak")" alt="Chart" />

Three Line Break Chart Output

Three Line Break Chart

Controller Action Bubble Chart

public ActionResult Bubblebreak()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Bubble
    .AddTitle("Chart for Growth [Bubble Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Bubble", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Bubble Chart

<img src="@Url.Action("Bubblebreak")" alt="Chart" />

Bubble Chart Output

Bubble Chart

Controller Action Doughnut Chart

public ActionResult DoughnutGraph()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Doughnut
    .AddTitle("Chart for Growth [Doughnut Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Doughnut", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Doughnut Chart

<img src="@Url.Action("DoughnutGraph")" alt="Chart" />

Doughnut Chart Output

Doughnut Chart

Controller Action StackedBar100 Chart

public ActionResult ChartStackedBar100()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.StackedBar100
    .AddTitle("Chart for Growth [StackedBar100 Chart]")
            .AddSeries("Default", chartType: "StackedBar100", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View StackedBar100 Chart

<img src="@Url.Action("ChartStackedBar100")" alt="Chart" />

StackedBar100 Chart Output

StackedBar100 Chart

Controller Action BoxPlot Chart


public ActionResult ChartBoxPlot()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.BoxPlot
    .AddTitle("Chart for Growth [BoxPlot Chart]")
            .AddSeries("Default", chartType: "BoxPlot", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View BoxPlot Chart

<img src="@Url.Action("ChartBoxPlot")" alt="Chart" />

BoxPlot Chart Output

BoxPlot Chart

Controller Action Pyramid Chart


public ActionResult ChartPyramid()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Pyramid
    .AddTitle("Chart for Growth [Pyramid Chart]")
            .AddLegend("Summary")
            .AddSeries("Default", chartType: "Pyramid", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Polar Chart

<img src="@Url.Action("ChartPyramid")" alt="Chart" />

Pyramid Chart Output

ChartPyramid

Controller Action Polar Chart

public ActionResult ChartPolar()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Polar
    .AddTitle("Chart for Growth [Polar Chart]")
            .AddSeries("Default", chartType: "Polar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Polar Chart

 <img src="@Url.Action("ChartPolar")" alt="Chart" />

Radar Chart Output

Polar Chart

Controller Action Radar Chart

public ActionResult RadarChart()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Radar
    .AddTitle("Chart for Growth [Radar Chart]")
            .AddSeries("Default", chartType: "Radar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Radar Chart

<img src="@Url.Action("RadarChart")" alt="Chart" />

Radar Chart Output

Radar Chart

Controller Action RangeBar Chart

public ActionResult ChartRangeBar()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)
            
    /// SeriesChartType.RangeBar
    .AddTitle("Chart for Growth [RangeBar Chart]")
            .AddSeries("Default", chartType: "RangeBar", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View RangeBar Chart

<img src="@Url.Action("ChartRangeBar")" alt="Chart" />

RangeBar Chart Output

RangeBar Chart

Controller Action Funnel Chart

public ActionResult ChartFunnel()
{
    var _context = new TestEntities();

    ArrayList xValue = new ArrayList();
    ArrayList yValue = new ArrayList();

    var results = (from c in _context.tblMVCCharts select c);

    results.ToList().ForEach(rs => xValue.Add(rs.Growth_Year));
    results.ToList().ForEach(rs => yValue.Add(rs.Growth_Value));

    new Chart(width: 600, height: 400, theme: ChartTheme.Green)

    /// SeriesChartType.Funnel
    .AddTitle("Chart for Growth [Funnel Chart]")
    .AddLegend("Summary")
            .AddSeries("Default", chartType: "Funnel", xValue: xValue, yValues: yValue)
            .Write("bmp");

    return null;
}

Razor View Funnel Chart

<img alt="Chart" chartfunnel="" src="@Url.Action("ChartFunnel") />

Funnel Chart Output

Funnel Chart

Conclusion

Charts help us to represent data into graphical form from tabular data. MVC charts have been provided facility to represent data into different charts. We can analyse data minutely with the help of MVC charts to take up comparative decisions. Hopefully, above all charts will help everyone to represent data in to many ways in your web app. I tried here how to create charts using MVC with detailed example and also attached a working sample with database.

Download Working Sample

Download
Note: Change Connection String in web.config before to run this working sample of MVC Charts.

Video: How to create charts using MVC

Suggested Reading

SMS API: How to send SMS using C#

Introduction

SMS stands for Short Message Service is widely used to communicate to another mobile devices. Earlier, provided resolution to resolve issue Authentication the Server Response was 5.5.1 Authentication required in gmail, now today explaining how to send SMS using C#. We can send SMS up to 160 characters through our mobile devices. Long message can split up into small multiple parts automatically. On mobile device can send text message only. Here, I am exposing how to send text SMS (Short Message Service) using c# code.
  1. First of all. We need to create an URL to send text message on mobile device.
  2. We require web or IP address with parameters like username, password, recipient, senderid, text message and response etc.
  3. Parameters can vary depend on SMS provider service. Providers provide complete information to send SMS.
  4. Now we need to create web request to send SMS using C# code.
  5. We can also track response after sending text message on mobile device.
SMS API
Fig: SMS API

Code Snippet


public ActionResult SendSMSInCsharp()
{
    //we creating the necessary URL string:
    string _URL = "192.168.1"; //where the SMS Gateway is running
    string _senderid = "TESTTC";   // here assigning sender id 
            
    string _user = HttpUtility.UrlEncode("TestSMS"); // API user name to send SMS
    string _pass = HttpUtility.UrlEncode("123456");     // API password to send SMS
    string _recipient = HttpUtility.UrlEncode("9999999999");  // who will receive message
    string _messageText = HttpUtility.UrlEncode("testing sms..."); // text message

    // Creating URL to send sms
    string _createURL = _URL + 
    "username =" + _user +
       "&pass=" + _pass +
       "&senderid=" + _senderid +
       "&dest_mobileno=" + _recipient +
       "&message=" + _messageText;

    try
    {
        // creating web request to send sms 
        HttpWebRequest _createRequest = (HttpWebRequest)WebRequest.Create(_createURL);
        // getting response of sms
        HttpWebResponse myResp = (HttpWebResponse)_createRequest.GetResponse();
        System.IO.StreamReader _responseStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
        string responseString = _responseStreamReader.ReadToEnd();
        _responseStreamReader.Close();
        myResp.Close();
    }
    catch
    {
        //
    }
    return View();
}

Conclusion

SMS (Short Message Service) is now used across the world through mobile devices to instant communication medium. In this article, demonstrated explained all steps to send SMS using C# code. You can send SMS through this code in ASP.Net, MVC using C# code.

Suggested Reading

SQL Table Size: How to Get Database tables size in sql server

Introduction

In Last article, I have explained very known SQL Server Error 25 And 87, here going to fully explain how to get database tables size in SQL server. Tables stores information in rows and columns in database. I am here explaining how to check tables storage in SQL database. This is very important to check database tables storage to optimise our application performance. Explaining all steps to check our database tables storage in single command. Here, you can see how to get all database tables size with detail.

Solution I (Shows usage one by one table)

1. Open your SQL Server Management Studio and login into your database.
2. Now navigate to Query Analyser (Ctrl + N).
3. Then now write given T-SQL command select 'exec sp_spaceused ' + TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE' in query analyser.

database table list

4. Now copy all records from result window.
5. Again now open a New Query (Ctrl + N) Analyser and paste all records copied from result window.
6. Next select option from top toolbar Results to File (Ctrl + Shift + F).


7. Now hit button Execute (F5) from top toolbar to run T-SQL command to store all database tables storage stats into a report file (.rpt).
8. Now open file saved into your machine hard drive to check the database tables storage stats. This file contains given columns  name (name of table), rows (total rows in table), reserved (reserved space), data (stored data size), index_size (total indexed size), unused (shows unused data).

tables space used file

Solution II (Consolidated Database Usage)

1. Open your SQL Server Management Studio and Right click on Database.
2. Now navigate to Reports >> Standard Reports >> Disk Usage.

Disk Usage Report
3. You will see here showing consolidated data usage detail Total Space Usage, Data Files Space Usage, Transaction Log Space Usage with graphical representation.

Total Space Usage

Conclusion

Database is soul of our application so it requires well-tuned, managed and optimised to run our application superbly. Here, I have managed all steps to get database tables size in SQL server so that we can manage accordingly.

Relevant Reading

Publish APP: Copying file failed in publish using Visual Studio

Introduction

I have already written an articles on how to publish web application in IIS using visual studio. Today, I am writing a very known issue Copying file failed in publish using Visual Studio, it comes issue while deleted files remained in visual studio solution. I am in this article demonstrating below how to get rid of this issue.

Monday

Fix Error: Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies

Introduction

Today, I am going to explain a MVC application error while our application is interrupted or closed properly. This might be arise a major issue in our build causes delay to deploy our MVC app.

Error Description

Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies

Reasons

This issue comes when our power failure and resulted into our application is not closed down properly.
Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies

Figure: Could not load file or assembly

Step 1

Press Windows + Run and then type %temp%

Step 2

Now delete all temporaries files located at your machine C:\Users\user1\AppData\Local\Temp,

Using with above 2 steps helped me to resolve issue Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies while working on MVC application.

Conclusion

I have explained MVC error Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies, how it comes, reasons behind it and provided all necessary steps to resolve issue Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies. Relevant MVC Fixes

Suggested Reading

Friday

Jquery MVC: Upload Image using jquery MVC

Introduction

Image Upload is very important work in our web application. It is most orderly needed whereas registering profile somebody with profile image, making album etc. I have explained during this article, how to upload image in MVC application (Razor Engine) using Jquery and preview image instantly. Image Uploading is gorgeous task of your application whenever search somebody image, if profile image is blur or heavy image then it'll increase your process time, blur image will lead to dangerous impact in visitor's mind means that cut traffic towards website or user profile. I have bring up a dashing working example.

Saturday

Csharp Example: Text to Speech

Introduction

Today, I am providing a working example of text to speech using .Net framework 4.5 with System.Text namespace. Text to speech is used widely in large scale for different purposes.
I am explaining all steps how to convert Text to Speech using C#, .Net framework.

Step 1. First of all, we have to add reference of System.Speech in our Text Speech application.

System.Speech

Step 2. Now import namespace using System.Speech.Synthesis in our form.
using System.Speech.Synthesis; 
Step 3. Now create object of SpeechSynthesizer
SpeechSynthesizer speech = new SpeechSynthesizer(); 
Step 4. Next one, write this line code speech.SpeakAsync(textBox1.Text) on button click.
speech.SpeakAsync(textBox1.Text); 
Step 5. Run application using F5 button to view Text speech interface.
Step 6. Enter sample text in input box to read through our application.
Step 7. Finally you can see how gracefully reading our text using our C# application.
Start Speech

Summary

Explained above, all steps Text to Speech using C# .Net framework 4.5 with working sample. I have attached working sample at the bottom of this article.
If anybody need help or further queries then write here.
Download

Video: Click here to Text to Speech Video Tutorial

Relevant Reading

Tuesday

MVC Caching: How to Disable Automatic Caching in ASP.Net MVC

Introduction

Today, I am explaining very important part of MVC application, just explaining about how to disable automatic caching in ASP.Net MVC application. It is very important in our MVC app while we don't allow end user to navigate browser cache (next, previous button etc.). MVC has provided feature to disable caching in ASP.Net MVC application.

Sunday

Count Down Timer: Jquery Timer Countdown in MVC Application

Introduction

Timer countdown is very important in our web apps while we are restricting to end user within specified time frame for example apps online Quiz, online survey etc. Here, in this article I am explain in full depth, how to implement Jquery/JavaScript timer count down in our web apps.

Step 1:First of all add following time to start count down while open our MVC web app, here I am adding 2 minutes of time count down.

public ActionResult Index()
{
  if (Session["Rem_Time"] == null)
  {
     Session["Rem_Time"] = DateTime.Now.AddMinutes(2).ToString("dd-MM-yyyy h:mm:ss tt");
   }
   ViewBag.Rem_Time = Session["Rem_Time"];

   ViewBag.Message = "Modify this template to jump-start your MVC application.";
   return View();
}
Step 2: Add following div in Index page of our MVC apps _layout.cshtml page.

id timecountdown

Step 3: Add following script in our MVC web app which will display time (hour, minutes, secs).

Interval Time Count Down

Populating JavaScript Timer Count Down in MVC Web Application

Finally, you can see how populating JavaScript Timer Count Down in MVC Web Application. I hope it will help you all. 
MVC Timer Count Down

Conclusion

I have explained fully with step to step, how we can implement Jquery timer count down in our MVC web apps. If any queries then let me know, I am very happy to reply all of your queries.

Download Complete Project

Download

Suggested Reading