DevExpertise

Practical tips and tricks for all things .NET, SharePoint, Silverlight, InfoPath, and general application development.

Implementing a LINQ version of SQL’s LIKE Operator

Posted by DevExpert on 25th September 2009

One of the requirements of one of my recent projects was to implement a search page which allowed the user to enter a search term that supported wildcards.  The search term could contain any number of wildcards in any position within that term.

If you’ve done anything like this before, you probably know there’s nothing built-in to LINQ that supports this type of behavior.  Sure, you could use a combination of String.StartsWith, String.EndsWith, or String.Contains, but this could quickly become too cumbersome if there are many wildcards and/or they are scattered throughout the search term.  Let’s look at a couple simple examples to illustrate…

Pretend for a second I was doing this in SQL, and I needed to get all values that start with the letter T.  I would do this:

select * from SomeTable where SomeField LIKE 'T%'


The .NET/LINQ equivalent would be this:

var results = (from v in values where v.StartsWith("T") select v);


Not too difficult.  However, what if you wanted to do the SQL-equivalent of this:

select * from SomeTable where SomeField LIKE '%a%a%'


You’d have do a little creative parsing.  It gets even worse when you as the developer doesn’t know what search term will be entered, how many wildcards will be included, and where in the term they appear.  It all has to be dynamic.

I did a little poking around to see if anyone has done this before, and the only thing I could find was recommendations on using StartsWith/EndsWith/Contains, which I already ruled out.  I also found the SqlMethods.Like() method which sounded perfect.  However after further research, discovered it can only be used on an entity directly retrieved from a DataContext, such as this:

using (DemoDataContext db = new DemoDataContext()){
    var results = (from v in db.SomeTable where SqlMethods.Like(v.SomeField, "*a*a*") select v);
}


If you try to use the SqlMethods.Like() method on anything except a DataContext’s Table<T>, you’ll get the following message:

“Method ‘Boolean Like(System.String, System.String)’ cannot be used on the client; it is only for translation to SQL.”

So much for that.  I decided to write my own extension method.  I figured I could write one fairly easily using a regular expression, and I was right!  I checked out a trusty RegEx cheat sheet and found the following relevant metacharacters:

  • ^     Indicates the start of a string
  • $     Indicates the end of a string
  • *     Indicates zero or more of previous expression

Knowing this, I wrote the following extension method:

public static bool Like(this string value, string term) {
    Regex regex = new Regex(string.Format("^{0}$", term.Replace("*", ".*")), RegexOptions.IgnoreCase);
    return regex.IsMatch(value ?? string.Empty);
}


Which I can then use like this:

var results = (from v in values where v.Like("*a*a*") select v);


I can even simplify this by wrapping it up in another extension method:

public static IEnumerable<string> Like(this IEnumerable<string> source, string expression) {
    return (from s in source where s.Like(expression) select s);
}


Now all I have to do is the following:

var results = values.Like("*a*a*");


Finally, a quick usage example to prove it works:

var values = new List<string>(){
    "Widget", "Gadget", "Whatchamacallit", "Gizmo",
    "Thingamabob", "Thingamajig", "Doodad", "Doohickey"};

var results = values.Like("*a*a*");

foreach (string result in results) {
    Console.WriteLine(result);
}


Which outputs:

image

 

Hopefully you’ll find this useful!

Tags: , , ,
Posted in .NET, LINQ, SQL Server | 3 Comments »

Installing a Theme as a SharePoint Feature

Posted by DevExpert on 11th February 2009

I briefly went over my approach to creating a custom SharePoint theme in my previous post, and I even included a downloadable solution package that you can install on your farm (provided you have the .NET 3.5 Framework installed).  How did I accomplish this?  Pretty easily actually.  Unfortunately there isn’t much documentation or examples of this out there, so allow me to put an end to that!

SharePoint features and solutions are absolutely essential if you want to provide an easy and maintainable method of deploying custom artifacts to your SharePoint servers.  A theme is a perfect candidate for this, as everything is file-system based and located with the 12 directory.  The only odd thing that throws a monkey wrench in this seemingly simple process is the SPTHEMES.XML file, which must be updated to include an entry for your custom theme.  Here’s a portion of that file, with the custom theme I developed in my previous post highlighted:

image

Now, you could by all means include the SPTHEMES.XML file in your solution and have it overwrite the existing file, but what if you have other themes defined in your file?  That approach will overwrite it, and you’ll have to reenter everything.  The recommended approach to this is to create a feature receiver that fires when the feature is installed and modifies the SPTHEMES.XML.  When the feature is installed, a custom <Templates> section is added for the custom theme, and when it’s uninstalled it’s removed.

NOTE: A feature is “installed” when you run the STSADM –o installfeature command, or when a feature is contained in a solution package and that solution package is deployed.

One important thing to mention is that this feature is scoped for the farm, not an individual site-collection or site, as the files deployed to the file system are used by the entire farm.  Let’s first take a look at the feature.xml file:

