Extension method for sorting keys in RESX file

2013/09/12

using System.Linq;
using System.Xml.Linq;
using System.Xml;
using System;

namespace SortResxFileKeys
{
  public static class XDocumentExtensionMethods
  {
    public static XDocument SortXDocumentResourceKeys(this XDocument xDoc)
    {
      XElement root = xDoc.Root;
      return new XDocument(
        new XElement(root.Name,
          root.Nodes().Where(n => n.NodeType == XmlNodeType.Comment),
          root.Elements().Where(n => n.Name.LocalName == “schema”),
          root.Elements(“resheader”).OrderBy(names),
          root.Elements(“assembly”).OrderBy(names),
          root.Elements(“metadata”).OrderBy(names),
          root.Elements(“data”).OrderBy(names)));
    }

    static Func<XElement, string> names =
            n => n.Attribute(“name”).ToString();
  }
}

Afterwards, the usage is simple

    XDocument xDoc = XDocument.Load(“SomeResxFileHere.resx”);
    xDoc.SortXDocumentResourceKeys();


WPF Application.DoEvents()

2010/09/25

VB6 or even .Net programmers know that in order not to block a desktop application UI when processing longer tasks, there is a little trick that can be applied, if the tasks contain a loop, which loop will allow a call to:
Application.DoEvents()
which will process Windows waiting messages.
But in WPF there is no such default method.
There are different approaches and implementations, but if you look for a fast solution, you can just add a reference to
System.Windows.Forms.dll
and the corresponding using directive and Application.DoEvents() is ready to use !
I usually use a directive with alias, in order not to conflict with other existing namespaces:
using SysWinForms = System.Windows.Forms;
So you can simply call:
SysWinForms.Application.DoEvents();


Using Reflection for retrieving values of static properties

2010/07/07

I had a list of classes for which I wanted to retrieve the static property Description; this is how I found out it can be done using Reflection:

Assembly assembly = Assembly.GetExecutingAssembly();
var types = assembly.GetTypes();
foreach (var type in types)
{
    if (!type.IsClass)
        continue;
    if (!type.IsSubclassOf(typeof(MyBaseClass)))
        continue;
    object obj = Activator.CreateInstance(type, new object[] { 0, 0 });
    PropertyInfo pi = obj.GetType().GetProperty("Description");
    string propValue = pi.GetValue(null, null).ToString();
}

Note:If Description is a property of the base class MyBaseClass, you’ll have to use obj.GetType().BaseType.GetProperty(“Description”); for this to work.
Also, as you can see, at least in my case, I need to create instances of the classes I work with, because Description property is defined in a base class, not in the derived ones, and the static property will be populated via constructors.


Searching files with LINQ

2009/11/10

LINQ is very powerful in many aspects of programming; for example, you can simulate the search for files feature of some known applications (Windows Explorer or Total Commander) with very few lines of code, as shown below:

    public List<FileInfo> SearchForFiles(String path, String ext, String search)
    {
        DirectoryInfo folder = new DirectoryInfo(path);
        return (from file in folder.GetFiles(ext, SearchOption.AllDirectories)
                where file.Name.ToLower().Contains(search.ToLower())
                orderby file.Name, file.Extension
                select file).ToList();
    }

Then, you can use in several ways the resulted list, for example by adding to your Windows Form application a DataGridView and setting its DataSource as following:

    dgvFiles.DataSource = SearchForFiles(path, extension, searchTerm).ToList();

Download a file in C#

2009/10/26

Easy task !
Import the System.Net namespace and after that use the DownloadFile method of the WebClient class:

public void DownloadFile(string link, string destination)
{
    using (WebClient webClient = new WebClient())
    {
        webClient.DownloadFile(link, destination);
    }
}

Navigate with C# WebBrowser control to a link and wait for full page loading

2009/10/26

If you need to build an application that is using the functionality of the WebBrowser control and want to wait until a page is loaded (somehow simulating the synchronous loading of a page), you can use the following piece of code:

private const int sleepTimeMiliseconds = 5;

public void NavigateAndWaitForLoad(WebBrowser wb, string link, int waitTime)
{
    wb.Navigate(link);
    int count = 0;
    while (wb.ReadyState != WebBrowserReadyState.Complete)
    {
        Thread.Sleep(sleepTimeMiliseconds);
        Application.DoEvents();
        count++;
        if (count > waitTime / sleepTimeMiliseconds)
            break;
    }
}


First peek on retrieving Entity Framework entities with Lambda expressions

2009/10/14

After adding an ADO.NET Entity Data Model item to the .Net project, you can easily retrieve a list of entities using Lambda expressions. Let’s suppose that the data model added to the project is called MyDataEntities and that it links to a table called Person, having Name as column. The following code can be used to retrieve the list:

    public static List<Person> GetPersons()
    {
        try
        {
            using (MyDataEntities context = new MyDataEntities())
            {
                return context.Person.OrderBy(p => p.Name).ToList<Person>();
            }
        }
        catch
        {
            // Do exception handling here
            throw;
        }
    }

%d bloggers like this: