Thursday, May 23, 2013

Sending Messages Between the Background and the Content Script of a Chrome Extension

As a Chrome Extension will usually persist information longer than the duration that the content script is running on a page, such as for database persistence, and because the background script of an extension has greater access to the Chrome API than a content script, (primarily for security reasons), there exists the ability to communicate between the two using messages.

There are two types of message sending as explained in the Extensions Developer Guide – simple one-time requests and long-lived connections. This post will focus on simple one-time requests and sending a message from the content script to the background and sending a message back to the content script in response.

In this example, when the user presses Ctrl-Shift-Z a message will be sent from the content script to the background script. The background script receives the message, adds to the message and sends a message back to the content script.

Firstly, the manifest.json file for the extension specifies our background script and content script files to be used in the “content_scripts” and “background” sections respectively, as shown below:

 
 
{
  "name": "Sending Messages Test",
  "version": "1.0",  
  "description": "Send a Message to background.js from contentscript.js and send reply",
  
  "permissions": ["tabs"],
  
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["contentscript.js"]
    }
  ],
  
  "background": { "scripts": ["background.js"] },

  "manifest_version": 2
}
 


The content script is what is injected into the current web page and is where the process is initiated from. An event listener is added to the ‘keyup’ keyboard event and calls the function doKeyPress() when triggered which in turn sends the message. 

In order to send the message to the background script, part of the chrome.extension API is available within the content script. Using the function chrome.extension.sendRequest() our message is sent to the background script. Any object can be passed to this method that can be serialised into a JSON string and that does not contain circular references. 

In order to receive a message back from the background script a function of the chrome.runtime API is used. The function chrome.runtime.onMessage.addListener() allows us to specify a function to handle a message from the background script. In our case, it shows an alert with the response from the background. 

The contentscript.js file is shown below:

 
 
trigger_key = 90; //ASCII key code for the letter 'Z'
contentScriptMessage = "Skinner Said the teachers will crack any minute";

if (window == top) {
 window.addEventListener('keyup', doKeyPress, false); 
}

function doKeyPress(e){
 if (e.shiftKey && e.ctrlKey && e.keyCode == trigger_key){ 
  alert("Contentscript is sending a message to background script: '" + contentScriptMessage  + "'");
  chrome.extension.sendRequest({message: contentScriptMessage});
 }
}

chrome.runtime.onMessage.addListener(
 function(request, sender) {
  alert("Contentscript has received a message from from background script: '" + request.message + "'");
  });
 



Our background script has two functions. To listen for messages from the content script and to send a reply once a message is received. To listen for messages, the function chrome.extension.onRequest.addListener() is used which listens for messages from the content script and calls our function returnMessage to send a message back to the content script. 

In order to send a message back to the contentscript, the background script needs to determine the id of the tab to send the message back to and so uses the chrome.tabs API to determine the currently open tab using chrome.tabs.getSelected(null, function(tab) { … }) The inner function to be called on the selected tab then calls the function chrome.tabs.sendMessage() with the id of the open tab and our return object as arguments. This is then received by the message listener in our contentscript as explained earlier.


 
 
var backgroundScriptMessage = " purple monkey dishwasher";

chrome.extension.onRequest.addListener(function(request, sender) 
{
 alert("Background script has received a message from contentscript:'" + request.message + "'");
 returnMessage(request.message);
});

function returnMessage(messageToReturn)
{
 chrome.tabs.getSelected(null, function(tab) {
  var joinedMessage = messageToReturn + backgroundScriptMessage;  
  alert("Background script is sending a message to contentscript:'" + joinedMessage +"'");
  chrome.tabs.sendMessage(tab.id, {message: joinedMessage});
 });
}
 


The complete project which can be loaded as an unpacked extension into Chrome can be downloaded from here.

The sequence of alerts that will be seen when pressing Ctrl-Shift-Z are:







Sunday, November 4, 2012

What is the best way to count the number of occurrences of all words in a string, and which method is most efficient?

I was thinking the other day about what the best way to find out how many times a word appears in a string and what the most efficient way of doing this is and it amazed me that there are a variety of ways that this can be done. And so I thought I would test this to find out which way is best. In doing so, my intention was to determine a variety of ways to count the number of occurrences of all words in a string and from that to establish which method was the most efficient. Using C#, I have implemented four different ways of doing this and timed the results. Each method was done ten times and the average taken of the results.

