Pages

Wednesday, October 19, 2011

Invoke Webservice Dyanamicly

Hi Friends this time I want to share , How to Invoke Webservice Dyanamicly and get Response
I Created a Class and Create a method to get all the webmethods in the given serivce Url
using System.Net;
using System;
using System.Web.Services.Description;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Xml.Serialization;

public class DyanamicProxyGeneration
{
 #region Members
 List _serviceMethods;
 Uri uri;
 String Url;
 WebRequest webRequest;
 Stream requestStream;
 ServiceDescription sd;
 ServiceDescriptionImporter servImport;
 MethodInfo[] methodInfo;        
 CodeCompileUnit codeCompileUnit;
 StringWriter stringWriter;
 CodeNamespace nameSpace;
 Type service;
 CSharpCodeProvider prov;
 Assembly assembly;
 CompilerResults results;
 CompilerParameters param;
 String[] assemblyReferences;                        
 #endregion
 public void DynamicInvocation(string Url)
 {
  try
  {
   uri = new Uri(Url + "?WSDL");
   webRequest = WebRequest.Create(uri);
   requestStream = webRequest.GetResponse().GetResponseStream();
   // Get a WSDL file describing a service
   sd = ServiceDescription.Read(requestStream);
   string sdName = sd.Services[0].Name;

   // Initialize a service description servImport
   servImport = new ServiceDescriptionImporter();
   servImport.AddServiceDescription(sd, String.Empty, String.Empty);
   servImport.ProtocolName = "Soap";
   servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;


   nameSpace = new CodeNamespace();
   codeCompileUnit = new CodeCompileUnit();
   codeCompileUnit.Namespaces.Add(nameSpace);
   // Set Warnings
   ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

   if (warnings == 0)
   {
    stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
    prov = new Microsoft.CSharp.CSharpCodeProvider();
    prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());
    
    // Compile the assembly with the appropriate references
    assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
    param = new CompilerParameters(assemblyReferences);
    param.GenerateExecutable = false;
    param.GenerateInMemory = true;
    param.TreatWarningsAsErrors = false;
    param.WarningLevel = 4;
    results = new CompilerResults(new TempFileCollection());
    results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
    assembly = results.CompiledAssembly;
    service = assembly.GetType(sdName);
    methodInfo = service.GetMethods();
    
    foreach (MethodInfo t in methodInfo)
    {
     if (t.Name == "Discover")
      break;
     _serviceMethods.Add(t.Name);
    }
   }
  }
  catch (Exception ex)
  {
  }
 }
}


public object GetResponse(MethodInfo[] methodInfoList)
        {
            Object response = null;
            ParameterInfo [] paramters;

            foreach (MethodInfo t in methodInfo)
            {
                //Invoke Method
                paramters  = new ParameterInfo []{};
                paramters = t.GetParameters();
                object[] param1 = paramters;
                Object obj = Activator.CreateInstance(service);
                response = t.Invoke(obj, param1);
                break;
            }
            if (response != null)
            {
                return response;
            }
            else
                return null;
        }

Monday, October 17, 2011

Return ObjectId From the Stored Procrdure & C#.

Hi Frineds, this time i want to share ,How to Get ObjectId From the Stored Procrdure in C#.
Here i have Written Both Stored Procedure and CSharp Code . Please look it and if you like this post. just comment it .


public class DataAccess
{
 private SqlConnection conn;
 public DataAccess()
 {
  string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
  // I used for SQLServer2005 .For other Databases check with "http://www.connectionstrings.com"
  conn = new SQLConnection(connectionString);
 }
// To Get Saved object Id 
 public int Save_Details(string parameter1, string paramter2,....., string parameterN)
   {
            int returnObjectId;
            conn.Open();            
            SqlCommand cmd = new SqlCommand("SP_Insert", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@parameter1", parameter1);
            cmd.Parameters.AddWithValue("@parameter2", parameter2);
   //.
   //.
   //.
   //.
            cmd.Parameters.AddWithValue("@parameterN", parameterN);
            cmd.Parameters.Add("@ObjectId", SqlDbType.Int, 0, "Id");
            cmd.Parameters["@ObjectId"].Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();

            returnObjectId = (int)cmd.Parameters["@ObjectId"].Value;
            conn.Close();
            if (returnObjectId > 0)
            { return returnObjectId;}
            else
   {return 0;}
        }

}


--Stored Procedure code
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_Insert] 

 @parameter1 nvarchar(50),
 @parameter2 nvarchar(50),
 -- .
 -- .
 -- .
 @parametern nvarchar(50),
 @Object_Id int OUTPUT
 

