regular expression asp.net - asp.net

I trying to improve a textbox that filters a gridview, by implementing an enhanced textbox that can identify AND, OR, NOT operators by searching for this keywords in the string the user inputs in the textbox.
I am trying to do a regular expression to group the results but I'm not very good at this and I am failing to get what I want.
An example of what I want is as follows:
string = "build1 and build2 and build3 or build4 or not build5 and not build6"
results in a split mode:
build1 and
build2 and
build3 or
build4 or not
build5 and not
build6
This is because then I will take the first for example and replace with
SomeTable.Name_Of_Build = 'build1' AND
SomeTable.Name_Of_Build = 'build2' AND .... so on

This works for me
\w+(\sand\snot|\sor\snot|\sand|\sor|$)

I might recommend that instead of using a regular expression to group the results you do something like this. I think it would be more robust than trying to guess at the right regex.
string filter = "build1 and buil2 and build3 or build4 or not build5"
list<string> filterTokens = filter.Split(new char[] {' '})
string gridViewFilter = "";
bool notEqual = false;
foreach(string token in filterTokens)
{
if(token == "and")
{
gridViewFilter += "and"
}
else if(token == "or")
{
gridViewFilter += "or"
}
else if(token == "not")
{
notEqual = true;
}
else if(notEqual)
{
gridViewFilter += "SomeTable.Name_Of_Build <> '" + token + "'";
notEqual = false;
}
else
{
gridViewFilter += "SomeTable.Name_Of_Build <> '" + token + "'";
}
}
Also, if you really want to implement a robust and full featured sort you need to look into using Reverse Polish Notation (RPN). It would allow you to handle parentheses and order of operations. An RPN implementation would look something like this.
private bool CheckForFilterMatch(string filter, List<string> values, bool exactMatch)
{
for (int i = 0; i < values.Count; i++)
{
values[i] = values[i].ToLower();
}
if (filter.Trim() == "")
{
return true;
}
List<string> rpn = GetPostFixNotation(filter);
Stack<bool> output = new Stack<bool>();
foreach (string token in rpn)
{
if (IsValue(token))
{
bool isMatch;
if (exactMatch)
{
isMatch = values.Contains(token.ToLower());
}
else
{
isMatch = false;
foreach (string value in values)
{
isMatch = (value.IndexOf(token.ToLower()) != -1);
if (isMatch) break;
}
}
output.Push(isMatch);
}
else if (IsOperator(token))
{
bool operand1 = output.Pop();
bool operand2 = output.Pop();
if (token == "&")
{
output.Push(operand1 && operand2);
}
if (token == "|")
{
output.Push(operand1 || operand2);
}
}
}
return output.Pop();
}
public List<string> GetPostFixNotation(string filter)
{
if (filter == "")
{
return new List<string>();
}
List<string> postFixNotation = new List<string>();
Queue<string> output = new Queue<string>();
Stack<string> operators = new Stack<string>();
List<string> parsedFilter = ParseFilterTokens(filter);
foreach (string token in parsedFilter)
{
if (IsValue(token))
{
output.Enqueue(token);
}
else if (IsOperatorNoParenth(token))
{
while (operators.Count > 0 && IsOperatorNoParenth(operators.Peek()))
{
if ((operators.Count > 0 && (Precedence(token) <= Precedence(operators.Peek()))))
{
string operatorToReturn = operators.Pop();
output.Enqueue(operatorToReturn);
}
else break;
}
operators.Push(token);
}
else if (token == "(")
{
operators.Push(token);
}
else if (token == ")")
{
while (operators.Count > 0 && operators.Peek() != "(")
{
output.Enqueue(operators.Pop());
}
operators.Pop();
}
}
while (operators.Count > 0)
{
output.Enqueue(operators.Pop());
}
while (output.Count > 0)
{
postFixNotation.Add(output.Dequeue());
}
return postFixNotation;
}

Try this regex out:
(build[^b]+)

Related

Write custom plugins/extensions like kendoui and telerik for asp.net mvc razor

