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

Tuesday, 2 June 2015

How to use AngularJs in Visual Studio 2013

Step 1 : Our First Step is to install the AngularJS extension for Visual Studio. To do this, I download the angular.intellisense.js file and place it in the 

C:\Program Files (x86)\Microsoft Visual Studio 12.0\JavaScript\References folder on you PC.

Step 2: Next, We have to add AngularJS to our project in Visual Studio using the NuGet package manager (you could also download AngularJS directly from http://www.angularjs.org and place it into your own project alongside your other script files).

First Create Normal empty web application.It will Look Like









Then Right Click on the project and select Package manager












Then search for angular and install in the project , Now you are ready to work with angularjs in visual studio 2013 and it will support intellisense also :)



Friday, 30 January 2015

Shopify API Integration from .NET

To Integrate Shopify first You need Key and Password

So to generate an API key and password, go to http://store.myshopify.com/admin/apps, and click "Create a private API key" at the bottom.It will generate password and key for you.



Then copy and paste this code ....

  public string GetCustomers()
        {
            const string url = "https://store.myshopify.com/admin/customers.json";

            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            req.ContentType = "application/json";
            req.Credentials = GetCredential(url);
            req.PreAuthenticate = true;

            using (var resp = (HttpWebResponse)req.GetResponse())
            {
                if (resp.StatusCode != HttpStatusCode.OK)
                {
                    string message = String.Format("Call failed. Received HTTP {0}", resp.StatusCode);
                    throw new ApplicationException(message);
                }

                var sr = new StreamReader(resp.GetResponseStream());
                return sr.ReadToEnd();
            }
        }

        private static CredentialCache GetCredential(string url)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            var credentialCache = new CredentialCache();
            credentialCache.Add(new Uri(url), "Basic", new NetworkCredential("api-key", "password"));
            return credentialCache;
        }




Done;)

Tuesday, 27 January 2015

Deploy PHP website from Visual Studio 2013 to Microsoft Azure Websites

Uf after 3 hours of struggle i found the solution for php deployment in Azure.

So First we have to download PHP Tools for Visual Studio 2013. I have given the URL from that you can download Or you have another option means you can download from Nuget package manager

https://visualstudiogallery.msdn.microsoft.com/6eb51f05-ef01-4513-ac83-4c5f50c95fb5

OR
Click on tool then click on Extensions and Updates



After that you will get new screen and search for php and install it.










Now you are ready to deploy PHP project in Azure. So now create a php project.

















Like that visual studio allow PHP developers to develop php projects and enhance the experience with Microsoft Azure.

However, when we are working with php projects we don’t have the same wizard for uploading like ASP.net or MVC solution.
This time you will get a screen like this.



















To retrieve the parameters required for Microsoft Azure Websites, You need to go to the website’s DASHBOARD and download the publish profile that contain all the information.



















One More things you must ensure that your website has enabled the correct version of PHP  for that go to CONFIGURE  then General  then  PHP Version











Thats it ... hope it helped you. :)

Friday, 26 December 2014

How to Enforce HTTPS on your Azure website

URL Rewrite rules are defined in a web.config file stored in the root of your application. The following example contains a basic URL Rewrite rule that forces all incoming traffic to use HTTPS.
URL Rewrite Example Web.Config











This rule works by returning an HTTP status code of 301 (permanent redirect) when the user requests a page using HTTP. The 301 redirects the request to the same URL as the visitor requested, but replaces the HTTP portion of the request with HTTPS. For example, http://testwebsite.com would be redirected to https://testwebsite.com.

How to create ssl certificate for Azure website using Godaddy

SSL Certificate For Azure Website using Godaddy .

OR
Step By Step Guide for Implementing Godaddy SSL Certificate on Windows Azure Website.


Today I got a task of implementing an SSL for a sub domain of one of our client .So i Did the Implementation so i am sharing my effort and knowledge.

Step 01: First Generate a Certificate Request i.e CSR.

Open the IIS Manager(Type IIS in Windows Search and click on IIS )





















When you will click on IIS then this screen will come.In that Screen just click on Server Certificate.




















On the Server Certificates Screen , click Create Certificate Request .












Fill all the details for the certificate. 

Make sure that the common name matches your domain name. In my case If you are using a Godaddy 
wild card certificate for a subdomain. Then used common name something like *.mydomain.com.




Choose Cryptographic Service Provider

This step is quite important to note, and this is where you follow the Azure guideline for certificate to be 
at least 2048.




















Choose the file path to generate the CSR. This file contains the message code that is used by SSL provider for generating digital identity Certificate.



















The File Will Be Something like this.