<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
         Id="2D965A22-73A9-4e00-A530-06F2AF6EC89F"
         Title="DevExpertise Vista Theme"
         Description="Adds the DevExpertise Vista Theme"
         Scope="Farm"
         Version="1.0.0.0"
         ImageUrl="DevExpertise\devexpertiseLogo.png"
         ReceiverAssembly="DevExpertise.SharePoint.Themes, Version=1.0.0.0,
                           Culture=neutral, PublicKeyToken=d39eedb6cff9b1c8"
         ReceiverClass ="DevExpertise.SharePoint.Themes.FeatureReceiver">
</Feature>

As you can see, it is executing a custom FeatureReceiver class.  At a high-level, the receiver looks like this:

[UPDATED 5/27/2009]

I received a couple comments that let me know that if this feature is activated on a farm with multiple front-ends, then the FeatureActivated event only gets fired on a single web front-end.  This is absolutely TRUE, and an oversight on my part (thanks guys!).  The solution is extremely simple – put your code in the FeatureInstalled and FeatureUninstalling events instead, as these get fired on EVERY web front-end in your farm!!  I’ve modified the code to reflect this:

public class FeatureReceiver: SPFeatureReceiver {

    private enum ModificationType { Add, Remove }

    public override void FeatureInstalled(SPFeatureReceiverProperties properties) {
        ModifySPTheme(ModificationType.Add);

        // if necessary, loop through all sites and set theme
    }

    public override void FeatureUninstalling(SPFeatureReceiverProperties properties) {
        ModifySPTheme(ModificationType.Remove);

        // if necessary, loop through all sites and reset theme
    }

    public override void FeatureActivated(SPFeatureReceiverProperties properties) {
        // do nothing
    }

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
        // do nothing
    }
}

For the sake of simplicity, I’m not including code to set the theme on any sites.  Since this is a farm feature, it doesn’t make sense to set the theme for a particular site here, but by all means if you wanted to you could.  Basically this feature receiver is only for modifying the SPTHEMES.XML file.

Let’s take a look at the ModifySPTheme() method.  It uses LINQ to XML to open and parse the file, add the necessary elements when the feature is installed, and remove it when the feature is uninstalling:

private void ModifySPTheme(ModificationType type) {
    XDocument doc = null;
    XNamespace ns = "http://tempuri.org/SPThemes.xsd";

    // path to the SPTHEMES.XML file
    string spthemePath = Path.Combine(SPUtility.GetGenericSetupPath(@"TEMPLATE\LAYOUTS\1033"), "SPTHEMES.XML");
    string contents = string.Empty;

    // read the contents of the SPTHEMES.XML file
    using (StreamReader streamReader = new StreamReader(spthemePath)) {
        contents = streamReader.ReadToEnd();
        streamReader.Close();
    }

    using (StringReader stringReader = new StringReader(contents.Trim())) {
        // create a new XDocument from the contents of the file
        doc = XDocument.Load(stringReader);

        // retrieve all elements with a TemplateID of 'VISTA'.  At most, there should only be one
        var element = from b in doc.Element(ns + "SPThemes").Elements(ns + "Templates")
                      where b.Element(ns + "TemplateID").Value == "VISTA"
                      select b;

        // determine if the VISTA theme element already exists
        bool exists = (element != null && element.Count() > 0);

        if (type == ModificationType.Add) {
            if (!exists) {
                // create an XElement that defines our custom VISTA theme
                XElement xml =
                    new XElement(ns + "Templates",
                        new XElement(ns + "TemplateID", "VISTA"),
                        new XElement(ns + "DisplayName", "DevExpertise Vista Theme"),
                        new XElement(ns + "Description", "A Vista-like Theme"),
                        new XElement(ns + "Thumbnail", "images/DevExpertise.SharePoint.Themes/VISTA/thVISTA.gif"),
                        new XElement(ns + "Preview", "images/DevExpertise.SharePoint.Themes/VISTA/thVISTA.gif"));

                // add the element to the file and save
                doc.Element(ns + "SPThemes").Add(xml);
                doc.Save(spthemePath);
            }
        }
        else {
            if (exists) {
                // if the element exists, remove it and save
                element.Remove();
                doc.Save(spthemePath);
            }
        }

        stringReader.Close();
    }
}

Pretty slick, huh? Now, keep in mind that this only modifies the SPTHEMES.XML file – it does NOT set the theme for any site.  It will still be up to the user or site admins to set the theme for a given site.  Also, if this theme is already applied to a site and the feature is deactivated, it won’t reset the theme – it will only remove the entry from the theme settings page in Site Settings.  Finally, if a site has this theme installed and the solution package is uninstalled and/or removed, your site’s theme will be messed up because the source files are gone.  It is probably beneficial to at least loop through all the sites and reset the theme to something else if and when the feature is deactivated, but I’ll leave that to you. Enjoy!

Tags: , , , , ,
Posted in .NET, LINQ, SharePoint, SharePoint UI, XML | 8 Comments »