Each method was tested over a variety of different input strings to determine which method was best for which circumstance. As a basis, each input string had 1036512 words. This was because the first text file used from http://norvig.com/big.txt was that number of words and this is a reasonable benchmark size that doesn't take too long to run.

Grouping

The grouping of items and a corresponding count has many uses and there are a variety of ways this can be implemented. This is similar in a sense to the GROUP BY statement in a SQL statement using a COUNT() function that would be implemented by the following SQL query:

Select word, count(word) from table group by word

This shows that there are two components required for a query. The word and the count. As a basis of each method a requirement was to return an array of objects that each had a word and a count. This lead to a method signature used for each grouping technique being defined such that it took a string as input and returned an array of objects that contained an int Count and a string Word.

Such that:
public class WordCount
{
    public string Word;
    public int Count;
}
And method signature:

WordCount [] RunGrouping(string input);

Which would run the method and time the duration of the grouping. Each method would split the string into a string array of words, the clock would start, the words grouped, the clock stopped and the results returned to the calling class.

The four procedures used consisted of:
  • A linear count of items using two nested foreach loops to count all words 
  • A sort of the words then a count 
  • A count using a Dictionary 
  • A count using a LINQ query
The string passed to the method to do the work had had all non-alpha characters removed and was in uppercase so that words were not incorrectly unique due to extra characters or case sensitivity.

Linear Count

The linear count of items used a List<WordCount> to hold the items and iterated through each word in the original string passed to it. Each word was then iterated through the List and if it was present in the list, the count for the corresponding word was increased. If the inner loop completes without finding the word, the word was added to the list with a count of 1. The list was then converted to an array and the method completed. Although not very linear, it was named this as there is one pass for each word in the original list. The code used is shown below:
public WordCount[] RunGrouping(string input)
{
        string[] words = input.Split(' ');
        List<WordCount> list = new List<WordCount>();
        bool found = false;
        WordCount[] counted;
        DateTime start = DateTime.Now;

        foreach (string word in words)
        {
            foreach (WordCount w in list)
            {
                if (w.Word == word)
                {
                    w.Count++;
                    found = true;
                    break;
                }
                else
                    found = false;
            }

            if (!found)
            {
                list.Add(new WordCount { Word = word, Count = 1 });
                found = true;
            }
        }

        counted = list.ToArray<WordCount>();
        DateTime end = DateTime.Now;
        Duration = end - start;
        return counted;
}

The efficiency of this query is evidently quite bad as there are two loops and the inner loop is increasing as more words get added to the list. The Big O notation for this was O(N^2)

Sort of words and then a count

The second procedure tried was a sort of all the words in an array and then a count of how many of each word appeared. The logic behind this method is slightly easier as there is only one foreach loop but a temp variable is used when a new item in the list is encountered. The code for this query was:


public TimeSpan Duration {get; set;}

public WordCount[] RunGrouping(string input)
{
        string[] words = input.Split(' ');
        List<WordCount> list = new List<WordCount>();
        WordCount[] counted;        
        int count = 0;
        DateTime start = DateTime.Now;

        Array.Sort(words);  
        string tempVar = words[0];
      
        foreach(string word in words)
        {
            if (word == tempVar)
            {
                count++;
            }
            else
            {
                list.Add(new WordCount { Word = tempVar, Count = count });
                tempVar = word;
                count = 1;
            }
        }

        list.Add(new WordCount{Word = tempVar, Count = count});

        counted = list.ToArray<WordCount>();
        DateTime end = DateTime.Now;
        Duration = end - start;
        return counted;
}

The efficiency of this query in Big O notation can be seen as O(1) as there is only one for loop instead of two and the iteration is linear. The sorting of the array at the start is a .NET function that is based on the Quicksort routine.

Dictionary Grouping

The Dictionary method uses a Dictionary object of Dictionary<string, int> and can be used as there will only ever be one instance of a word in the returned array, and so the dictionary Key can be the word and the Value the word count. The efficiency of this query is O(N) and is simpler to understand than the previous two methods. The code used is shown below.

public TimeSpan Duration {get; set;}

public WordCount[] RunGrouping(string input)
{
        string[] words = input.Split(' ');
        Dictionary<string, int> dict = new Dictionary<string, int>();            
        int i = 0;
        WordCount[] counted;
        DateTime start = DateTime.Now;

        foreach (string word in words)
        {
            if (!dict.ContainsKey(word))
                dict.Add(word, 1);
            else
                dict[word]++;
        }                       

        counted = new WordCount[dict.Count];           

        foreach (var pair in dict)
            counted[i++] = new WordCount { Word = pair.Key, Count = pair.Value };

        DateTime end = DateTime.Now;
        Duration = end - start;          
        return counted;           
}

The efficiency of this query could be considered O(N^2) due to the foreach loop and the fact the dict.ContainsKey() method has a call to a private system method int FindEntry(TKey key) that iterates over the collection to find a match.

LINQ Grouping

This method is arguably the easiest program flow to understand as the syntax is similar to a SQL statement GROUP BY but is the most difficult to understand what it actually does (and probably requires a separate post to discuss this). The code used is shown below:


public TimeSpan Duration {get; set;}

public WordCount [] RunGrouping(string input)
{                       
        string[] words = input.Split(' ');
        WordCount[] counted;
        DateTime start = DateTime.Now;
           
        counted = words.GroupBy(w => w).Select(o => new WordCount { Word = o.Key, Count = o.Count() }).ToArray<WordCount>();

        DateTime end = DateTime.Now;
        Duration = end - start;
        return counted;
}

The efficiency of this query is difficult to understand by looking at the code and so will not be given an O notation.

Results from the Testing:

As mentioned, each grouping method was run ten times over the original word list from http://norvig.com/big.txt to determine the most efficient grouping routine. The results are graphed below:



This shows that the linear count is dramatically less efficient than the other three counts and so was removed from the remaining comparisons. Although the linear count does show poor performance here, it did show better results when run against a list of 1 letter words (as shown below) but was still not included for future tests.


The results at this point appeared to be that the Linq grouping was the most efficient, followed by the Dictionary Count, the Sort and Count and lastly the Linear Count.

It was then decided to test the efficiency of the Linq and the Dictionary groupings exclusively for different scenarios to establish which was the better for different circumstances as these had the best efficiency over the most ranges so far. Firstly, random words of varying length were tested with combinations between 26^1 to 26^10. The number of combinations of words are shown below. Each text file used remained at the 1036512 words so that a comparison could be done to other results. It is important to note, however, that as the test input only had 1026512 words to begin with, only combinations up to 26^5 (11881376 words) can be considered relevant.

26^1 = 26 combinations
26^2 = 676
26^3 = 17576
26^4 = 456976
26^5 = 11881376
26^6 = 308915776
26^7 = 8031810176
26^8 = 208827064576
26^9= 5429503678976
26^10 = 141167095653376

As the number of combinations increased, the number of duplicates decreased and so it was estimated that the search time to determine whether the item existed already in the grouping routine would also increase. The results obtained are shown below:


From this it can be seen that for combinations up to about 3 letters, or 17576 different combinations of words, the Linq grouping and the Dictionary grouping are similar in efficiency. When the number of combinations increases beyond that, it would appear that the Dictionary grouping is more efficient than the Linq grouping.

A final test was done to determine the range and extent that this occurred for. Groups of similar words for four letter words were created in batches of size repeating from 1 to 100000 words and this was plotted for various values of interest. For example, a batch size of 1 repeating was one word repeating 1036512 times.  A batch size of 100 was 100 words repeating 10365.12 times (100 * 10365.12 = 1036512 words). The results are shown below:



This table is logarithmic and points out that when there are between 1 – 1000 repeated words the Linq query is more efficient. However, between 1000 – 20000, either method will give similar results; although it must be said that the Dictionary grouping in this range gives more consistent results with less variation in duration. After 20000 repeated words, the Dictionary count is evidently more efficient. This is further outlined in the graph below.

 Conclusion:


From the preceding observations, the following conclusions could be justified:
  • On average, both the Linq grouping and the Dictionary grouping are more efficient than the Linear Count and the Sort then Count approaches.

In comparison of the Linq and Dictionary approaches,
  • The Linq grouping is better for words where there is less than 1000 different four letter words
  • The Dictionary grouping and Linq grouping give similar results where there is between 1000 and 20000 different four letter words
  • The Dictionary grouping is better when there are more than 20000 different four letter words
  • The Dictionary grouping has less variation in the execution time overall.

The results are useful to take into account if grouping larger sets (>20000) of items such as primary keys or GUIDs to use the Dictionary approach. As well, when doing a lot of groupings of small sets (< 1000) the Linq approach works best.

A future post may investigate words of more or less than four letters as well as the profiling of the Dictionary and Linq Methods to determine where the performance hits are in each at different counts of words repeating.

Thursday, October 25, 2012

How to pause Windows Media Player or Spotify when locking Windows with AutoHotkey

I'm beginning to use AutoHotkey to automate mundane mouse clicks with keyboard shortcuts and thought I would share how to pause either Windows Media Player (WMP) or Spotify when locking Windows with a couple of keystrokes from any application instead of having to switch context to the player and select pause manually. The following example can be added to your .AHK script to give action to the Windows-S keystroke and the Pause key.

When pressing Windows-S, this will send the pause key (Ctrl-P for WMP and Space for Spotify) to either WMP or Spotify if they are running. When using this, only have either WMP OR Spotify running but not both otherwise one will pause and the other will unpause when you lock the PC. The script can be split to map to two different keys (one for each of WMP and Spotify) but I like the convenience of only having to have one shortcut for both and I'm not usually running both programs at the same time. If either program is already running but paused when deciding to lock the PC, just use the regular Windows-L to lock instead otherwise the player will start playing.

The script also overrides the Pause key so you can pause either WMP or Spotify from any program without having to switch context.


#s::
{
 DetectHiddenWindows, On
 ControlSend, ahk_parent, {Space}, ahk_class SpotifyMainWindow
 ControlSend, ahk_parent, ^{p}, ahk_class WMPlayerApp
 DetectHiddenWindows, Off
 Run, % "rundll32.exe user32.dll,LockWorkStation"ss
 return
}

Pause::
{
 DetectHiddenWindows, On
 ControlSend, ahk_parent, {Space}, ahk_class SpotifyMainWindow
 ControlSend, ahk_parent, ^{p}, ahk_class WMPlayerApp
 DetectHiddenWindows, Off
 return
}

Tuesday, July 19, 2011

Cannot complete the install because one or more required items could not be found.Software being installed: Google Plugin for Eclipse 3.7 2.3.2.r37v201106211634

I was attempting to install the Google Plugin for Eclipse and the SDKs for Google App Engine and Google Web Toolkit today when I came across the emblazoned error mentioned in the title of this blog.

In Eclipse, I am using Helios (version 3.6) on my main PC. I forgot this, and thought I had Eclipse Indigo installed (version 3.7), which I do on another PC. In doing so, and attempting to install new software from 'Help -> Install New Software...', for the site to work with, I inadvertently selected:

 http://dl.google.com/eclipse/plugin/3.7 

which gave the error:

Cannot complete the install because one or more required items could not be found.Software being installed: Google Plugin for Eclipse 3.7 2.3.2.r37v201106211634

This was simply resolved by going back and changing the site to:

http://dl.google.com/eclipse/plugin/3.6

Then selecting the required components and clicking Next.

Problem solved. Short post, but it hopefully may help someone out there who encounters this.

Thursday, July 7, 2011

Adding an Arrow Image to the Right of a ListView

The following shows how to create a ListView with an arrow image to the right of the text for a simple application in Android. It also shows how to create a class to handle adapting the text and images to the ListView in a reusable way.

The motivation behind the application is to highlight how an array of text strings and an array of boolean values can be passed to an adapter that binds this information to a ListView and to show the strings in the array as list items, as well as showing how a right-arrow on the right side of the list based on the values in the boolean array can be produced.


Creating the Layout

The ListActivity class is used instead of the Activity class so that the extended methods of the ListActivity class can be accessed, in particular the setListAdpater() method that makes the task of setting the adapter for the ListView in our layout easier to perform.

In the main.xml, the layout consists of a RelativeLayout that surrounds a ListView, a TextView, and and an ImageView.

As the ListActivity is being used in our example, the ListView is required in the layout with an id of ‘list’ to prevent a NullPointerException when setContentView() is called.

The TextView is the element that will display the text from our string array for each element. To make this align to the left of the RelativeLayout, the property android:layout_alignParentLeft="true" is set.

The ImageView is the element that will contain the right-arrow image that we want to set. To make this align to the right of the RelativeLayout, the property android:layout_alignParentRight="true" is set.

The main.xml appears below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/layercontainer"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:background="#ffffff">
   <ListView 
   android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
   <TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true" 
    android:padding="10dp"
    android:textSize="16sp"
    android:textColor="#000000"    
    android:typeface="sans"/>
   <ImageView
    android:id="@+id/image1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"/>
</RelativeLayout>


Creating the Adapter