-----BEGIN NEW CERTIFICATE REQUEST-----
MIIEaDCCA1ACAQAwezELMAkGA1UEBhMCSU4xEjAQBgNVBAgMCUthcm5hdGFrYTES
MBAGA1UEBwwJQmFuZ2Fsb3JlMR0wGwYDVQQKDBRMb3ZlIFdpdGggVGVjaG5vbG9n
eTELMAkGA1UECwwCSVQxGDAWBgNVBAMMD2xvdmV3aXRodGVjaC5pbjCCASIwDQYJ
KoZIhvcNAQEBBQADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXBZQMEAQIwCwYJYIZIAWUDBAEFMAcGBSsOAwIHMAoGXXXXXXXX
CCqGSIb3DQMHMB0GA1UdDgQWBBQ0hA5sL7ClGR9/Bj0YiO/tn9M3PTANBgkqhkiG
9w0BAQUFAAOCAQEAp9duVMU8+8/8XUsrALIoRnDW0mOwDQRhnpJCYVDqHZqztRrO
ZRKMz788+qqtUrO5yVsRx4pbUg752f+/UBeTM+Z0Yg4FiWQpMAr+59/9/m0Fw/W7
bjocnzx0nizy/Uw8BVhFFQwH4rWOpjxWeftbXGx+YLa7QrhQMJzLYG3LSljjFz+c
Usv1KPsmF+DTZPYIEk64eYUcchP19QXKb162i62TAEferhb71+412pJb0zltj2Uw
e7cvZ1xdascdQG5MXLqzsXZ0yiLP/6/i4X9IgUl3xp/mU1w4HSC1IS7zq56IWTJR
NTyBIJV8CP+K8M1DQmtJek0clhlwMV9ek9nwBA==
-----END NEW CERTIFICATE REQUEST-----



Logon to your Godaddy account, and from product tab click SSL Certificates. 
Note that you need the entire text of the CSR file to submit the request. I won’t include all
the sub steps here since it’s a relatively simple process and it’s very well documented by Godaddy at this link. Requesting a standard or a wildcard certificate


Download the certificate Zip file after you’ve submitted the request. 




















After the download, you’ll observe that there are two files in the zip, one is a *.crt (Server Certificate) file and other is of type PKCS #7. Ignore the PKCS #7 Certificate file, and instead use the *.crt file. Go to Server Certificate option in IIS 7 and click Complete Certificate Request.












Provide the path of the *.crt file, and fill out the details on the form. Note make sure you change the file types to *.* Once completed you will see a row entry with name of your certificate.

Some time it will give error , so just close the iis and open it again, now you can see the certificate.



















 Right click the certificate and click export to convert it into *.pfx file for uploading it on 
Azure. Note that this conversion of crt to pfx is required since *.crt alone only contains the 
public key but the azure would also need private key to do end to end encryption. Make sure
 you note the password since while uploading it on Azure Account you’d need this.

Now We have to import PFX file into Azure.For that Go to Azure Portal for the website in which you want SSL.

Click on Domains and SSL and then on the Upload button. You’ll then be able to browse to
 your pfx file and to enter your password. Click on Save when done.














Last : Bind configured domain names to the certificate


The final step is to link each configured domain to the certificate. This step I had to do in the
 old portal. The reason was that Azure needed to ask me if I was aware of the potential 
extra costs of using a certificate, before it could be approved, and that dialog box never 
showed up in the new portal. But the steps are the same on the old and the new so no 
problems.



Now, it should all be up and running for all your configured domains.








Tuesday, 23 December 2014

Conflicting versions of ASP.NET Web Pages detected: specified version is "1.0.0.0", but the version in bin is "2.0.0.0". To continue, remove files from the application's bin directory or remove the version specification in web.config.

I am trying to run my application and it is showing an error like this..

Conflicting versions of ASP.NET Web Pages detected: specified version is "1.0.0.0", but the version in bin is "2.0.0.0". To continue, remove files from the application's bin directory or remove the version specification in web.config.





Answer :

You need to set webpages:Version appSettings with appropriate value. In your case it has to be 2.0.0.0... For this just go in Web config file and write / Change ....

<add key="webpages:Version" value="1.0.0.0"/> 

to 

 <appSettings>
    <add key="webpages:Version" value="2.0.0.0"/>
 </appSettings>


Done :)

Tuesday, 18 November 2014

Wednesday, 15 October 2014

How to Use Log4net with ASP.NET MVC 5 for Logging

Log4net is an open source library that allows .NET applications to log output to a variety of sources.

Log4net provides a simple mechanism for logging information to a variety of sources. 
Information is logged via one or more loggers. These loggers provide 5 levels of logging:
  1. Debug
  2. Information
  3. Warnings
  4. Error
  5. Fatal
Here I will be walking through the step by step in implementing logging functionality using log4net framework in an ASP.NET MVC 5 application.

I am using Visual Studio Express 2013 for Web as my development environment targeting .NET framework 4.5.1

Step 1:

Open Visual Studio 2013 for Web and create a new ASP.NET Web application selecting MVC template.

Step 2: 

Now We need to add reference of log4net DLL using NuGet package manager.






Step 3:

Next, we need to configure our application to use log4net logging framework. Add the below line in yourstartup.cs file in ASP.NET MVC5 Solution folder. The below line of code provides information about log4net configuration file.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]




Step 4:

Next, add the below section to web.config file.

<configSections>
    <!-- Add log4net config section-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,     log4net" />
  </configSections>

  <log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

Step 5:

Next modify Global.asax.cs and add the below code inside Application_Start() method.

readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Step 6:

Use the logger.Error() method to log messages when needed.


Step 7:

Run an application and we can see the log file generated under the logs folder under the application root directory as configured in the web config file.




DONE :)


Tuesday, 9 September 2014

instance failure' error while connection string is correct



If you got the error "instance failure", that might be the error with your SQL Server instance..


Make sure your SQL Server instance(i.e MS SQLSERVER) is running, where you can check in Services list. to get into services list: open run dialog box and type: "services.msc" (without quotes) and hit Enter.

That takes you to services management console, where you can check whether your instance in running or not..
If the problem still persists, then try using: Data Source=.\SQLEXPRESS.

For Example