Blog

  • C# Reading content from text files

    This is something I do frequently, and I always forget the streaming syntax, so here it is. There are couple of ways to do this. Firstly, from an application:

    1. From the properties panel, set the Build Action as Resource and the Copy to Output Directory as Copy Always
    2. From code this can then be accessed with:
    public class ListOfStrings: List
    {
    //@ctor
    public ListOfStrings()
    {
    string line;

    StreamResourceInfo sri = App.GetResourceStream(new Uri("Namespace;component/filename.txt", UriKind.Relative));
    using (TextReader tr = new StreamReader(sri.Stream))
    {
    while ((line = tr.ReadLine()) != null)
    {
    Add(tr.ReadLine());
    }
    }
    }
    }

    NOTE: Namespace;component/filename.txt: the Namespace and filename have to be replaced. Leave in the component syntax

    In a class library, it is slightly different.

    1. From the properties panel, set the Build Action as Embedded Resource
    2. From code this can then be accessed with:

    public class ListOfStrings: List
    {
    //@ctor
    public ListOfStrings()
    {
    string line;

    Assembly assembly = Assembly.GetExecutingAssembly();
    Stream stream = assembly.GetManifestResourceStream("Namespace.ResourceFolder.Filename.txt");

    using (TextReader tr = new StreamReader(stream))
    {
    while ((line = tr.ReadLine()) != null)
    {
    Add(tr.ReadLine());
    }
    }
    }
    }

     
    NOTE: Namespace.ResourceFolder. has to be replaced with a suitable value.

    Obviously, both examples return at list of string objects, one object per line.

  • Using Generics and Isolated Storage

    To read and write generic objects to isolated storage, you will need to pass the object types. This is so the DataContractSerializer knows how to process the object.

    So, to write data:

    /// 
    /// Write a generic object to Isolated Storage
    ///

    /// Type of object being written
    /// The object being written
    /// The location to write the object to
    private void WriteToIsolatedStorage(T dataToSave,string StreamLocation)
    {
    using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
    using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(StreamLocation, System.IO.FileMode.Create, isolatedStorageFile))
    {
    DataContractSerializer dcs = new DataContractSerializer(typeof(T));
    dcs.WriteObject(fileStream, dataToSave);
    }
    }
    }

     
    and to read data:

    /// 
    /// Read a generic object from isolated storage
    ///

    /// Type of the object being deserialised
    /// Location of the isolated storage file.
    /// A deserialised object of type T
    private T ReadFromIsolatedStorage(String StreamLocation)
    {
    using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
    using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(StreamLocation, System.IO.FileMode.Open, isolatedStorageFile))
    {
    DataContractSerializer dcs = new DataContractSerializer(typeof(T));
    return (T)dcs.ReadObject(fileStream);
    }
    }
    }

    To consume these methods:

    WriteToIsolatedStorage<List>(objListOfPersons, "PersonStore.xml");
    WriteToIsolatedStorage(objOrders, "Orders.xml");
    _objListOfPersons = ReadFromIsolatedStorage<List>("PersonStore.xml") as List;
    _objOrders= ReadFromIsolatedStorage("Order.xml") as List;

  • C# Event Delegates

    Using the “+=” notation when creating delegate event is a really fast
    way of coding but there is a caveat if the delegate is declared in the
    wrong place. for example declaring the handler inline, in a method:

    private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
    {
    EventBus.Event+= new EventHandler(EventBus_Event);
    //….do code here
    }

    When the btn_Click method is fired, an event handler is added to the
    EventBus.Event event. The clue (and problem) here is the worded
    “added”. If the btn_Click method is fired again, another identical
    handler is added, so now you have two. These will continue processing
    requests asyncronously, and continue to fire off your additional
    logic.. oh dear!

    To resolve this, simply abstrac the Event Delegation away from the UI
    method calls, unless they are being specifically created and removed
    for specific scenarios. I now add mine during class initialisation for
    generic events:

    private void EventBusDelegateEventHandlers()
    {
    //event handlers, these delegate control from the EventBus events.
    EventBus.Event1+= new EventHandler(EventBus_Event1);
    EventBus.Event2+= new EventHandler(EventBus_Event2);
    EventBus.Event3+= new EventHandler(EventBus_Event3);
    EventBus.Event4+= new EventHandler(EventBus_Event4);
    }

    I’m also using a centralised EventBus class that allows me to call and
    handle events across classes.

  • Extracting values from ServiceReference.ClientConfig

    You can open the document as an XDocument and go from there:

    var streamInfo = Application.GetResourceStream(new Uri(“ServiceReferences.ClientConfig”, UriKind.Relative));
    var config = XDocument.Load(streamInfo.Stream);
    var endpoints = from endpoint in config.Descendants(“endpoint”)
    where endpoint.Attribute(“name”).Value == endPointName
    select new { Address = endpoint.Attribute(“address”).Value };
    foreach (var endpoint in endpoints)
    {
    if (_binding.Security.Mode == BasicHttpSecurityMode.Transport)
    {
    String address = endpoint.Address.Replace(“http://&#8221;, “https://&#8221;);
    //address = string.Concat(address, “/secure/”);
    result = new EndpointAddress(address);
    }
    else
    {
    result = new EndpointAddress(endpoint.Address);
    }
    }
  • Invalid or malformed application: Check manifest

    When changing the namespace of a SL application, the startup object information must also be changed

  • Using ASPNET_RegSQL.exe with SQL Express databases in APP_DATA

    As discussed at Lance’s Whiteboard, a really easy way to hook up an ASPNET membership provider database to an application … perfect for rapid prototyping…

    “Creating a new DB in VisualStudio.NET 2005 is as simple as “Select APP_DATA node -> Add New Item -> Sql Database” and wah-lah you have a new aspnet.mdf file located in your APP_DATA folder.”

    and to register the ASPNET membership provider content within this database:

    aspnet_regsql -A all -C "Data Source=.\SQLEXPRESS;Integrated Security=True;User Instance=True" -d "C:\MyProject\APP_DATA\aspnetdb.mdf

  • blacklight.silverlight showcase

    Now this is the good shiz!!

    It is people like Martin, Dave, Neil and Mike that make the rest of our lives so easy! Great work guys, these controls are AWESOME!!

    :: blacklight.silverlight showcase ::

  • Self-signed SSL Certificate on Development PC

    Creating SSL based WCF services requires a SSL certificate. Adam Nofsinger’s blog gives a really easy way to do this using SelfSSL from the IIS Toolkit…

    Adam_Nofsinger.Tech: Self-signed SSL Certificate on Development PC

    …Unfortunately self signed SSL certs will not work from SilverLight … (e.g. HTTPS WCF service called from SL) … :-(…