Friday, 20 March 2015

Mvc DbUpdateConcurrencyException

Exception :-DbUpdateConcurrencyException thrown:-

Solution :-

If you have manually created the table in the database, then delete it and let the entity framework made the table
automatically.

Run the following command in the nudget console :-
PM>enable-migrations -ContextTypeName EmployeeContext

PM>add-migration InitialCreate

PM>update-database -verbose

MVC NullReference Exception


1. Null Reference Exception :-


Null reference exception occurred at view page because you have not passed the model object from the controller class to
the respective view page

e.g:-
public ActionResult Index()
{
            Customer obj = new Customer();
            obj.id = 1001;
            obj.name = "raju";
            return View("index");//--->this will inoke the view index.aspx
}

[index.aspx]
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcCustomer.Models.Customer>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        The customer id is <%=Model.id %> //-->Model is used to bind view with Model objects
        The customer name is <%=Model.name %>
    </div>
</body>
</html>

//This will cause "NullreferenceExceptoin" error at view page because you have not passed the model object from the
controller to the view page

solution :- Pass the object in the view as follows:-
public ActionResult Index()
{
            Customer obj = new Customer();
            obj.id = 1001;
            obj.name = "raju";
            return View("index",obj);//--->this will invoke the view index.aspx
}


Friday, 13 March 2015

WCF SERVICE CONFIGURING


Configure your WCF service in "web.config" as below ;-
[web.config]

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="web"
                 receiveTimeout="00:30:00"
                 sendTimeout="00:30:00"></binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="namespace.serviceName"  behaviorConfiguration="web">
        <endpoint name="mex" address="" binding="basicHttpBinding"         contract="namespace.serviceInterface">
        </endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="web">
          <!-- To enable metadata information -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details  -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

[Iservice1.cs]
using System.ServiceModel;
using System.ServiceModel.Web;

namespace namespaceName
{
 
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "/method1/{arg1}", ResponseFormat =    WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]

        string method1(string arg1);

        [OperationContract]
        [WebInvoke(UriTemplate = "/method2/{arg1}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        string method2(string arg1);
    }

}

[Service1.svc]
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

namespace NamespaceName
{
    public class Service1 : IService1
    {
        public string method1(string arg1)
        {
            //do implementation here
        }

        public string method2(string arg1)
        {
             //do implementation here
        }
    }
}

Note:deploy/publish the service as mentioned in other posts

WCF


What is WCF?

WCF stands for windows communication foundation. WCF is a feature which is made available by the Microsoft for building distributed and inter-operable applications.

Distributed applications:
--------------------------------
Distributed application is an application where parts of it run on more than one computer.In distributed applications some part of the application may reside on one system while other parts of application may reside on other systems.

For e.g:- A client machine of any user is accessing the web service of other third party which may be sitting miles away from the client machine.

Distributed systems provide the better scalablity for the applications, which means that the if a application is large enough to be reside on one machine than it can divided to different tiers. These tiers can be Presentation tier,business tier and data access tier.

Inter-operable applications
----------------------------------
Sometimes we have a client which may be running java on its client machine and our service may be built in .net platform then how will a java client will be able to access the .net service.
This is where an inter operable application comes in play. An inter operable application makes it possible for any platform to communicate with each other.

Why we use WCF?

Previously we were having web services to deploy the services but we need the separate technology like "remoting" if we want to deploy "tcp protocol", but Microsoft has eradicated that headache of learning separate technology. You can now do all the service stuff by using WCF only.

for e.g:- if you have 2 clients and if one client wants to access your service by using the following format:-
-HTTP PROTOCOL WITH XML MESSAGE FORMAT

and there is 2nd client who wants to access your service by using the following format:-
TCP PROTOCOL WITH BINARY MESSAGE

then instead of making the remoting services for 2nd client, we can just use the same wcf service by adding the 2nd endpoint for the 2nd client.

In the endpoint configuration, we can specify the format of messages and protocols

With this we are having only single service and this service ,we can deploy multiple endpoints for multiple clients.





PUBLISH WCF SERVICE


1.CREATE A NEW PROJECT AND ADD A WCF SERVICE APPLICATION

2.THIS WILL ADD A SERVICE PROJECT WITH TWO CLASSES. ONE OF INTERFACE TYPE AND ANOTHER CLASS WHICH IMPLEMENTS THE INTERFACE CLASS.
THE SERVICE CLASS WHICH IS IMPLEMENTING THE INTERFACE CLASS WILL BE HAVING A .SVC EXTENSION WHICH MEANS IT IS YOUR SERVICE CLASS

3.NOW TO PUBLISH THIS SERVICE ,YOU CAN EITHER RUN YOUR SERVICE PROJECT BY CLICKING THE "PLAY" BUTTON OR HITTING "F5" OR "CTRL+F5"
 OR
BY PUBLISHING THE WCF SERVICE USING THE IIS MANAGER

HOW TO PUBLISH WCF SERVICE USING IIS MANAGER?

1. OPEN YOUR IIS MANAGER FIRST BY TYPING "inetmgr" IN YOUR RUN WINDOW.
IIS MANAGER WILL LOOK SOMETHING LIKE THE BELOW IMAGE :-

