Search This Blog

Friday, 24 November 2017

Creating a Self Hosted WCF Service

If you haven't created the WCF Service go to following link to create the Service.



If you created the WCF Service follow the following Step to Self Host.

Step 1:- Open Visual Studio 2010

Step 2:- Go to File menu => New => Project...



Step 3:- Left Pane Templates select Visual C# => Select Console Application from Middle pane => Type SelfHost in the Name box => Click OK.




Step 4:- Right click SelfHost in Solution Explorer => Select Add Reference.... => Select System.ServiceModel from the .NET tab => Click OK.






Step 5:- Right click SelfHost in Solution Explorer => Select Add Reference.... => Select Browse tab => Give Service File path "D:\DEMO\WCF\EmployeeWcfService\EmployeeWcfService\bin" => Click OK => Select EmployeeWcfService.dll => Click OK.





Step 5:- Add the following namespace

using System.ServiceModel;
using System.ServiceModel.Description;
using EmployeeWcfService;



Step 6:- Create an instance of the Uri class with the base address for the service.

Uri baseAddress = new Uri("http://localhost:52923/EmployeeService.svc");



Step 7:- Create an instance of the ServiceHost class, passing a Type that represents the service type and the base address Uniform Resource Identifier (URI) to the ServiceHost(Type, Uri[]). Enable metadata publishing, and then call the Open method on the ServiceHost to initialize the service and prepare it to receive messages.

// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(EmployeeService), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);

// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
host.Open();

Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();

// Close the ServiceHost.
host.Close();
}



Complete Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using EmployeeWcfService;

namespace SelfHost
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:52923/EmployeeService.svc");

// Create the ServiceHost.
using (ServiceHost host = new ServiceHost(typeof(EmployeeService), baseAddress))
{
// Enable metadata publishing.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);

// Open the ServiceHost to start listening for messages. Since
// no endpoints are explicitly configured, the runtime will create
// one endpoint per base address for each service contract implemented
// by the service.
host.Open();

Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();

// Close the ServiceHost.
host.Close();
}
}
}
}


Step 7:- Press Ctrl + F5 Or Use Visual Studio Start Debugging(F5) icon to run the service.

If you get the following error.
1. Check you have administrative rights.
2. Run Visual Studio instance as an administrator.
Step :- Right Click Visual Studio Icon => Click "Run as administrator"




Step 8:- If following screen appear, Your WCF service is running and SelfHosted Successfully => Use following URL to Consume the Service.

URL :- http://localhost:52923/EmployeeService.svc



Now your WCF Service running, to check it follow the following link to consume it.



For More Info Visit microsoft.com

Hosting WCF Service inside IIS

If you haven't created the WCF Service go to following link to create the Service.


If you create the WCF Service follow the following Step to Host WCF Service inside IIS

Note :- Step based on Windows 10 Operating System

Step 1 :- To Open the IIS Manager, Search "Run" in Search Windows => Click/Enter "Run" => "Run" Window box Open => Type "inetmgr" => Click/Enter "OK"

Or

Search "inetmgr" in Search Windows => Click/Enter "Internet Information Services (IIS) Manager"





Step 2:- Right Click Sites => Add Website...




Step 3:- Fill Details... => Click OK => WCF Website added under Sites List

Site name :- WCF
Physical path :- D:\DEMO\WCF\EmployeeWcfService\EmployeeWcfService
Port :- 52923




Step 4:- Select the WCF Website and switch to Features View to Content View



Step 5:- Select the EmployeeService.svc => Right Click EmployeeService.svc => Select Browse



Step 6:- If following screen appear, Your WCF service is running and hosted on IIS Successfully => Use following URL to Consume the Service.

URL :- http://localhost:52923/EmployeeService.svc?wsdl




Now your WCF Service running on IIS, to check it follow the following link to consume it.

Sunday, 23 July 2017

Interview Question

Q. Can static constructor have parameter and access modifier?
A. No, static constructor does not have a parameter and access modifier.

1. A static constructor must be parameter less.
2. Constructor does not have access modifier.
3. A static constructor is called automatically when you creating the object of class. Therefore you can't send it any parameters.

public class StaticClass
{
    static StaticClass(string abc) // This line throw error
    {
        Console.WriteLine("Static constructor" + abc);
    }

    public StaticClass(string xyz)
    {
        Console.WriteLine("Instance constructor" + xyz);
    }

    static void Main(string[] args)
    {
        StaticClass obj = new StaticClass("Hello");
    }
}
**************************************************
Q. Can abstract class have constructor?
A. Yes, Abstract class can have constructors.
**************************************************
public abstract class AbstractClass
{
    public AbstractClass()
    {
        Console.WriteLine("Abstract constructor");
    }
}

class Program : AbstractClass
{
    static void Main(string[] args)
    {
        AbstractClass obj = new Program();
    }
}
**************************************************
SQL tunner?
**************************************************
Trace file in SQL?
**************************************************
How join internally work?
**************************************************
Q. Html.partial vs Html.RenderPartial? In which condition used?
A.
Html.Partial

1. Html.Partial returns a String
2. Return Type MvcHtmlString
3. Renders the specified partial view as an HTML-encoded string.
4. Returns value store into variable
@{
    var str = @Html.Partial("_Index");
    <p>@str</p>
}
5. Useful in this case, where you want to manipulate the generated HTML

Html.RenderPartial

1. Html.RenderPartial returns a void
2. Return Type void
3. Renders the specified partial view by using the specified HTML helper.
4. Returns a void due to whitch not store into variable
@{
     Html.RenderPartial("_Index");
}
**************************************************
Q. How to create custom control in mvc?
A.
1. Create an extension method.
2. To create an extension method, Use the "this" keyword with HtmlHelper class and pass the first parameter of method i.e. "this HtmlHelper htmlHelper".
3. Make sure class and method mark static.

using System;
using System.Web.Mvc;
using System.Text;

namespace MvcApplication1.UC
{
    public static class CustomeControl
    {
        public static MvcHtmlString CopyRights(this HtmlHelper htmlHelper)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<p>");

            sb.Append("© ");
            sb.Append(DateTime.Now.Year + " - My ASP.NET MVC Application");

            sb.Append("</p>");
            return MvcHtmlString.Create(sb.ToString());
        }
    }
}

Use in View page

@using MvcApplication1.UC;

@Html.CopyRights("")
**************************************************
Q. Write code to get following output?
     1
     12
     123
     1234
A.
for (int i = 1; i < 5; i++)
{
     for (int j = 1; j <= i; j++)
     {
           Console.Write(j);
     }
     Console.WriteLine("");
}
**************************************************
Q. What is outproc in session?
A.
Session State
1. InProc (default Session State Mode)
2. StateServer (dedicated machine) also called outproc
3. SQLServer (SQL server)
4. Custom
5. Off

More Info Visit
https://msdn.microsoft.com/en-us/library/ms178586.aspx
**************************************************
Q. Which one is not a methods of  DataAdapter?
     Fill
     FillSchema
     Copy
     GetFillParameters
     Update
A.  Copy
**************************************************
Q. How to read value from Stake?
     Stack<string> stack = new Stack<string>();
     stack.Push("One");
     stack.Push("Two");
     stack.Push("Three");
     stack.Push("Four");
     stack.Push("Five");
Option
1.
     IEnumerator e = stack.GetEnumerator();
     while (e.MoveNext())
     {
         Console.WriteLine(e.Current);
     }
2.
     IEnumerable e = stack.GetEnumerator();
     while (e.MoveNext())
     {
         Console.WriteLine(e.Current);
     }
3.
     IEnumerator e = stack.IEnumerable();
     while (e.MoveNext())
     {
         Console.WriteLine(e.Current);
     }
4.
     IEnumerable e = stack.IEnumerable();
     while (e.MoveNext())
     {
         Console.WriteLine(e.Current);
     }
A. 1
**************************************************
Q. Which one used to expose method to client in WCF?
     ServiceContract
     OperationContract
     WebMethod
     MethodContract
A.  OperationContract
**************************************************
Q. Which one copy both structure and data of the table?
     CopyAll
     Clone
     Copy
     Select
A.  Copy
**************************************************
Q. Filter in mvc?
A.
1.  Authorization filters
2.  Action filters
3.  Response filters
4.  Exception filters
**************************************************
Q. Session management in mvc?
A. You can manage session using tempdata, viewdata, and viewbag in mvc.

TempData:-
Helps to maintain data when you move from one controller to another controller or from one action to another action.

Store Syntax(Action):- TempData["Message"] = "TempData Hello World";
Read Syntax(View):- @{<p>@TempData["Message"]</p>}
Note:-
"TempData" is once read it will not be available in the subsequent request. Call "Keep" method, if we want to "TempData" available in the subsequent request.
Read Syntax(View):- @{
   <p>@TempData["Message"]</p>
   TempData.Keep("Message");
}
    
ViewData:-
Helps to maintain data when you move from controller to view.

Store Syntax(Action):- ViewData["Message"] = "ViewData Hello World";
Read Syntax(View):- @{<p>@ViewData["Message"]</p>}
  
ViewBag:- 
It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not required. It uses the dynamic keyword internally.

Store Syntax(Action):- ViewBag.Message = "ViewBag Hello World";
Read Syntax(View):- @{<p>@ViewBag.Message</p>}
**************************************************
Q. One to one interaction to client in mvc?
     View
     Controller
     ViewModels
     Action Method
A.  Controller
**************************************************
Q. Asp.net vs. mvc?
A.
Refer following link
http://www.dotnettricks.com/learn/mvc/difference-between-aspnet-webform-and-aspnet-mvc
**************************************************
Q. Web services vs. WCF web services?
A.
Refer following link
http://www.dotnettricks.com/learn/wcf/difference-between-wcf-and-aspnet-web-service
**************************************************
Q. Default value of Value Data Type?
A.
Value type Default value
bool      false
byte       0
char       '\0'
decimal    0.0M
double     0.0D
enum       The value produced by the expression (E)0, where E is the enum      identifier.
float      0.0F
int        0
long       0L
sbyte      0
short      0
struct     The value produced by setting all value-type fields to their         default values and all reference-type fields to null.
uint       0
ulong      0

ushort     0