AS
BEGIN
   INSERT INTO [dbo].[TableName]
           ([Parameter1]
           ,[Parameter2]
           ,[ParameterN])
     VALUES
     (@parameter1,
  @parameter2,
     @parametern)   
     
END

select @Object_Id =@@Identity

Wednesday, October 5, 2011

Create Dynamic controls

Somtime we need controls created at runtime . here i am giving the example of TextBox. How to create multiple textboxes at runtime in Asp.Net. with the help of this you can also create other conrtols also.
Example:
--------
// 1.Create a div or Table where you have to create textboxes
// <table>
// <tr>
// <td id="DynamicTextBox" runat="server" style="width: 165px" align="left"></td>
// </tr>
// </table>

// 2. Create a list or collection

//Create Dynamic Textbox

int counterTextBox =0;

foreach (var item in collection)
{
      //Create Dynamic Textbox
      System.Web.UI.WebControls.TextBox tb = new System.Web.UI.WebControls.TextBox();
      tb.Width = 495;
      tb.Height = 18;
      tb.TextMode = TextBoxMode.SingleLine;
      tb.ID = "TextBox_ID" + ++coutnerTextbox;
      DynamicTextBox.Controls.Add(tb);
      DynamicTextBox.Controls.Add(new LiteralControl("<br/>"));          

} 

Sunday, October 2, 2011

Compile Soultion/Projects by Batch Files

So this time i am writing abt compiling Solutions Or pRoject with the help of Batch File .  That  will really helpfull when you have multiple solutions and having dependency on it .You dont need to open each solution and build it . one by one . Just take Latest/Update with your source control and build it with the crssponding batch file that you have created. If you want to do more you can make a separate batch file to build all batch file one by one . So it is not a very big deal to doing this ..

I have put the one template for a one solution you just Replace You data ( which are in CAPITAL LETTERS) and try the same .After builing you will get the log file in BUildLlog Folder ( it will be created when you are build your soultion)
@echo off

set Configuration="debug"

set MSBuildPath=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\



set dir1="%CD%\(PATH OF PROJECT 1).csproj"
set dir2="%CD%\(PATH OF PROJECT 2).csproj"
set dir3="%CD%\(PATH OF PROJECT 3).csproj"  
set dir4="%CD%\(PATH OF PROJECT 4).csproj"
set dir5="%CD%\(PATH OF PROJECT 5).csproj"  

ECHO Building (PUT THE PROJECT/SOLUTION/NAMESPACE FOR REFRENCE(it will show in the screen) )


%MSBuildPath%MSBuild /logger:FileLogger,c:\windows\Microsoft.Net\Framework\v2.0.50727\Microsoft.Build.Engine.Dll;LogFile="BuildLogs\PROJECT_NAME.txt" %dir1% /p:Configuration=%Configuration%
%MSBuildPath%MSBuild /logger:FileLogger,c:\windows\Microsoft.Net\Framework\v2.0.50727\Microsoft.Build.Engine.Dll;LogFile="BuildLogs\PROJECT_NAME.txt";Append %dir2% /p:Configuration=%Configuration%
%MSBuildPath%MSBuild /logger:FileLogger,c:\windows\Microsoft.Net\Framework\v2.0.50727\Microsoft.Build.Engine.Dll;LogFile="BuildLogs\PROJECT_NAME.txt";Append %dir3% /p:Configuration=%Configuration%
%MSBuildPath%MSBuild /logger:FileLogger,c:\windows\Microsoft.Net\Framework\v2.0.50727\Microsoft.Build.Engine.Dll;LogFile="BuildLogs\PROJECT_NAME.txt";Append %dir4% /p:Configuration=%Configuration%
%MSBuildPath%MSBuild /logger:FileLogger,c:\windows\Microsoft.Net\Framework\v2.0.50727\Microsoft.Build.Engine.Dll;LogFile="BuildLogs\PROJECT_NAME.txt";Append %dir5% /p:Configuration=%Configuration%

ECHO (PUT THE PROJECT/SOLUTION/NAMESPACE FOR REFRENCE(it will show in the screen) ) Completes
pause