The ImageAdapter class is a standalone class (as opposed to a nested class in the ListActivity) that binds the text and boolean arrow information to the ListView at runtime. It extends the ArrayAdapter class and implements the getView() method to do the binding. The getView() method iterates for the number of items that are passed to the base class by the items variable through the call to super(). As ImageAdapter is not nested in the ListActivity, all required variables are passed through the class' constructor. This includes the arrays, the activity context and the id’s of the TextView and ImageView that are to be bound to. This also allows the class to be reusable for multiple ListViews.

Within the getView() method,  the currently selected row is inflated from the layout through the inflate() method, which returns a View to the current row that is to be manipulated.

The call to setText() assigns the string array for the row position to the current row’s TextView.
Based on the current row and the corresponding boolean array, if the array element is true, the ImageView for the row is retrieved with findViewById() and the arrow image is assigned to it with the setImageResource() method. The arrow image is stored in the ‘\res\drawable’ location of the project as an image called arrow.jpg and is called as R.drawable.arrow.

The code for the ImageAdapter class is shown below:

package com.ListViewApp;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ImageAdapter extends ArrayAdapter 
{ 
    Activity context;
    String[] items;
    boolean[] arrows;
    int layoutId;
    int textId;
    int imageId;

    ImageAdapter(Activity context, int layoutId, int textId, int imageId, String[] items, boolean[] arrows) 
    { 
        super(context, layoutId, items); 

        this.context = context; 
        this.items = items;
        this.arrows = arrows;
        this.layoutId = layoutId;
        this.textId = textId;
        this.imageId = imageId;
    } 

    public View getView(int pos, View convertView, ViewGroup parent) 
    { 
        LayoutInflater inflater=context.getLayoutInflater(); 
        View row=inflater.inflate(layoutId, null); 
        TextView label=(TextView)row.findViewById(textId); 

        label.setText(items[pos]); 
        
        if (arrows[pos]) 
        { 
         ImageView icon=(ImageView)row.findViewById(imageId);  
            icon.setImageResource(R.drawable.arrow); 
        }    

        return(row); 
    } 
} 

The Main ListActivity

The main call to the application is through the ListActivity class that basically sets the content of the View for the current Activity and sets the custom ImageAdapter for the list in the current Activity. The code for this is shown below:

package com.ListViewApp;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;

public class ListViewActivity extends ListActivity 
{
 String[] listItems={"alpha", "beta", "gamma", "delta", "epsilon"}; 
 boolean[] listImages={true, false, true, false, true};
 
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setListAdapter(new ImageAdapter(this, R.layout.main, R.id.text1, R.id.image1, listItems, listImages ));
        
    }
}


The complete project can be downloaded from here.

Wednesday, December 15, 2010

Using LINQ with generics and lambda expressions to add wildcard searches to a query

Adding generic search functionality as a helper class to a project has the advantage of giving greater flexibility in querying results when using linq. Using a method that returns a type of Expression<Func<T, bool>> allows the method to be used as a predicate in linq .where() clauses as per the following:

var resultSet = from p in db.Products.Where(
GenericSearch.GetWildCardCriteria<Products>("ball*","productName"))
 select p;

Given this query, the Generic type passed through is the class of the linq table that is to be queried. "ball*" is the search criteria, which would return all results starting with 'ball', using "ball*10" would give all results starting with 'ball' and ending with '10'. Alternatively, "*ball" would give all results ending with 'ball'.

Due to linq functions being relatively limited in their ability to query the database, and being much more limited that a SQL statement, the second GetWildCardCriteria<T>() method attempts to interpret a search string in terms of wildcard searches using the linq functions available, specifically, the .StartsWith(), .EndsWith() and .Contains() methods. These methods have been called through the building of the functions using the BuildExpressionFromMethod<T>() method, which is used as the search is generic, and so needs to be built dynamically so the correct type <T> and property name are used.

The BuildExpressionFromMethod<T>() can build the given .Contains(), .EndsWith(), etc. expression from the strings sent to it, and return a lambda expression to the predicate as all the functions have the same signature x.Method("comparisonText")

A direct comparison is done if there are no wildcards, and so a lambda expression for x.Field == "ball" is generated using the BuildEqualsExpression<T>() method.

Note: The PredicateBuilder extension class is also required to run this code and can be found at: http://www.albahari.com/nutshell/predicatebuilder.aspx

The code for the search is below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;

namespace LINQ.Helpers
{
 
    public class GenericSearch
    { 
        // use this if no predicate is added to and directly using .Where()
        public static Expression<Func<T, bool>> GetWildCardCriteria<T>(string searchString, string propertyName)
        {
            return GetWildCardCriteria<T>(True<T>(), searchString, propertyName);
        }
                
