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.

Disabling Browser Cache In C# and ASP.NET

Disable browser caching seems to revolve around how to make it work in IE, Mozilla and other browsers.

Here is the code that will disable browser cache. I have used this and it worked for me.

//Used for disabling page caching 
 HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
 HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
 HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
// Requires for IE
 HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
// Requires for Mozilla
 HttpContext.Current.Response.Cache.SetNoStore();

Using SortedList for FileWatcher

I need to do an update and archive files based on a condition in my application. So i have used sortedList to get all the files by processing the thread in my service. For details check my last post on this Multi Threading Using parameters for reference.

So I have updated on of my method DoTXT to achieve this from my previous post.

/// <summary>
        /// Thread 2, Displays that we are in thread 2
        /// </summary>
        public void DoTXT()
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    // Write your TXT LOGIC HERE, Moving files and updating database etc
                    Console.WriteLine("Display Thread 2 " + strExt);
                    _threadOutput = "Hello Thread 2";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    string[] Files = Directory.GetFiles("D://ThreadSample//Files//");
                    SortedList sList = new SortedList();
                    if (Files.Length > 0)
                    {
                        foreach (string s in Files)
                        {
                            try
                            {
                                if (Path.GetExtension(s).ToUpper().Equals(strExt))
                                {
                                    try
                                    {
                                        // if you date falls between two dates you need to change the condition while comparing.
                                        // Check the File class for rest of useful methods you require..File.GetLastAccessTime
                                        if (File.GetLastWriteTime(s).ToShortDateString().Equals(strDateTime))
                                        {
                                            DateTime dt = File.GetLastWriteTime(s);
                                            sList.Add(dt, Path.GetFullPath(s));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                        // Getting information from the SortedList.
                        foreach (string filename in sList.Values)
                        {
                            // Get all these file to zip for archive
                            Console.WriteLine("filename with sorted list." + filename);
                            // Do the db logic..
                        }
                    }
                    // we are in thread #2
                    Console.WriteLine("DoTXT Output --> {0}", _threadOutput + " datetime: -- > " + strDateTime);
                }
            }
        }

Multi Threading using Parameters

Recently i need write a file watcher. So i need to do based on the file types. I have written little bit of code for doing so. Here is the snippet of this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Collections;
namespace ThreadSample
{
    class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            // 
            DisplayThread objContainer1 = new DisplayThread(".TXT", DateTime.Now.ToShortDateString());
            Thread objThread1 = new Thread(new ThreadStart(objContainer1.DoTXT));
            objThread1.Start();
            DisplayThread objContainer2 = new DisplayThread(".PDF", DateTime.Now.ToShortDateString());
            Thread objThread2 = new Thread(new ThreadStart(objContainer2.DoPDF));
            objThread2.Start();
            Console.ReadLine();
        }
        
    }
    class DisplayThread
    {
        private bool _stopThreads = false;
        public bool StopThreads
        {
            set
            {
                _stopThreads = value;
            }
        }
        private string strExt, strDateTime = "";
        public DisplayThread(string Ext, string datetime)
        {
            strExt = Ext;
            strDateTime = datetime;
        }
        // shared memory variable between the two threads
        private string _threadOutput = "";
        /// <summary>
        /// Thread 1, Displays that we are in thread 1
        /// </summary>
        public void DoPDF( )
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    // Write your PDF LOGIC HERE, Moving files and updating database etc
                    Console.WriteLine("Display Thread 1 " + strExt);
                    _threadOutput = "Hello Thread 1";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    string[] Files = Directory.GetFiles("D://ThreadSample//Files//");
                    if (Files.Length > 0)
                    {
                        foreach (string s in Files)
                        {
                            try
                            {
                                if (Path.GetExtension(s).ToUpper().Equals(strExt))
                                {
                                    try
                                    {
                                        // if you date falls between two dates you need to change the condition while comparing.
                                        if (File.GetLastWriteTime(s).ToShortDateString().Equals(strDateTime))
                                        Console.WriteLine(s);
                                        // do the db logic and filemoving etc
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                    }
                    // we are in thread #1
                    Console.WriteLine("DoPDF Output --> {0}", _threadOutput + " datetime: -- > " + strDateTime);
                }
            }
        }
        /// <summary>
        /// Thread 2, Displays that we are in thread 2
        /// </summary>
        public void DoTXT( )
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    // Write your TXT LOGIC HERE, Moving files and updating database etc
                    Console.WriteLine("Display Thread 2 " + strExt);
                    _threadOutput = "Hello Thread 2";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    string[] Files = Directory.GetFiles("D://ThreadSample//Files//");
                    if (Files.Length > 0)
                    {
                        foreach (string s in Files)
                        {
                            try
                            {
                                if (Path.GetExtension(s).ToUpper().Equals(strExt))
                                {
                                    try
                                    {
                                        // if you date falls between two dates you need to change the condition while comparing.
                                        // Check the File class for rest of useful methods you require..File.GetLastAccessTime
                                        if (File.GetLastWriteTime(s).ToShortDateString().Equals(strDateTime))
                                            Console.WriteLine(s);
                                        // do the db logic and filemoving etc
                                    }
                                    catch (Exception ex)
                                    {
                                        throw ex;
                                    }
                                }
                            }
                           
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                       
                    }
                    // we are in thread #2
                    Console.WriteLine("DoTXT Output --> {0}", _threadOutput + " datetime: -- > " + strDateTime);
                }
            }
        }
    }
}


I need to check files based on the last modified date. so i am using File class to know the GetLastWriteTime. Instead you can also using System.IO.FileInfo to get the information of LastWriteTime.



string[] Files =  Directory.GetFiles("D://ThreadSample//Files//");
System.IO.FileInfo fileInfo = null;
if (Files.Length > 0)
 {
   foreach (string s in Files)
   {
     fileInfo = new System.IO.FileInfo(s);
      try
      {
        DateTime LastWT = fileInfo.LastWriteTime;
        Console.WriteLine("LastWrite Time" + LastWT.ToShortDateString());
       }
       catch (Exception ex)
       {
         throw ex;
       }
    }
}


Happy coding :-)

Thursday, May 20, 2010

HEX to Color in Silverlight GridView

Recently i need to use colors in my grid cells, for that i have written code in RadGridView_RowLoaded to set the colors. But i had trouble setting color as background to cells. I could able to achieve this way.

 // Setting backgrounds to cells 
        private void RadGridView1_RowLoaded(object sender, Telerik.Windows.Controls.GridView.RowLoadedEventArgs e)
        {
            string strPirority = "";
            string strStage = "";
            if (e.Row.Item != null)
            {
                strPirority = ((TelerikOrderSilverlight.ServiceReference1.v_order_mgmt)(((Telerik.Windows.Controls.RadRowItem)(((Telerik.Windows.Controls.GridView.GridViewRowItemEventArgs)(e)).Row)).Item)).priority.ToString();
                if (((TelerikOrderSilverlight.ServiceReference1.v_order_mgmt)(((Telerik.Windows.Controls.RadRowItem)(((Telerik.Windows.Controls.GridView.GridViewRowItemEventArgs)(e)).Row)).Item)).stage != null)
                {
                    strStage = ((TelerikOrderSilverlight.ServiceReference1.v_order_mgmt)(((Telerik.Windows.Controls.RadRowItem)(((Telerik.Windows.Controls.GridView.GridViewRowItemEventArgs)(e)).Row)).Item)).stage.ToString();
                }               
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (e.Row.Cells[i].Column.UniqueName == "priority")
                    {
                        if (strPirority == "Critical")
                        {
                            // Can set this way using solid
                            e.Row.Cells[i].Background = new System.Windows.Media.SolidColorBrush(Colors.Red);
                        }
                    }
                    if (e.Row.Cells[i].Column.UniqueName == "MileStone")
                    {
                        if (strStage.Length > 0)
                        {
                            // You can set this way using Hexa codes.
                            if (strStage.Substring(0, 4) == "Bill")
                            {
                                e.Row.Cells[i].Background = new System.Windows.Media.SolidColorBrush(GetColorFromHexa("#FF000000"));
                            }
                        }
                    }
                }
            }
        }
        private Color GetColorFromHexa(string hexaColor)
        {
            return Color.FromArgb(
                    Convert.ToByte(hexaColor.Substring(1, 2), 16),
                    Convert.ToByte(hexaColor.Substring(3, 2), 16),
                    Convert.ToByte(hexaColor.Substring(5, 2), 16),
                    Convert.ToByte(hexaColor.Substring(7, 2), 16));
        }


Here is the list of all predefined SolidColorBrush objects.

Thursday, May 13, 2010

Configuring IIS for Silverlight Applications

Recently i want to deploy my Silverlight application Window 2003 Server. I have copied all the files and thought it will work as in development machine. But i am not able to run on Window 2003 server, so for that i need to configure my server to support silverlight.

Here is the URL that found helpful.

How to Create Hidden folders using c#

using System.IO; 
// folder path that you want to create
string path = @"c:\createfolder\NewFolder"; 
if (!Directory.Exists(path)) 
{ 
  // Creating folder 
  DirectoryInfo di = Directory.CreateDirectory(path); 
  // setting attributes
  di.Attributes = FileAttributes.Directory | FileAttributes.Hidden; 
}