Sunday 27 September 2015

Entity Framework: how to solve “FOREIGN KEY constraint may cause cycles or multiple cascade paths”?

Introducing FOREIGN KEY constraint 'FK_dbo.ChildProfile_dbo.SourceType_SourceTypeId' on table 'ChildProfile' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.



Answer

Also you can modify your migration class. In my case in the migration class was:


Make  "cascadeDelete: false" Update-Database works perfectly.


OR
Add this code in context



protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    }

Update-Database works perfectly.

No connection string named 'MyEntities' could be found in the application config file.

I am using entity framework and ASP.NET MVC 5 and WEB API 2 to build an application


My solution is split into two projects;
  • A class library that includes my data model (.edmx) file and a few custom interfaces
  • The 'container' MVC project that references the class library above
My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error


No connection string named 'MyEntities' could be found in the application config file.




Answer:


This happens because the class library (where the .edmx file) is not your startup / main project.
You'll need to copy the connection string to the main project config file.
Incase your startup / main project does not have a config file (like it was in my Console Application case) just add one (Startup project - Add New Item -> Application Configuration File).






Saturday 26 September 2015

Creating a Flot Chart with jQuery Flot and ASP.NET Web API 2

Step 1 : Create ASP.NET Web API 2 project

Step 2: Create Master_Site and SiteAnalyticsData Models in Model Folder

Master_Site


SiteAnalyticsData
Step 3: Add Context Class in Model Folder

Step 4: Open Package Manager Console Enable MIgration and Add Migration then Update database in 
PM> enable-migrations
PM> add-migration "Initial"
PM> update-database

Step 5 : Go to database and add some dummy data like 

Now our data is ready.

Step 6: Create a Web api Controller and paste the below code

using jQueryFlotChart.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace jQueryFlotChart.Controllers
{
    public class ChartController : ApiController
    {
        public dynamic Get(int year)
        {
            using (SampleDbContext context = new SampleDbContext())
            {

                var alldata = (from item in context.SiteAnalyticsDatas
                               where item.Date.Year == year && item.SiteID == 1
                               group item by item.Date.Month into grp
                               select new
                               {
                                   Month = grp.Key,
                                   Visitors = grp.Sum(x => x.Visitors),
                                   Visits = grp.Sum(x => x.Visits),
                                   PageViews = grp.Sum(x => x.PageViews)
                               }).ToList();

         var ret = new[]
        {  
            new { label="PageViews", data = alldata.Select(x=>new int[]{ x.Month, x.PageViews })},
            new { label="Visits", data = alldata.Select(x=>new int[]{ x.Month, x.Visits })},
            new { label="Visitors", data = alldata.Select(x=>new int[]{ x.Month, x.Visitors })}
            
        };

         return ret;
            }
        }

    }
}
Step 7 : Go to manage package Manager and search for flot and instal it... or you can directly download from Flot website and keep the required js and css file. 
one css file we have to take from flot website... when you will download the file in that example.css will be there so you can use that.


Step 8: Go to View : Home> Index and write /Paste the following code                              

@{Layout = null;}

<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="~/Scripts/flot/excanvas.min.js"></script><![endif]-->
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/flot/jquery.flot.min.js"></script>

<script type="text/javascript">
    $(function () {
        debugger;
        var dataurl = 'api/Chart/';
        $.ajax({
            url: dataurl,
            method: 'GET',
            data: { year: 2012 },
            dataType: 'json',
            success: function (data) {
                debugger;

                $.plot($("#placeholder"), data, options);
            }
        });
        // setup plot
        var options = {
            legend: {
                show: true,
                margin: 10,
                backgroundOpacity: 0.9
            },
            points: {
                show: true,
                radius: 3
            },
            lines: {
                show: true
            },
            grid: { hoverable: true, clickable: true },
            yaxis: { min: 0, tickFormatter: formatter },
            xaxis: { ticks: [[1, "Jan"], [2, "Feb"], [3, "Mar"], [4, "Apr"], [5, "May"], [6, "Jun"], [7, "Jul"], [8, "Aug"], [9, "Sep"], [10, "Oct"], [11, "Nov"], [12, "Dec"]] }

        };
        function formatter(val, axis) {
            return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }
       
    });



    var previousPoint = null;
    $("#placeholder").bind("plothover", function (event, pos, item) {
        if (item) {
            if (previousPoint != item.dataIndex) {
                previousPoint = item.dataIndex;

                $("#tooltip").remove();
                var x = item.datapoint[0],
                    y = item.datapoint[1].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                showTooltip(item.pageX, item.pageY, item.series.label + ": " + y);

            }
        }
        else {
            $("#tooltip").remove();
            previousPoint = null;
        }
    });


    function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css({
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '2px',
            'background-color': '#fee',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
    }

</script>




<section style="width: 500px; margin: 10px; text-align:center;">
    <div id="placeholder" style="width: 500px; height: 300px;">
    </div>
    <h3 style="font-size:1.4em">Traffic Overview - 2015 </h3>
</section>

Done: RUN the application you will get the o/p.




Sunday 20 September 2015

How to convert .NET object to JSON string in MVC 5 .

Step 1: First create an empty MVC application
Step 2:Create Employee class in Model folder                                                                                         

Step 3: To converts List<Employee> objects to a JSON string we will use Serialize() method of         JavaScriptSerializer class.  
For that First Create a Empty Home Controller and Paste the Below code.

Step 4 : Create the Index view and write the below code                                                                        
@{

    Layout = null;
}

@ViewBag.Data

Step 5 :Run the application
Done :)

Thursday 17 September 2015

How to Resolve null values in C Sharp

How to Resolve null values in C #

Say you have a method which accepts a string parameter. The method may need to handle null values in some way. One strategy is to validate the parameter and throw an exception


Another strategy is to provide some default value with an if-else statement:










This can be greatly simplified with the ternary operator:




An even simpler solution is by using the null-coalescing operator ?? :







This statement is equal to the first if-else solution but it’s a lot more elegant and concise.
You can use this technique with any nullable type of course, not just strings. The ?? operator can even be chained:


How to hide the text entered in a .NET console application

You’ve probably encountered console applications that ask for a password. It’s very likely that the password will stay hidden otherwise other people viewing your screen can easily read it.
This short post will present a possible solution on how to achieve a hidden string input in a .NET console application.

The key feature to bear in mind is the overloaded Console.ReadKey method where you can pass in a boolean parameter. A ‘true’ means that the given character typed should be intercepted, i.e. not shown in the console window. We continue reading the characters until it is equal to the new line character ‘\r’ which closes the while loop. We store the password characters in a string builder. Unfortunately the ReadLine method has no equivalent overload which would turn the solution into a one-liner.

Here it comes in code:


You can even hide the blinking cursor with the following code:



Just don’t forget to set the visibility back to true later on.

How to add basic sounds to a .NET console application


How to add basic sounds to a .NET console application:

Today we will look how to add basic sounds to our .Net Console application

Create a Console Application:

The Console object has a Beep method which has a parameterless version:

Console.Beep();










It plays a short beep sound. If you’re not satisfied with it you can go for the overloaded Beep method that accepts a frequency in hertz and a duration in milliseconds.

The lower the frequency value the deeper the sound:

Console.Beep(100, 5000);

That sounds like an organ.

Console.Beep(10000, 5000);

That on the other hand just sounds awful.

Saturday 12 September 2015

How to publish a project to BitBucket from Visual Studio 2013

Visual Studio 2013 and BitBucket

Today i will show how to publish a project to BitBucket from Visual Studio 2013.
Step 1 :Add solution to Source Control


Step 2: Commit to local Git

Step 3: In the "Changes" area, click "Commits". This takes you to the dialog where you can publish to a Remote Repository.

Step 4: Then go to BitBucket and login and create a repository                                               



Part 5: provide basic information.about your repo and click create                                         

Step 6: Enter the URL to your BitBucket repository (must already exist in BitBucket and must be empty) and click "Publish"

   Step 7: Enter your BitBucket credentials when prompted. After the publish finishes you'll get a results message like this.

Step 8: Use the "Sync" button to update BitBucket with your local commits         
                           

Done Hope it Helps you:)

Wednesday 2 September 2015

Dependency Injection in ASP.NET MVC 5 or MVC 6 with Structure Map

Dependency Injection in ASP.NET MVC 5 or MVC 6 with Structure Map

You people may be wondering why we need dependency injection. So the answer is DI is a design pattern that basically let you to write a loosely coupled testable code or application.
Three types of dependency injection



There are at least three ways an object can receive a reference to an external module



Constructor injection: the dependencies are provided through a class constructor.
Setter injection: the client exposes a setter method that the injector uses to inject the dependency.
Interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.
But Today we will look Constructor injection.



In day to day life of coding or programming our one class generally depend on some other class.
Take a look of my MVC 5 code.







You can see that in index method, it requires to create an instance of "Employee" class to get the full name of a employee. It is very clear that the Index method is tightly coupled with the Employee class.
This is not good when it comes to testing HomeController class. Suppose that you have other methods, with similar types of class dependencies. So, each time when you test the code, you have to pass an actual instance Employee class. This is tedious. You don't have the luxury of passing a fake employee class to easily test your controllers.
So how do we decouple the Employee class from HomeController ? This is our question so



This is where DI comes in handy. You can inject dependencies in several ways. Today i will show you "constructor injection", where you simply inject the dependencies to the constructor of the class. (Ex: in the above example, inject dependencies to the constructor of the HomeController).



So we will look step by step ,How to implement DI using structure map in MVC 5 Application



Step 1 – We have to setup Structure Map



- Lets create a new MVC5 application in Visual Studio 2013/15.
  • Let's use popular "StructreMap" Ioc container to inject dependencies externally. To setup StructreMap, Open a nuget package manager and search for “StructreMap” and install it.
  • You can do the same thing using package manager console powershell.
Step 2 - Create IEmployee interface.



public interface IEmployee
{
string GetFullName();
}



Step 3 - Now Create the actual Employee class/concrete class. This class implements IEmployee interface.



public class Employee: IEmployee
{
public string GetFullName()
{
return "Ravi Kumar Singh";
}
}



Step 4 - Go to the HomeController. Since we use constructor injection, let's create a constructor for the HomeController. It will look similar to this.



public class HomeController : Controller
{
private readonly IEmployee _employee;



// constructor
public HomeController( IEmployee employee)
{
this._employee = employee;
}
//action method
public ActionResult Index()
{
return Content(this.employee.GetFullName());
}
}



Notice that, we are passing the IEmployee interface as the parameter for the constructor. Then we saved the passed parameter into a instant variable of type IEmployee. So what is the benefit of doing this?



Now you can pass any class that implements IEmployee interface to our HomeController. We can create a dummy class which implements IEmployee with dummy data and simply test our HomeController quite easily!



To do this, we need a way to Map our IEmployee interface either with Actual Class or Dummy Class. This is facilitated by our Ioc container "StrutureMap".



Step 5 - Goto ~/DependencyResolution -> IoC.cs file. This file is automatically created once you installed StructureMap. Change it as follows.



public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.For<IEmployee>().Use<Employee>();
});
return ObjectFactory.Container;
}
}



x.For<IEmployee>().Use<FakeEmployee >();
You can easily replace the Actual Employee class with a Dummy Class. That's it.







Done ;)