Wednesday, June 09, 2010

How to: call/Invoke a web service without adding web reference

Why would anybody want to do this since there is a simple way given by Visual studio by adding a Web Reference from Solution Explorer. But recently wants to build an application which should install in different client locations with different names etc. As in the installer we can give different custom names to virtual directory this will not work for me.  That means “Virtual Directory” can be different for each client in that case i need modify the web reference as per the “Virtual Directory” name of the hosted solution.

So for that i end up adding proxy class of the web service in my solution by using WSDL tool. I need to generated Proxy class of the web service that i have created and add the proxy class in my Web solution.  For example here is a sample web service code for simplicity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace SampleWebSerivce
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}


Once your done with your custom web methods, you add the web reference where you actually consume the web service methods. When you add a web reference - based on the WSDL specifications IDE actually creates proxy classes in your application which represents the web service classes and its methods on the remote server



Visual Studio provides Intellisense with Web services, which will not be accurate till you update your web reference each time you change your web service, it is because the proxy classes which are local to your solution are being used to offer you the Intellisense. So, ultimately when you invoke a Web method you are invoking a method in one of these proxy classes. These classes, in turn, are capable of invoking the remote methods on the Web Service URL.



So, every time the web service is updated, these proxy classes need to be regenerated by clicking Update Web Reference. However, the proxy classes do not always have to be generated from the IDE, .NET also gives us the WSDL.exe utility to manually generate these proxy classes and include them in your project.



Here is the syntax to create Proxy class from WSDL tool.wsdl



Just grab the class, and add in the App_Code folder if its a web site or you can add in root folder if it is a web solution.



If you open the proxy class you will notice  the constructor of the proxy class contains "url" member property which is by default assigned the url of the website in which the web service exists. You can store the web service url in web.config or in database or as per your logic.



So, finally to call the "Hello World" web method - you need to create object of this proxy class and assign the url property correctly as below:



public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Service1 objService = new Service1();
        objService.Url =
            System.Configuration.ConfigurationManager.AppSettings["WebServiceUrl"];
        Response.Write("Output of Web method call: " + objService.HelloWorld());
    }
}


Finally, You can call web service method without adding Web Reference. But make sure you update the proxy class through WSDL utility as and when you have any changes in the Web Service.

Thursday, May 27, 2010

How to: Deploying Sliverlight applications in different machines

I am working on my silverlight application and i need to deploy the same on multiple machines as i need to test its performance on different servers.

Here is a small work around to do this.

  • Unzip the .XAP file in the clientBin folder of the website with WinRar or other archivator or Rename your XAP file to zip
  • Extract the zip file to a folder
  • Edit ServiceReference.ClientConfig in notepad
  • Here is the snippet of ServiceReference.ClientConfig.
<configuration>
    <system.serviceModel>
        <bindings>
            <customBinding>
                <binding name="CustomBinding_DPService" closeTimeout="00:10:00" openTimeout="00:10:00" sendTimeout="00:10:00"  receiveTimeout="00:10:00">
                    <binaryMessageEncoding />
                    <httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
                        <extendedProtectionPolicy policyEnforcement="Never" />
                    </httpTransport>
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="/SLSampleWebsite/DPService.svc" 
                binding="customBinding" bindingConfiguration="CustomBinding_DPService"
                contract="ServiceReference1.DPService" name="CustomBinding_DPService" />
        </client>
    </system.serviceModel>
</configuration>



  • Update the endpoint address in the XML with relevant address if its hosted in different machine or in the same machine.


  • Add the folder contents to ZIP file



            <endpoint address="http://Server1/SLSampleWebsite/DPService.svc" 



  • After updating the ServiceReference.ClientConfig, Compress all files again to create new .ZIP file.


  • Delete the old .XAP file and remame the .ZIP to XAP file



It works great!

Wednesday, May 26, 2010

Tips & Tricks : Visual Studio

Shortcuts Its fun and helpful. They are helpful for faster development and easy. Here are the few shortcuts that we use regularly.

Usage C# Key Description
View.ShowSmartTag CTRL + .  
Edit.ParameterInfo CTRL + SHIFT + SPACE  
Edit.Find CTRL + F Quick find
Edit.IncrementalSearch CTRL + I Incremental find
Edit.FindInFiles CTRL + SHIFT + F Find in files
Edit.Replace CTRL + H Quick replace
Edit.ReplaceInFiles CTRL + SHIFT + H Replace in files
Edit.GotoNextLocation F8 Go to next location (in search results)
Edit.GotoPrevLocation SHIFT + F8 Go to previous location (in search results)
Edit.FindNext F3 Repeat search
Edit.FindPrevious SHIFT + F3 Search previous
Edit.FindNextSelected CTRL + F3 Search for next with selected text
Edit.FindPreviousSelected CTRL + SHIFT + F3 Search for previous with selected text
     
