Tag: .NET

  • Persisted Properties

    Back in classic ASP.NET I’d persist data extract from a web service in base class property as follows:

    private string m_stringData;
    public string _stringData
    { get {
    if (m_stringData==null)
    {
    //fetch data from my web service
    m_stringData = ws.FetchData()
    }
    return m_stringData;
    }
    }

    This way I could always simple use _stringData and know that I’d always get the data I was after (sometimes I’d use Session state as a store instead of a private member variable).

    In Silverlight with a WCF this doesn’t work, because the WCF service has to be called asynchronously.

    So, how do I get round this?… There are a number of routes to take. One method involves wrapping the messages synchronously and can be found at codeplex

    Another alternative that is less verbose, and arguably easier, to follow is using a lambda expression as follows:

    private string m_stringData;
    public string _stringData
    {
    get
    { //if we don't have a list of departments, fetch from WCF
    if (m_stringData == null)
    {
    StringServiceClient client = new StringServiceClient();
    client.GetStringCompleted +=
    (sender, e) =>
    {
    m_stringData = e.Result;
    };
    client.GetStringAsync();
    }

    return m_stringData;
    }
    }

    A final solution was posted on this stackoverflow thread

  • 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.

  • Accessing the ASP.NET Authentication, Profile and Role Services

    Creating service to control Authentication, Profiles and Roles makes a lot of sense. It allows the abstraction of these commonly reused elements into a Service Oriented Architecture. It would also allow easy repositioning of these features into a centralised source (for common applications) or to be embedded into a standalone application, with zero code rewritting.

    There is an excellent article discussing this here:

    Brad Abrams : Accessing the ASP.NET Authentication, Profile and Role Service in Silverlight

  • Code Standards Enforcement

    To help with the enforcement of code standards within C# the following tool may be of use:

    Blog by Joel Fjordén a.k.a. Will o Wisp – Code Style Enforcer

  • Using ADO.NET Data Services

    Good work from Beth Massi on ADO.NET Data Services – this is simplicity incarnate! I reckon that you could have prototype code up and running within half-an-hour…

    Beth Massi – Sharing the goodness that is VB : Using ADO.NET Data Services

  • Which domain groups is a user in?

    Which domain groups is a user in?

    A console application to determine which groups a user is in:

    My.User.InitializeWithWindowsUser() Dim identity As System.Security.Principal.WindowsIdentity = TryCast(My.User.CurrentPrincipal.Identity, System.Security.Principal.WindowsIdentity) Debug.WriteLine(identity.Name) For Each group As System.Security.Principal.SecurityIdentifier In identity.Groups() Debug.WriteLine(group.Translate(GetType(System.Security.Principal.NTAccount)), “group”) Next
  • Rotate Data table

    Private Function RotateDataTable(ByVal dt As DataTable) As DataTable   Dim dtNew As New DataTable
    'for each row, create a column
    For i As Integer = 0 To dt.Rows.Count() - 1
    Dim dc As New DataColumn(dt.Rows(i)(0))
    dtNew.Columns.Add(dc)
    Next
    'for each column, create a row
    For j As Integer = 1 To dt.Columns.Count() - 1
    Dim dr As DataRow
    dr = dtNew.NewRow()
    For k As Integer = 0 To dt.Rows.Count() - 1
    dr(k) = dt.Rows(k)(j)
    Next
    dtNew.Rows.Add(dr)
    Next
    Return dtNew
    End Function