2. NOW RIGHT CLICK THE "SITES" FOLDER AND CLICK THE "ADD WEBSITE"
3.MENTION THE SITE NAME AND PHYSICAL PATH WHERE YOUR SERVICE WILL BE LOCATED.
IP ADDRESS WILL BE YOUR LOCAL MACHINE IP ADDRESS OR "LOCALHOST" BY DEFAULT.

4. YOU NEED TO METION THE PORT NUMBER APART FROM LOCAL PORT NUMBER WHICH IS "80".

5.CLICK THE "OK" BUTTON AND YOUR SERVICE WEB SITE WILL BE CREATED AT YOUR MENTIONED PHYSICAL PATH.

6.FOR E.G:- I HAVE CREATED THE WEB SITE "SITENAME" WHICH YOU CAN SEE IN THE IIS MANAGER WINDOW. AT THE RIGHT HAND SIDE YOU CAN SEE THE OPTION OF "RESTART,START,STOP" UNDER THE "MANAGE WEBSITE". FROM HERE YOU CAN START OR STOP YOUR SERVICE.

RIGHT CLICK YOUR SITE NAME AND GO TO THE OPTION "MANAGE WEBSITE". FROM HERE YOU CAN BROWSE YOUR WEBSITE. YOU CAN ALSO START/STOP YOUR SERVICE FROM HERE.

YOUR SERVICE FOLDER WILL LOOK SOMETHING AS BELOW :-
THIS WILL CONTAIN YOUR SERVICE1.SVC AND WEB.CONFIG FILE OF YOUR SERVICE.

7. NOW GO TO YOUR SERVICE PROJECT IN THE VISUAL STUDIO AND BUILD THE PROJECT.

8.RIGHT CLICK YOUR PROJECT AND GO TO THE "PUBLISH" OPTION. FROM THERE CHOOSE THE "TARGET LOCATION" UNDER THE "CONNECTION" SECTION.
BROWSE THE PATH WHERE YOU HAVE SAVED YOUR WEBSITE [E.G:- E:\FILE1].

9.CLICK "NEXT" BUTTON AND CLICK THE "PUBLISH" BUTTON TO PUBLISH YOUR WEB SERVICE.

10.NOW TO CHECK IF YOUR SERVICE IS RUNNING, RIGHT CLICK YOUR WEBSITE IN IIS MANAGER AND CLICK THE BROWSE AND IN THE ADDRESS BAR ADD YOUR SERVICE NAME AFTER THE IP ADDRESS.
FOR E.G: LOCALHOST:88/SERVICE1.SVC
IF YOU ARE SEEING BELOW IMAGE IN YOUR PAGE, THAT MEANS YOUR SERVICE IS WORKING FINE !!


Thursday, 12 March 2015

Exception :- Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied solution Administartot tools>component services> 1.Go to Administrator tools 2.Then go to component services 3.open the Computers>my computer>DCOM config 4.search the microsoft word and assign the admin permission to it 5.In microsoft word go to Security -> Customize all 3 permissions to allow everyone For more information you can visit the follwoing url : http://stackoverflow.com/questions/17785063/retrieving-the-com-class-factory-for-component-error-80070005-access-is-de https://social.msdn.microsoft.com/Forums/vstudio/en-US/b401459a-d14a-4517-b204-fe7c0f5b1f83/retrieving-the-com-class-factory-for-component-with-clsid-000209ff00000000c000000000000046?forum=netfxbcl

Solution :-

Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied

solution

Administrator tools>component services>

1.Go to Administrator tools
2.Then go to component services
3.open the Computers>my computer>DCOM config
4.search the microsoft word and assign the admin permission to it
5.In microsoft word go to Security -> Customize all 3 permissions to allow everyone

For more information you can visit the follwoing url :
http://stackoverflow.com/questions/17785063/retrieving-the-com-class-factory-for-component-error-80070005-access-is-de


https://social.msdn.microsoft.com/Forums/vstudio/en-US/b401459a-d14a-4517-b204-fe7c0f5b1f83/retrieving-the-com-class-factory-for-component-with-clsid-000209ff00000000c000000000000046?forum=netfxbcl

How to get local ip address of host in c#



public string LocalIPAddress()
 {
   IPHostEntry host;
   string localIP = "";
   host = Dns.GetHostEntry(Dns.GetHostName());
   foreach (IPAddress ip in host.AddressList)
   {
     if (ip.AddressFamily == AddressFamily.InterNetwork)
     {
       localIP = ip.ToString();
       break;
     }
   }
   return localIP;
 }



To get ip address of local host

Tuesday, 10 March 2015

Hosting WCF services in console application

Adding and hosting WCF services in console application

1. Create a New "class library" project and add a new item in this project as "wcf service"
2. Add the new "console project" in your solution
3.Add the service refernece to your "console project"
4.Add the system.servicemodel reference to your project
5.Add the "app.config" to your project
6.Code "App.config" as :-
//<App.config>

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="namespace.Name_of_Service" behaviorConfiguration="Name_of_behavior">
        <endpoint address="Name_of_Service" binding="basicHttpBinding" contract="namespace.Name_of_ServiceInterface"></endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/"/>
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="Name_of_behavior">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

  </system.serviceModel>
</configuration>

7.Make your "console project" as startup project and code the program.cs as :-

 public static void Main(string[] args)
        {
            try
            {
                using (ServiceHost host = new ServiceHost(typeof(Namespace.Name_of_Service)))
                {
                    host.Open();
                    Console.WriteLine("Host started @" + DateTime.Now.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }