Sunday, January 26, 2014

which binding we used for WCF REST protocol

In my previous post i explained, Interview question and few details on WCF. and Transaction in WCF  Now in this article i will explain which binding used during the WCF REST protocol. 


most of the time this question may asked during the interview , Yes its simple. 

For WCF REST used WebHttpBinding. You may enabled WebHttpBinding by as shown in the below code snippet.

    <endpointBehaviors>
            <behavior name="NewBehavior0">       
            <webHttp />
            </behavior>
    </endpointBehaviors>
 You can find more details here.


Saturday, December 28, 2013

Transactions in WCF

In my previous post i explained, Interview question and few details on WCF. Now in this article i will explain how WCF Transaction protocol.

Transaction is an important factor in any business application which contain CRUD operations. Here in WCF we have TransactionScope class which basically manages the transaction and also detech the transaction scope.


for ex. If your calling multiple methods and if any of method fails, then entire transaction will be rolled back unless its outside boundary of Scope.
WCF supports transaction on below bindings.
 
1.  WSHttpBinding
2.  WSFederationHttpBinding
3.  NetNamedPipeBinding
4.  NetTcpBinding
5.  WSDualHttpBinding



You need to specify the TransactionFlow attribute on all the contracts where it required transaction to be handled. where we have to specified that transaction are allowed for this specific method by assigning enum as 'TransactionFlowOption.Allowed'  

[ServiceContract]

public interface IUserDetails

{

    [OperationContract]

    [TransactionFlow(TransactionFlowOption.Allowed)]

    public void DeleteUserData();   
    [OperationContract]

    [TransactionFlow(TransactionFlowOption.Allowed)]

    public void UpdateUserData();   

}

there are following option present in TransactionFlow attribute.
TransactionFlowOption.Allowed :Transaction can be flowed.
TransactionFlowOption.NotAllowed: Transaction should not be flowed. This is default.
TransactionFlowOption.Mandatory: Transaction must be flowed.
 


Now implementing 'TransactionScopeRequired' attribute on specific method.

[OperationBehavior(TransactionScopeRequired = true)]
public void UpdateUserData()
{
  // database call goes here.
}

Once the scope assing, the last process will be enabling the transaction flow in config file.
 

Now consume the service by calling the UpdateUserData method and assign the scope block which check if the transaction method fails, if so then it will automatically rollback it.


using (TransactionScope Transcope = new TransactionScope())
{
  try
  {
   Services.UserDetailsService.UserDetailsServiceClient()
   clientVal = new Services.UserDetailsService.UserDetailsServiceClient();


   // code goes here to call method and assing the value.
   scope.Complete();
 }
catch (Exception ex)
{
scope.Dispose();

}

I know this will helps to understand the concepts of transaction in WCF , if you have any query or suggestion please put your comments to know more.
 

Saturday, December 21, 2013

Change schema name of tables, store procedure, views and functions

Today i come across one situation where i need to changes my current SQL schema to some other name. due to client requirement.so i searched few article and decided to write one article on same

Below query will returns list of all tables along with the schema name from your database.



SELECT TABLE_SCHEMA, TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES


If you want to add new schema you need to add that into sys.schemas table then only it will be accessible else it will give an error message as 


 Cannot alter the schema 'xxx', because it does not exist or you do not have permission.
 

IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'Excprod'))
BEGIN
    EXEC ('CREATE SCHEMA [Excprod] AUTHORIZATION [dbo]')
END

You can also view list of schema from below query and you will find new schema "Excprod" get added.

SELECT * FROM sys.schemas

Now, below query used to alter the scheme tables

ALTER SCHEMA Excprod TRANSFER dbo.Temp1
ALTER SCHEMA Excprod TRANSFER dbo.Temp2
ALTER SCHEMA Excprod TRANSFER dbo.temp3


You may also alter the schema for store procedure as well. to find the list of all store procedures from your
database just use.



select * from information_schema.routines
where routine_type = 'PROCEDURE'


below query will generate the select statement for all list of sp



select 'ALTER SCHEMA Excprod TRANSFER ' + SPECIFIC_SCHEMA + '.' + ROUTINE_NAME
from INFORMATION_SCHEMA.ROUTINES where ROUTINE_TYPE='procedure'
Result will be :


ALTER SCHEMA Excprod TRANSFER synprod.Usp_Response
ALTER SCHEMA Excprod TRANSFER synprod.Usp_Request


To view list of view from database use this


SELECT * FROM information_schema.VIEWS


Please comment if you want more details on this.

Wednesday, December 11, 2013

Interview questions on WCF


Today i would like to share something about WCF, This is my first post on Windows Communication Foundation (WCF). since last 1 year i worked on WCF, so i would like to share my experience/points with you.
First will see what exactly mean by WCF . It's Microsoft programming model which helps for building service-oriented application. where we can send/ received the data asynchronously. service endpoint is the main channel where client can request data.

It has very good features :

1. Extensibility
2. Interoperability
3. Data Contracts
4. Security
5. Transactions
6. AJAX and REST Support
You may refer more about wcf here
 
 
Below interview question helps you to know more about WCF.
 
1.How session management worked in WCF?
answer - WCF manage the session by instanciating the service class. It basically used the Instance Context class to manage the server side at server side. you can refer more about Session management in WCF.


 
2. Is overloading possible in WCF? and How?
Yes method overloading is possbile in WCF. But yes it will raise the error as contract mismatch during method overload.
By providing the unique operationcontract name you can resolved that issue. It has Name property which expose the wcf method to schemas.
Look at the below example.
 
[ServiceContract]

public interface ICalculate
{

    [OperationContract(Name="ADD")]
    string methodName(int x,int y);
    

    [OperationContract(Name = "DISPLAY")]
    string methodName(string val1, string val2);
}
 
all the method get called by their attribute name and parameter value. 
for ex
ClientApp client = new ClientApp();
           
string method1 = client.methodName(1, 1);

string method2 = client.methodName("sample1", "sample2");

3.how to track no of visit to your service.
WCF has very good feature which enable us to manage the service call. with the help of this you can easily track the count. extension point is used.


4. list types of binding and have you worked on netMsmqBinding or netNamedPipeBinding ?
 
 
If you know more unique questions, please do share it.

Saturday, November 23, 2013

creating word documents using open xml with asp.net

Now in this article i will explain how to use the Office Open XML C# (alternate solution to the Interop object. 

The Open XML provides you set of .NET API. It helps helps you manipulate and creating the documents in the Open XML Formats
in both the environments (i.e client and server both) and that is without help of MS office applications.

Before using Open XML Format, you have to add the below namespaces in your C# class. Add references to the Packaging and Spreadsheet API components with the following code.
 
 
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
 
Here is the CreateOpenXmlDocument function where you need to pass the filepath and it will created that doc file on specified positionl
 
public void CreateOpenXmlDocument(string filepath)
{
    
 using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
  {
    // Add a main document part.
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

    mainPart.Document = new Document();
    Body body = mainPart.Document.AppendChild(new Body());
    Paragraph para = body.AppendChild(new Paragraph());
    Run run = para.AppendChild(new Run());
    run.AppendChild(new Text("Create text sample text, coding stuffs daily..."));
  }
}



Here now i am integrating that function into my page_load event.


protected void Page_Load(object sender, EventArgs e)
{

      string FilePath =  @"C:\\Temp";
      CreateWordprocessingDocument(FilePath);

      FileInfo myDoc = new FileInfo(FilePath);
      Response.Clear();
      Response.ContentType = "Application/msword";
      Response.AddHeader("content-disposition", "attachment;filename=" + myDoc.Name);
      Response.AddHeader("Content-Length", myDoc.Length.ToString());
      Response.ContentType = "application/octet-stream";
      Response.WriteFile(myDoc.FullName);
      Response.End();

}
 
 
This is just an sample doc creation , you may even format the document with adding images, graphs, style to para and may more. Just refer this Microsoft article on how to do this. 

feel free to raise your suggestion/comments on this. Thanks you and happy coding....


 
 
 

Tuesday, November 12, 2013

Microsoft.Office.Interop.Word how to prevent word file opening

In my previous post i explained, how to Convert the dataset to xml string using  C# and asp.net
Now in this article i will explain how to prevent the word file opening, i have bunch of word document and i want to read/search text value out of it.  i tried that using Microsoft.office.Interop.Word object. 

Here is the sample code which prevent the word to opening the main window.
private void PreventOpenWord(string Filepath)
{
 Application word = new Application();
 FileInfo fileInfo = (FileInfo)file;


object save = false;
object confirmConversion = false;
object visible = false;
object skipEncodingDialog = true;
object readOnly = true;
object filename = fileInfo.FullName;

word.Visible = false;

Document srcDoc = word.Documents.Open(ref Filepath, ref confirmConversion, ref readOnly, ref missing,
    ref missing, ref missing, ref missing, ref missing,
    ref missing, ref missing, ref missing, ref visible,
    ref missing, ref missing, ref skipEncodingDialog, ref missing);




foreach (Microsoft.Office.Interop.Word.Range docRange in doc.Words)
{
if (docRange.Text.Trim().Equals(textToFind,
StringComparison.CurrentCultureIgnoreCase))
{
  
IsWordFound = true;
break;
}
}
}
catch (Exception ex)
{
 Response.Write("Error while reading file : " + ex.Message);
}
}


Hope this will helps you.. Happy  coding.. 

Sunday, October 27, 2013

Convert Dataset to xml string using C#


In my previous post i explained, Save images to database using SQL. Count string occurrence and much more articles realted with asp.net, SQL. Now in this article i will going to explain how to Convert the dataset to xml string using  C# and asp.net 

below is the short and sweet way to convert the dataset into xml.


DataSet dsUser = new DataSet();

SqlCommand cmdSelect = new SqlCommand("select name,age,location,ph,cell,status from userDetails ", conn);

SqlDataAdapter sda = new SqlDataAdapter(cmdSelect);

da.Fill(dsUser);

string strUserDetails = dsUser.GetXml();

Its very simple and easy method. Please post your comments for any suggestion.