View.NavigateBackward CTRL + - Go back to previous location (Browser-style)
View.NavigateForward CTRL + SHIFT + - Go forwards to next location
View.ViewCode F7 View code
View.ViewDesigner SHIFT + F7 View designer when in markup
View.ViewMarkup SHIFT + F7 View markup when in designer
     
Edit.CycleClipboardRing CTRL + SHIFT + V Cycle through Visual Studio clipboard
     
Edit.GotoBrace CTRL + ] Jump to opposing brace / XML tag
Edit.GotoBraceExtend CTRL + SHIFT + ] Select text to the opposing brace / tag
     
Edit.GotoFindCombo CTRL + / Jump to the find combo in the toolbar
     
Window.ShowEzMDIFileList CTRL + ALT + DOWN ARROW Show popup of all open files
     
Debug.Start F5 Start with debugger
Debug.StartWithoutDebugging CTRL + F5 Start without debugger
Debug.Restart CTRL + SHIFT + F5 Restart the program
Debug.StopDebugging SHIFT + F5 Stop debugger
Debug.RunToCursor CTRL + F10 Run to the cursor
Debug.ToggleBreakpoint F9 Set / remove breakpoint
Debug.DeleteAllBreakpoints CTRL + SHIFT + F9 Delete all breakpoints
Debug.EnableBreakpoint CTRL + F9 Enable a breakpoint
Debug.StepInto F11 Step into a method
Debug.StepOut SHIFT + F11 Step out of a method
Debug.StepOver F10 Step over a line
     
Tools.RecordTemporaryMacro CTRL + SHIFT + R Start recording a macro
Tools.PlayTemporaryMacro CTRL + SHIFT + P Playback a macro

 

If you want an even more comprehensive list of keyboard combinations, you can check out the following links, or go exploring in Tools > Options > Keyboard in Visual studio.

C# Keybindings

VB Keybindings

Tips & Tricks : Visual Studio

1. Disable HTML Navigation bar.

Tools -> Options -> Text Editor -> HTML –> Uncheck Navigation Bar option

2. Auto insert quotes when typing.

Tools -> Options -> Text Editor -> HTML -> Format -> Check "Insert attribute value quotes when typing"

3. Format HTML on paste

Tools -> Options -> Text Editor -> HTML -> Miscellaneous -> Format HTML on Paste

Tuesday, May 25, 2010

How To: Get File Time [C#]

To get file time information like attributes and all or when any file was created, last modified or accessed. For getting this you can get file DateTime info by using either static methods of File class or instance methods of FileInfo class.

Get file times using File class

Use File class when you want to get just one specific time, for example if you are only interested in a file last modification time. To do this use static method File.GetLastWri teTime with file path as a parameter. File class also provides static methods to get file creation time or file last access time. You can also get this times in UTC, e.g. to get file last write time in UTC use File.GetLastWri teTimeUtc.

// local times
DateTime creationTime = File.GetCreationTime(@"c:\Demo.txt");
DateTime lastWriteTime = File.GetLastWriteTime(@"c:\Demo.txt");
DateTime lastAccessTime = File.GetLastAccessTime(@"c:\Demo.txt");
// UTC times
DateTime creationTimeUtc = File.GetCreationTimeUtc(@"c:\Demo.txt");
DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(@"c:\Demo.txt");
DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(@"c:\Demo.txt");
// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 5/25/2010 10:10:00 PM
Console.WriteLine(lastWriteTimeUtc);  // 5/25/2010 10:10:00 PM


Get file times using FileInfo class



Use instance of  FileInfo class when you want to get more than one file time or any other information's about the file (like file attributes). Advantage is that you will get all needed information's just in one disk access. See following example.



FileInfo fileInfo = new FileInfo(@"c:\Demo.txt");
// local times
DateTime creationTime = fileInfo.CreationTime;
DateTime lastWriteTime = fileInfo.LastWriteTime;
DateTime lastAccessTime = fileInfo.LastAccessTime;
// UTC times
DateTime creationTimeUtc = fileInfo.CreationTimeUtc;
DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc;
DateTime lastAccessTimeUtc = fileInfo.LastAccessTimeUtc;
// write file last modification time (local / UTC)
Console.WriteLine(lastWriteTime);     // 5/25/2010 10:10:00 PM
Console.WriteLine(lastWriteTimeUtc);  // 5/25/2010 10:10:00 PM


Hope this is useful.