Telerik and kendoUI offers a number of html controls like grids, charts etc. to enhance the ui in asp.net mvc. More interesting thing is they are used as html extensions and hence we can bind some model to the controls which also makes it somewhat strongly typed. It also uses javascript libs to handle client side interactions. I need to get some gist over how can we write custom plugins like kendo and telerik like building my own grid component. What is the proper pattern that i should follow?
This is not good example but i think it is good start.
This method generates dataTable
public static string GenerateTableHtml<TValue>(IEnumerable<TValue> model, string DeleteUrl, string EditUrl)
{
StringBuilder Table = new StringBuilder();
Table.AppendLine("<script type='text/javascript'> $(document).ready(function () {"
+ "$('.btnDelete').click(function () {"
+ "var url = $(this).attr('dropzone');"
+ "$('#dialog-form').attr('action', url);})"
+ "})</script>");
Table.AppendLine(" <div class=\"dataTables_wrapper\"><div class=\"\">");
string TableButtonsTemplate = "<td><div class=\"table_buttons\">"
+ "<img src=\"../Images/icons/dark/pencil.png\")\" title=\"რედაქტირება\" />"
+ "<a href=\"#\" id=\"opener\" class=\"btnDelete\" dropzone=\"{1}\">"
+"<img class=\"\" src=\"../Images/icons/dark/close.png\")\" title=\"წაშლა\" /></a>"
+ "</div></td>";
string TableButtons = String.Empty;
bool HaveActionButtons = false;
string rowID = string.Empty;
if (String.IsNullOrEmpty(DeleteUrl) == false || string.IsNullOrEmpty(EditUrl) == false)
{
HaveActionButtons = true;
}
Table.AppendLine("<table class=\"display dTable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">");
Table.AppendLine("<thead>");
Table.AppendLine("<tr>");
int ColumnIndex = 0;
int rowIndexer = 0;
var fType = model.GetType().FullName;
var startIndex = fType.IndexOf("[[") + 2;
var type = fType.Substring(startIndex, fType.Length - startIndex - 2);
foreach (var item in model)
{
if (ColumnIndex == 0)
{
var properties = item.GetType().GetProperties();
foreach (var prop in properties)
{
var metaData = ModelMetadataProviders.Current.GetMetadataForProperty(null,
Type.GetType(type), prop.Name);
if (metaData.DisplayName != null)
{
Table.AppendLine("<th class=\"ui-state-default\" rowspan=\"1\" colspan=\"1\">" + metaData.DisplayName + "</th>");
}
else
{
Table.AppendLine("<th class=\"ui-state-default\" rowspan=\"1\" colspan=\"1\">" + prop.Name + "</th>");
}
}
Table.AppendLine("<th></th>");
Table.AppendLine("</tr>");
Table.AppendLine("</thead>");
Table.AppendLine("<tbody>");
}
foreach (var value in item.GetType().GetProperties().Select(x => x.GetValue(item, null)))
{
int rowCount = item.GetType().GetProperties().Select(x => x.GetValue(item, null)).Count();
rowIndexer++;
if (rowIndexer != rowCount)
{
if (rowIndexer == 1)
{
Table.AppendLine("<tr class=\"gradeA odd\">");
}
if (value != null)
{
string val = value.ToString();
Table.AppendLine("<td>" + val + "</td>");
rowID = item.GetType().GetProperty("ID").GetValue(item, null).ToString();
}
else
{
Table.AppendLine("<td></td>");
}
}
else
{
if (value != null)
{
Table.AppendLine("<td>" + value.ToString() + "</td>");
}
else
{
Table.AppendLine("<td></td>");
}
if (HaveActionButtons == true)
{
Table.AppendLine(String.Format(TableButtonsTemplate, EditUrl + rowID, DeleteUrl + rowID));
}
Table.AppendLine("</tr>");
if (rowIndexer != item.GetType().GetProperties().Count())
{
Table.AppendLine("<tr class=\"gradeA odd\">");
}
}
}
rowIndexer = 0;
ColumnIndex++;
}
Table.AppendLine("</tbody></table></div></div>");
Table.AppendLine(String.Format(Resources.MainResources.ModalDialogConfirm, "Confirmation",
"<strong>Warning!</strong><br /> Are you sure you want to delete user?", ""));
return Table.ToString();
}

ASP.NET - What Characters does Server.HtmlEncode Encode into Named Character Entities

What characters does Server.HtmlEncode encode into named character entities?
So far I have only found < > & and " surely there must be more than this?
This is the code of HtmlEncode, so here you can see how they done it.
public static unsafe void HtmlEncode(string value, TextWriter output)
{
if (value != null)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
int num = IndexOfHtmlEncodingChars(value, 0);
if (num == -1)
{
output.Write(value);
}
else
{
int num2 = value.Length - num;
fixed (char* str = ((char*) value))
{
char* chPtr = str;
char* chPtr2 = chPtr;
while (num-- > 0)
{
chPtr2++;
output.Write(chPtr2[0]);
}
while (num2-- > 0)
{
chPtr2++;
char ch = chPtr2[0];
if (ch <= '>')
{
switch (ch)
{
case '&':
{
output.Write("&");
continue;
}
case '\'':
{
output.Write("'");
continue;
}
case '"':
{
output.Write(""");
continue;
}
case '<':
{
output.Write("<");
continue;
}
case '>':
{
output.Write(">");
continue;
}
}
output.Write(ch);
continue;
}
if ((ch >= '\x00a0') && (ch < 'Ā'))
{
output.Write("&#");
output.Write(ch.ToString(NumberFormatInfo.InvariantInfo));
output.Write(';');
}
else
{
output.Write(ch);
}
}
}
}
}
}
.NET 4 and 4.5 encode single quotes also, which doesn't appear to be in the answer

AjaxControlToolkit is undefined - Error when bringing an extender up to date

I am looking for some way to warn the user if a form is 'dirty' and they try and navigate away from it.
This project seemed to do exactly what I needed.
However, it was written back in 2007, and when I tried to use it "as-is" in my .NET 4.0 app with the latest version of the Ajax Control Toolkit it didn't work.
So, I downloaded the source (available from the CodeProject article) and tried to bring it up-to-date. But this is the first time I've attempted such a task and I'm a bit lost.
The error I'm now getting is as follows:
Microsoft JScript runtime error: 'AjaxControlToolkit' is undefined
The line in the DirtyPanelExtenderBehaviour.js which gives the error is:
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', AjaxControlToolkit.BehaviorBase);
Here's what I've done so far:
1. Downloaded the source from the Codeproject article
2. Opened in Visual Studio 2010 and completed the upgrade wizard
3. Deleted references to AjaxControlToolkit.dll and replaced with a new reference to the latest version of the toolkit
4. Amended references to ScriptManager with ToolkitScriptManager (Not sure if this was needed)
5. Amended the sample website to use a ToolkitScriptManager on the page in place of a ScriptManager
Sooo, any ideas what I've done wrong? Or what I'm missing? So that I can recompile the DirtyPanelExtender.dll and use it in my .NET 4.0 project?
The full code is below that I am using. The original author wrote this with exception of my amendments as detailed above - I'm not taking credit!
DirtyPanelExtender.cs:
using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Text;
using AjaxControlToolkit;
[assembly: System.Web.UI.WebResource("DirtyPanelExtender.DirtyPanelExtenderBehavior.js", "text/javascript")]
namespace DirtyPanelExtender
{
[Designer(typeof(DirtyPanelExtenderDesigner))]
[ClientScriptResource("DirtyPanelExtender.DirtyPanelExtenderBehavior", "DirtyPanelExtender.DirtyPanelExtenderBehavior.js")]
[TargetControlType(typeof(Panel))]
[TargetControlType(typeof(UpdatePanel))]
public class DirtyPanelExtender : ExtenderControlBase
{
[ExtenderControlProperty]
[DefaultValue("Data has not been saved.")]
public string OnLeaveMessage
{
get
{
return GetPropertyValue("OnLeaveMessage", "");
}
set
{
SetPropertyValue("OnLeaveMessage", value);
}
}
protected override void OnPreRender(EventArgs e)
{
string values_id = string.Format("{0}_Values", TargetControl.ClientID);
string values = (Page.IsPostBack ? Page.Request.Form[values_id] : String.Join(",", GetValuesArray()));
ToolkitScriptManager.RegisterHiddenField(this, values_id, values);
base.OnPreRender(e);
}
private string[] GetValuesArray()
{
return GetValuesArray(TargetControl.Controls);
}
private string[] GetValuesArray(ControlCollection coll)
{
List<string> values = new List<string>();
foreach (Control control in coll)
{
if (control is RadioButtonList)
{
for (int i = 0; i < ((RadioButtonList)control).Items.Count; i++)
{
values.Add(string.Format("{0}_{1}:{2}", control.ClientID, i, ((RadioButtonList)control).Items[i].Selected.ToString().ToLower()));
}
}
else if (control is ListControl)
{
StringBuilder data = new StringBuilder();
StringBuilder selection = new StringBuilder();
foreach (ListItem item in ((ListControl) control).Items)
{
data.AppendLine(item.Text);
selection.AppendLine(item.Selected.ToString().ToLower());
}
values.Add(string.Format("{0}:data:{1}", control.ClientID, Uri.EscapeDataString(data.ToString())));
values.Add(string.Format("{0}:selection:{1}", control.ClientID, Uri.EscapeDataString(selection.ToString())));
}
else if (control is IEditableTextControl)
{
values.Add(string.Format("{0}:{1}", control.ClientID, Uri.EscapeDataString(((IEditableTextControl)control).Text)));
}
else if (control is ICheckBoxControl)
{
values.Add(string.Format("{0}:{1}", control.ClientID, ((ICheckBoxControl)control).Checked.ToString().ToLower()));
}
values.AddRange(GetValuesArray(control.Controls));
}
return values.ToArray();
}
public void ResetDirtyFlag()
{
ToolkitScriptManager.RegisterClientScriptBlock(TargetControl, TargetControl.GetType(),
string.Format("{0}_Values_Update", TargetControl.ClientID), string.Format("document.getElementById('{0}').value = '{1}';",
string.Format("{0}_Values", TargetControl.ClientID), String.Join(",", GetValuesArray())), true);
}
}
}
DirtyPanelExtenderBehaviour.js:
Type.registerNamespace('DirtyPanelExtender');
DirtyPanelExtender.DirtyPanelExtenderBehavior = function(element) {
DirtyPanelExtender.DirtyPanelExtenderBehavior.initializeBase(this, [element]);
this._OnLeaveMessageValue = null;
}
DirtyPanelExtender.DirtyPanelExtenderBehavior.prototype = {
isDirty : function() {
var values_control = document.getElementById(this.get_element().id + "_Values");
var values = values_control["value"].split(",");
for (i in values) {
var namevalue = values[i];
var namevaluepair = namevalue.split(":");
var name = namevaluepair[0];
var value = (namevaluepair.length > 1 ? namevaluepair[1] : "");
var control = document.getElementById(name);
if (control == null) continue;
// alert(control.id + " -> " + control.type);
if (control.type == 'checkbox' || control.type == 'radio') {
var boolvalue = (value == "true" ? true : false);
if(control.checked != boolvalue) {
// alert("checkbox changed: " + control.checked + " vs. " + boolvalue);
return true;
}
} else if (control.type == 'select-one' || control.type == 'select-multiple') {
if (namevaluepair.length > 2) {
if ( control.options.length > 0) {
// control is listbox
// there's data:value and selection:value
var code = value;
value = (namevaluepair.length > 2 ? namevaluepair[2] : "");
var optionValues = "";
// concat all listbox items
for( var cnt = 0; cnt < control.options.length; cnt++) {
if (code == 'data') {
optionValues += control.options[cnt].text;
} else if (code == 'selection') {
optionValues += control.options[cnt].selected;
}
optionValues += "\r\n";
}
if( encodeURIComponent(optionValues) != value ) {
// items in the listbox have changed
// alert("listbox " + code + " changed: " + encodeURIComponent(optionValues) + " vs. " + value);
return true;
}
}
} else if(control.selectedIndex != value) {
// alert("dropdown selection changed: " + control.selectedIndex + " vs. " + value);
return true;
}
} else {
if(encodeURIComponent(control.value) != value) {
// alert("control " + control.type + " changed: " + control.value + " vs. " + value);
return true;
}
}
}
return false;
},
initialize : function() {
DirtyPanelExtender.DirtyPanelExtenderBehavior.callBaseMethod(this, 'initialize');
DirtyPanelExtender_dirtypanels[DirtyPanelExtender_dirtypanels.length] = this;
},
dispose : function() {
DirtyPanelExtender.DirtyPanelExtenderBehavior.callBaseMethod(this, 'dispose');
},
get_OnLeaveMessage : function() {
return this._OnLeaveMessageValue;
},
set_OnLeaveMessage : function(value) {
this._OnLeaveMessageValue = value;
}
}
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', AjaxControlToolkit.BehaviorBase);
var DirtyPanelExtender_dirtypanels = new Array()
function DirtyPanelExtender_SuppressDirtyCheck()
{
window.onbeforeunload = null;
}
function __newDoPostBack(eventTarget, eventArgument)
{
// supress prompting on postback
DirtyPanelExtender_SuppressDirtyCheck();
return __savedDoPostBack (eventTarget, eventArgument);
}
var __savedDoPostBack = __doPostBack;
__doPostBack = __newDoPostBack;
window.onbeforeunload = function (eventargs)
{
for (i in DirtyPanelExtender_dirtypanels)
{
var panel = DirtyPanelExtender_dirtypanels[i];
if (panel.isDirty())
{
if(! eventargs) eventargs = window.event;
eventargs.returnValue = panel.get_OnLeaveMessage();
break;
}
}
}
The BehaviorBase class now resides in a different namespace. You need to replace the line...
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', AjaxControlToolkit.BehaviorBase);
with...
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', Sys.Extended.UI.BehaviorBase);

Filtering LINQ query

I have problem that is bothering me last couple of days.
I need to filter LINQ query using comboboxes and textboxes. The problem is I can't manage to get the result and I always get the empty gridview (used for showing filtered data).
Can anyone help me why am I getting no results at all? I've checked the debugger and the data sent to query is valid, although, I'm not sure about "string.Empty" value.
Here is the code:
string naziv, nazivEn, adresa, tel, fax, mob, email, web, oib, tip, mjesto;
if (chkMjesto.Checked == true)
{
mjesto = cbMjesto.SelectedItem.Text;
}
else
{
mjesto = string.Empty;
}
if (chkTip.Checked == true)
{
tip = cbTip.SelectedItem.Text;
}
else
{
tip = string.Empty;
}
string tema;
if (chkTema.Checked == true)
{
tema = cbTema.SelectedItem.Text;
}
else
{
tema = string.Empty;
}
if (chkAdresa.Checked == true)
{
adresa = txtAdresa.Text;
}
else
{
adresa = string.Empty;
}
if (chkTelefon.Checked == true)
{
tel = txtTelefon.Text;
}
else
{
tel = string.Empty;
}
if (chkMobitel.Checked == true)
{
mob = txtMobitel.Text;
}
else
{
mob = string.Empty;
}
if (chkEmail.Checked == true)
{
email = txtEmail.Text;
}
else
{
email = string.Empty;
}
if (chkWeb.Checked == true)
{
web = txtWeb.Text;
}
else
{
web = string.Empty;
}
if (chkOIB.Checked == true)
{
oib = txtOIB.Text;
}
else
{
oib = string.Empty;
}
if (chkNaziv.Checked == true)
{
naziv = txtNaziv.Text;
}
else
{
naziv = string.Empty;
}
if (chkNazivEn.Checked == true)
{
nazivEn = txtNazivEn.Text;
}
else
{
nazivEn = string.Empty;
}
if (chkFax.Checked == true)
{
fax = txtFax.Text;
}
else
{
fax = string.Empty;
}
if (rblOrganizator.SelectedItem.Value == "Nije")
{
var pretraga = from t in db.tijeloes
where t.tijelo_naziv.Contains(naziv) && t.tijelo_adresa.Contains(adresa) && t.tip_tijela.tip_tijela_naziv.Contains(tip) && t.mjesto.mjesto_naziv.Contains(mjesto)
where t.tijelo_telefon.Contains(tel) && t.tijelo_fax.Contains(fax) && t.tijelo_email.Contains(email) && t.tijelo_mob.Contains(mob) && t.tijelo_web.Contains(web) && t.tijelo_oib.Contains(oib) && t.tijelo_naziv_en.Contains(nazivEn)
select new { t.tijelo_naziv, t.tijelo_oib,t.tip_tijela.tip_tijela_naziv,t.tijelo_adresa,t.mjesto.mjesto_naziv, t.mjesto.zupanija_drzava.zupanija_naziv};
gvTijelo.DataSource = pretraga;
gvTijelo.DataBind();
if (pretraga.Count() != 0)
{
gvTijelo.HeaderRow.Cells[0].Text = "Naziv";
gvTijelo.HeaderRow.Cells[1].Text = "OIB";
gvTijelo.HeaderRow.Cells[2].Text = "Tip tijela";
gvTijelo.HeaderRow.Cells[3].Text = "Adresa";
gvTijelo.HeaderRow.Cells[4].Text = "Mjesto";
gvTijelo.HeaderRow.Cells[5].Text = "Regionalni centar";
}
}
The string.Empty seems to the culprit. I would bet the SQL being generated is checking if a field contains '', which just won't likely work with data in that field.
Your best bet is to start the query before your conditionals, then append a where to it if the corresponding check box is checked.
var pretraga = db.tijeloes;
if (chkMjesto.Checked == true)
{
pretraga = pretraga.Where(t => t.tijelo_naziv.Contains(cbMjesto.SelectedItem.Text));
}
if (chkTip.Checked == true)
{
pretraga = pretraga.Where(t => t.tip_tijela.tip_tijela_naziv.Contains(cbTip.SelectedItem.Text));
}
...
pretraga = pretraga.Select(t => new { t.tijelo_naziv, t.tijelo_oib,t.tip_tijela.tip_tijela_naziv,t.tijelo_adresa,t.mjesto.mjesto_naziv, t.mjesto.zupanija_drzava.zupanija_naziv });
// Bind to pretraga.
...
If I were you I would declare all the variables at the top seperately like
string naziv = string.empty;
string whatever = string.empty; etc
Doing this will make your code smaller because you can get rid of the else statements as the variables are already set.
Sorry not a solution but might thin down the code for you a little :)

Use MatchPattern property of FindMatchingFiles workflow activity

I'm customizing the default workflow of build process template using TFS 2010 Team Build. There is an activity named FindMatchingFiles allows to search for specific files with a pattern defined in MatchPattern property. It works if I only specify one file extension. Example:
String.Format("{0}\\**\\\*.msi", SourcesDirectory)
But I would like to include *.exe as well. Trying following pattern but it doesn't work:
String.Format("{0}\\**\\\*.(msi|exe)", SourcesDirectory)
Anyone could show me how to correct it?
You can use String.Format("{0}\**\*.msi;{0}\**\*.exe", SourcesDirectory)
The FindMatchingFiles activity's MatchPattern property uses the
Syntax that is supported by the searchPattern argument of the Directory.GetFiles(String, String) method.
That means that you can't combine multiple extensions. You'll need to call the FindMatchingFiles activity twice. You can then combine the results of those two calls when you use them (i.e. if your results are msiFiles and exeFiles, you can use msiFiles.Concat(exeFiles) as the input to a ForEach).
However, as you can see with #antwoord's answer, the activity does actually seem to accept a semi-colon delimited list of patterns, unlike Directory.GetFiles.
FindMatchingFiles has some strange search pattern. Here is the code (decompiled using ILSpy) so you can test your search patterns without having to kick off a new build.
It contains a hardcoded root dir at the following location (Z:)
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
Code:
using System;
using System.Collections.Generic;
using System.IO;
namespace DirectoryGetFiles
{
//// Use the FindMatchingFiles activity to find files. Specify the search criteria in the MatchPattern (String) property.
//// In this property, you can specify an argument that includes the following elements:
//// Syntax that is supported by the searchPattern argument of the Directory GetFiles(String, String) method.
////
//// ** to specify a recursive search. For example:
//// To search the sources directory for text files, you could specify something that resembles the following
//// value for the MatchPattern property: String.Format("{0}\**\*.txt", SourcesDirectory).
////
//// To search the sources directory for text files in one or more subdirectories that are called txtfiles,
//// you could specify something that resembles the following value for the MatchPattern property:
//// String.Format("{0}\**\txtfiles\*.txt", SourcesDirectory).
class Program
{
static void Main(string[] args)
{
string searchPattern = #"_PublishedWebsites\Web\Scripts\jasmine-specs**\*.js";
var results = Execute(searchPattern);
foreach (var i in results)
{
Console.WriteLine("found: {0}", i);
}
Console.WriteLine("Done...");
Console.ReadLine();
}
private static IEnumerable<string> Execute(string pattern)
{
string text = pattern;
text = text.Replace(";;", "\0");
var hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
string[] array = text.Split(new char[]
{
';'
}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
string text2 = array[i];
string text3 = text2.Replace("\0", ";");
if (IsValidPattern(text3))
{
List<string> list = ComputeMatchingPaths(text3);
if (list.Count > 0)
{
using (List<string>.Enumerator enumerator = list.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
hashSet.Add(current);
}
goto IL_15C;
}
}
////Message = ActivitiesResources.Format("NoMatchesForSearchPattern", new object[]
}
else
{
//// Message = ActivitiesResources.Format("InvalidSearchPattern", new object[]
}
IL_15C: ;
}
return hashSet;//.OrderBy((string x) => x, FileSpec.TopDownComparer);
}
private static bool IsValidPattern(string pattern)
{
string text = "**" + Path.DirectorySeparatorChar;
int num = pattern.IndexOf(text, StringComparison.Ordinal);
return (num < 0 || (pattern.IndexOf(text, num + text.Length, StringComparison.OrdinalIgnoreCase) <= 0 && pattern.IndexOf(Path.DirectorySeparatorChar, num + text.Length) <= 0)) && pattern[pattern.Length - 1] != Path.DirectorySeparatorChar;
}
private static List<string> ComputeMatchingPaths(string matchPattern)
{
List<string> list = new List<string>();
string text = "**" + Path.DirectorySeparatorChar;
int num = matchPattern.IndexOf(text, 0, StringComparison.OrdinalIgnoreCase);
if (num >= 0)
{
List<string> matchingDirectories = GetMatchingDirectories(#"Z:", matchPattern.Substring(0, num), 0);
string searchPattern = matchPattern.Substring(num + text.Length);
using (List<string>.Enumerator enumerator = matchingDirectories.GetEnumerator())
{
while (enumerator.MoveNext())
{
string current = enumerator.Current;
list.AddRange(Directory.GetFiles(current, searchPattern, SearchOption.AllDirectories));
}
return list;
}
}
int num2 = matchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (num2 >= 0)
{
List<string> matchingDirectories2 = GetMatchingDirectories(string.Empty, matchPattern.Substring(0, num2 + 1), 0);
string searchPattern2 = matchPattern.Substring(num2 + 1);
using (List<string>.Enumerator enumerator2 = matchingDirectories2.GetEnumerator())
{
while (enumerator2.MoveNext())
{
string current2 = enumerator2.Current;
try
{
list.AddRange(Directory.GetFiles(current2, searchPattern2, SearchOption.TopDirectoryOnly));
}
catch
{
}
}
return list;
}
}
try
{
list.AddRange(Directory.GetFiles(Directory.GetCurrentDirectory(), matchPattern, SearchOption.TopDirectoryOnly));
}
catch
{
}
return list;
}
private static List<string> GetMatchingDirectories(string rootDir, string pattern, int level)
{
if (level > 129)
{
return new List<string>();
}
List<string> list = new List<string>();
int num = pattern.IndexOf('*');
if (num >= 0)
{
int num2 = pattern.Substring(0, num).LastIndexOf(Path.DirectorySeparatorChar);
string text = (num2 >= 0) ? Path.Combine(rootDir, pattern.Substring(0, num2 + 1)) : rootDir;
if (text.Equals(string.Empty))
{
text = Directory.GetCurrentDirectory();
}
int num3 = pattern.IndexOf(Path.DirectorySeparatorChar, num);
if (num3 < 0)
{
num3 = pattern.Length;
}
string searchPattern = pattern.Substring(num2 + 1, num3 - num2 - 1);
try
{
string[] directories = Directory.GetDirectories(text, searchPattern, SearchOption.TopDirectoryOnly);
if (num3 < pattern.Length - 1)
{
string pattern2 = pattern.Substring(num3 + 1);
string[] array = directories;
for (int i = 0; i < array.Length; i++)
{
string rootDir2 = array[i];
list.AddRange(GetMatchingDirectories(rootDir2, pattern2, level + 1));
}
}
else
{
list.AddRange(directories);
}
return list;
}
catch
{
return list;
}
}
string text2 = Path.Combine(rootDir, pattern);
if (text2.Equals(string.Empty))
{
list.Add(Directory.GetCurrentDirectory());
}
else
{
if (Directory.Exists(text2))
{
list.Add(Path.GetFullPath(text2));
}
}
return list;
}
}
}

Resources