        // use this method when predcate already exists - type is inferred from expression
        public static Expression<Func<T, bool>> GetWildCardCriteria<T>(Expression<Func<T, bool>> predicate, string searchString, string propertyName)
        {
            string[] parts = searchString.Split('*');
            if (parts.Length == 1)
            {
                predicate = predicate.And(BuildEqualsExpression<T>(propertyName, searchString));
            }
            else
            {
                //Check for predicate wild card
                if (parts[0] == "")
                {
                    if (parts.Length == 2)
                    {
                        //If on only 2 parts the end with
                        predicate = predicate.And(BuildExpressionFromMethod<T>(propertyName, "StartsWith", parts[1]));
                    }
                    else
                    {
                        //Else do a contains
                        predicate = predicate.And(BuildExpressionFromMethod<T>(propertyName, "Contains", parts[1]));
                    }
                }
                else if (parts.Length == 2 && parts[1] == "")
                {
                    //handle suffix wild card
                    predicate = predicate.And(BuildExpressionFromMethod<T>(propertyName, "StartsWith", parts[0]));
                }
                else if (parts.Length == 2 && !string.IsNullOrEmpty(parts[1]))
                {
                    //handle mid string wild card
                    predicate = predicate.And(BuildExpressionFromMethod<T>(propertyName, "StartsWith", parts[0]));
                    predicate = predicate.And(BuildExpressionFromMethod<T>(propertyName, "EndsWith", parts[1]));
                }
                //handle internal wild cards
                for (int i = 2; i < parts.Length - 1; i++)
                {
                    predicate = predicate.And(BuildExpressionFromMethod<T>(propertyName, "Contains", parts[i]));
                }
                //Check for a suffix in the more than 2 parts case
                if (parts.Length > 2 && !string.IsNullOrEmpty(parts[parts.Length - 1]))
                {
                    predicate = predicate.And(BuildExpressionFromMethod<T>(propertyName, "StartsWith", parts[parts.Length - 1]));
                }
            }
            return predicate;
        }

        // propName is name of the property, ie. if T is the linq table Product, then propName could be the field "Product_Name"
        // value is the value that propName is equal to, eg. the product 'ball' would be equivalent to x => x.Product_Name == "ball"

        private static Expression<Func<T, bool>> BuildEqualsExpression<T>(string propName, string value)
        {
            try
            {
                ParameterExpression param = Expression.Parameter(typeof(T), "x");
                MemberExpression prop = Expression.Property(param, propName);
                BinaryExpression equals = Expression.Equal(prop, Expression.Constant(value));
                Expression<Func<T, bool>> expr = Expression.Lambda<Func<T, bool>>(equals, param);

                return expr;
            }
            catch (Exception)
            {
                return x => true;
            }
        }

        // propName is same as above
        // method is the method to call on the property, eg. if method = "Contains" and prop_Name = "Product_Name",
        // and comparisonText = "ball"
        // this would be equivalent to x => x.Product_Name.Contains("ball")

        private static Expression<Func<T, bool>> BuildExpressionFromMethod<T>(string propName, string method, string comparisonText)
        {
            try
            {
                MethodInfo mi = typeof(String).GetMethod(method, new Type[] { typeof(String) });
                ParameterExpression param = Expression.Parameter(typeof(T), "x");
                MemberExpression field = Expression.PropertyOrField(param, propName);
                MethodCallExpression mce = Expression.Call(field, mi, Expression.Constant(comparisonText));
                Expression<Func<T, bool>> expr = Expression.Lambda<Func<T, bool>>(mce, param);

                return expr;
            }
            catch (Exception)
            {
                return x => true;
            }
        }

        private static Expression<Func<T, bool>> True<T>() { return f => true; }
    }
}

Friday, October 15, 2010

Removing carriage returns from a text file using a DOS batch file



Hello there. Well this is really a test post more than anything else to get me aquainted with the SyntaxHighlighter set of files for code publishing on a blog available at alexgorbatchev.com. But in doing so I thought I would give an example of how to remove CR/LF characters from a text file using only batch commands.

The only trick to this is to note that when doing string manipulations in DOS, the enabledelayedepansion option needs to be set, and the variables then need to be accessed as !VAR! instead of %VAR% when being reused in a FOR loop.

@echo off 
setlocal enabledelayedexpansion

for /f %%j in (%1) do (
  set linea=%%j 
  set line=!line!!linea!
 )
echo !line! > %1