VB.Net compiler error when compare with Nothing.

I’ve got a compiler error


 Compiler Error Message: BC30452: Operator ‘<>’ is not defined for types ‘BaseResultItemsListUsc’ and ‘BaseResultItemsListUsc’.


If listResults <> Nothing Then
End If


Of course, the correct code should be
If listResults isNot Nothing Then
or
If Not (listResults is Nothing) Then
or
If Not IsNothing(listResults) Then


I made a search that there are a few other places where the <> Nothing  was used e.g.


If Request.QueryString(“Field”) <> Nothing then


dim r as DataRow
If r(x) <> “” And r(x) <> Nothing Then


It seems that compiler doesn’t report “ <> Nothing“ for Object type, but reports errors for strong typed varables.

use VS 2005 or VS 2003 due to VS 2005 slowness?

One reader of my post “How to fix “Visual Studio 2005 is very slow” problem -no solution so far“ asked me should he use VS 2005 or VS 2003:

 “We recently moved from VB6 environment to .net.  We started our project in VS 2005 , asp.2.0 . But the issue is VS 2005 is VERY Slow on our computers. My Team members are getting frustrated.

 I increased the Ram to 1 GB… still no significant improvement!  (yet to implement the hot fix).”

 

I’ve posted his questions and my answers here:

1) apart from being slow does VS 2005 has any other major problems?


 


2) Will our customers suffer in any way ? (speed, frequent crashes etc)

I believe that .Net 2. is more reliable than .Net 1.1

3) Since i have just started in VS 2005 , Should i roll back to VS 2003 ?


 My personal preference is VS 2005(even if it is slow for some ASP.NET Projects).

4) Will the migration from VS 2003 to VS 2005 later will be easy ?


 Note that VS 2005 now has 2 projects -Web Site Projects and Web Application Projects


5) What about the learning Curve (from VS 2003 to VS 2005)

You need to learn new features if you want to use them. To do the same things in most cases VS virsions are similar, in many cases VS 2005 more user friendly, in some (not often) scenarios VS 2005 is not good (e.g. http://geekswithblogs.net/mnf/archive/2006/01/09/65292.aspx)

6) how is deployment in VS 2005 does it have problems?

Ther are some differences with VS 2003, but they are resolvable. 

7) The core focus of our company will be developement of softwares for PDA…… will rolling back to VS 2003

affect this ?

I have no idea.

8) Do you think that MS will launch SP 1 for VS 2005 soon?

MS promissed  SP 1 for VS 2005 in the second half of 2006.

 

How to refer to parent DataGrid from DataGridItem – use NamingContainer

It’s published in a few places, but I had to do a few Google searches before confirming that you should use NamingContainer property to get parent DataGrid for DataGridItem. So I’ve created a shared method in my WebFormsHelper class.


    Public Shared Function ParentDataGrid(ByVal Item As DataGridItem) As DataGrid


        ‘ Dim gridTable As DataGridTable = Item.Parent ‘DataGrid = gridTable.Parent doesn’t work because  MS declared DataGridTable as private(why?)


        Dim grid As DataGrid = Item.NamingContainer


        Return grid


    End Function

HyperLink for files with spaces in the path not working in Internet Explorer.

I was using asp:hyperlink  control to show links to local LAN files , e.g.

<asp:HyperLink ID=”lnkToClick” runat=”server”>link to LAN fileasp:HyperLink>

 Me.lnkToClick.NavigateUrl = file://\ServerFolderFileName.ext

 It worked fine, unless Folder path or filename has spaces in it(Probably other special character could cause the same problem). In this case, generated html file has %20 instead of space and clicking on the generated link in IE doesn’t open file.
In othe words Internet Explorer 6. doesn’t open the following link
        file://\databasedocssallystaff’ _fcksavedurl=’file://\ServerFolderTWO%20WORDS.doc”>file://\databasedocssallystaff’>file://\ServerFolderTWO%20WORDS.doc”>file://\ServerFolderTWO WORDS.doc

After some investigation with Reflector I found that HyperLink calls AddAttributesToRender, which calls  ResolveClientUrl, which in turn calls  HttpUtility.UrlPathEncode. And there is no simple way to exclude encoding for “file://“ paths.
There is ASP.NET 2.0  asp:hyperlink  control bug, the control worked correctly in ASP.NET 1.1 .

However ther is a simple alternative -use A control instead of HyperLink.

<a ID=”lnkToClick” runat=”server”>link to LAN file</a>

 

 Me.lnkToClick.href = file://\ServerFolderFileName.ext

The similar problem is reported to MS here.

One reader of the post asked how to replace  
<asp:HyperLink runat=”server” Target=”_blank” Text=”<img src=pdficon_small.gif border=0 align=absmiddle alt=’Load PDF File’>” NavigateUrl='<%# DataBinder.Eval(Container, “DataItem.FilePath”) %>’>
</asp:HyperLink>

My suggestion was:

<a runat=”server” target=”_blank”  href='<%# DataBinder.Eval(Container, “DataItem.FilePath”) %>’>
<img src=pdficon_small.gif border=0 align=absmiddle alt=’Load PDF File’>
</a>

DotNetNuke: InstallationDate entry in web.Config can be missing.

We had couple sites when during install of DotNetNuke(4.0.3) there was a known “Nothing to Install At This Time” message.
I’ve tried to investigate , how it could happen.
At the first installation the function Install.InstallApplication (InstallInstall.aspx.vb) checks web.config file.
If InstallationDate  is missing, it tries to call Config.UpdateMachineKey, which should add InstallationDate element and save web.config.
If the save not succced, the DotNetNuke Configuration Error“ error(403-3.htm) is reported.
However if the new DotNetNuke Web Application  with web.config file is attached to database with DNN tables installed,
 Install.InstallApplication is not called and InstallationDate element is not added.


However in event handler Application_BeginRequest(App_CodeGlobal.asax.vb) web.config file is checked if InstallationDate  is missing:
            Dim installationDate As String = Config.GetSetting(“InstallationDate”)
            If installationDate Is Nothing Or installationDate = “” Then
                Response.Redirect(“~/Install/Install.aspx?mode=none”)
            End If


mode=none invokes NoUpgrade() method(InstallInstall.aspx.vb) which doesn’t do any installation, but compares database and assembly version and shows link to install or shows  “Nothing to Install At This Time” message.


It will be good if
1.NoUpgrade() name will be changed to more descriptive WriteResponseIfUpdatesRequired
2.the function will also check
InstallationDate element in web.config and add clear instruction/link to update if the element is missing.


I’ve posted my suggestion to DNN support
 

my VB.Net WebFormsHelper class

I’ve posted a few code snippets and some people noticed that there are references to unresolved methods.I am using a few helper classes. This post describes my VB.Net WebFormsHelper class. 

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.HtmlControls

Imports System.Data

Imports System.Data.SqlClient

Imports System.Text

Imports Microsoft.ApplicationBlocks.Data

Imports FSHelperLib.DataHelper

Imports System.Data.Common

 

Public Class WebFormsHelper

#Region “DataGrid columns search”

 

    Public Shared Function ColumnByHeaderText(ByVal Columns As DataGridColumnCollection, ByVal HeaderText As String) As DataGridColumn

        Dim oRet As DataGridColumn = Nothing

        Dim i As Integer = ColumnIndexByHeaderText(Columns, HeaderText)

        If i >= 0 Then

            oRet = Columns(i)

        End If

        Return oRet

    End Function

    Public Shared Function ColumnIndexByHeaderText(ByVal Columns As DataGridColumnCollection, ByVal HeaderText As String) As Integer

        For i As Integer = 0 To Columns.Count – 1

            If Columns(i).HeaderText = HeaderText Then

                Return i

            End If

        Next i

        Return -1

    End Function

    Public Shared Function ColumnIndexBySortExpression(ByVal Columns As DataGridColumnCollection, ByVal SortExpression As String) As Integer

        For i As Integer = 0 To Columns.Count – 1

            If Columns(i).SortExpression = SortExpression Then

                Return i

            End If

        Next i

        Return -1

    End Function

    ‘MNF 6/8/2004 created ColumnByFooterText and ColumnIndexByFooterText

    Public Shared Function ColumnByFooterText(ByVal Columns As DataGridColumnCollection, ByVal text As String) As DataGridColumn

        Dim oRet As DataGridColumn = Nothing

        Dim i As Integer = ColumnIndexByFooterText(Columns, text)

        If i >= 0 Then

            oRet = Columns(i)

        End If

        Return oRet

    End Function

    Public Shared Function ColumnIndexByFooterText(ByVal Columns As DataGridColumnCollection, ByVal text As String) As Integer

        For i As Integer = 0 To Columns.Count – 1

            If LCase(Columns(i).FooterText) = LCase(text) Then

                Return i

            End If

        Next i

        Return -1

    End Function

    ‘If not exists return false

    Public Shared Function ColumnByFooterVisibleIfExists(ByVal Columns As DataGridColumnCollection, ByVal FooterName As String, ByVal Visible As Boolean) As Boolean

        Dim clmn As DataGridColumn = ColumnByFooterText(Columns, FooterName)

        Dim bRet As Boolean = False

        If IsNothing(clmn) Then

            bRet = False

        Else

            clmn.Visible = Visible

        End If

        Return bRet

    End Function

    Public Shared Function ColumnByFooterVisible(ByVal Columns As DataGridColumnCollection, ByVal FooterName As String, ByVal Visible As Boolean) As Boolean

        Dim bRet As Boolean = ColumnByFooterVisibleIfExists(Columns, FooterName, Visible)

        If bRet Then  ‘IsNothing(clmn)

            Debug.Assert(False)

        End If

        Return bRet

    End Function

    ‘See http://www.mcse.ms/showthread.php?s=&postid=1481861

    ‘Alternative way is to specify ID in controls within the cell and 

    Public Shared Function CellByHeaderText(ByVal Item As DataGridItem, ByVal HeaderText As String) As TableCell

        ‘ Dim gridTable As DataGridTable = Item.Parent ‘DataGrid = gridTable.Parent doesn’t work because  MS declared DataGridTable as private(why?)

        Dim grid As DataGrid = Item.NamingContainer

        Dim nColumn As Integer = ColumnIndexByHeaderText(grid.Columns, HeaderText)

        If nColumn < 0 Then

            Return Nothing

        Else

            Return Item.Cells(nColumn)

        End If

    End Function

    Public Shared Function CellByFooterText(ByVal Item As DataGridItem, ByVal FooterText As String) As TableCell

        ‘ Dim gridTable As DataGridTable = Item.Parent ‘DataGrid = gridTable.Parent doesn’t work because  MS declared DataGridTable as private(why?)

        Dim grid As DataGrid = Item.NamingContainer

        Dim nColumn As Integer = ColumnIndexByFooterText(grid.Columns, FooterText)

        If nColumn < 0 Then

            Return Nothing

        Else

            Return Item.Cells(nColumn)

        End If

    End Function

    Public Shared Function CellBySortExpression(ByVal Item As DataGridItem, ByVal SortExpression As String) As TableCell

        ‘ Dim gridTable As DataGridTable = Item.Parent ‘DataGrid = gridTable.Parent doesn’t work because  MS declared DataGridTable as private(why?)

        Dim grid As DataGrid = Item.NamingContainer

        Dim nColumn As Integer = ColumnIndexBySortExpression(grid.Columns, SortExpression)

        If nColumn < 0 Then

            Return Nothing

        Else

            Return Item.Cells(nColumn)

        End If

    End Function

     Public Shared Function ParentDataGrid(ByVal Item As DataGridItem) As DataGrid

        ‘ Dim gridTable As DataGridTable = Item.Parent ‘DataGrid = gridTable.Parent doesn’t work because  MS declared DataGridTable as private(why?)

        Dim grid As DataGrid = Item.NamingContainer

        Return grid

    End Function

 

#End Region  ‘”DataGrid columns search”

#Region ” datagrid items helpers”

 

    ‘Separate oveloads for DataGridItem and RepeaterItem

    Public Shared Function IsItemNormalOrAlterating(ByVal item As System.Web.UI.WebControls.DataGridItem) As Boolean

        Return item.ItemType = ListItemType.Item Or item.ItemType = ListItemType.AlternatingItem

    End Function

    Public Shared Function IsItemNormalOrAlterating(ByVal item As System.Web.UI.WebControls.RepeaterItem) As Boolean

        Return item.ItemType = ListItemType.Item Or item.ItemType = ListItemType.AlternatingItem

    End Function

#End Region  ‘//datagrid items helpers

    Public Shared Function CurrentPageIndexAdjustIfRequired(ByVal dg As DataGrid, ByVal nCount As Integer) As Boolean

        ‘If the last row on the last page is deleted, the following error can happen: Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount.

        ‘Possible workaround- catch error see http://groups.google.com.au/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=29aa01c1d59b%248257bdc0%243aef2ecf%40TKMSFTNGXA09

        ‘Solution used from http://www.devarticles.com/index2.php?option=content&task=view&id=495&pop=1&page=0&hide_js=1

        ‘ Unfortunutely,The actual  DataGrid.PageCount  is the “old” page count.

        ‘ The new page count of the DataGrid control will be set automatically after we bind the Datagrid to the data source

        ‘ with new page size set, but it’s too late to avoid exception.

        ‘ We need the new page count already now to find out the new current page index, so we must calculate it.

        Dim nNewPageCount As Integer = CType(Math.Ceiling(nCount / dg.PageSize), Integer)

        ‘ get the new current page index

        If dg.CurrentPageIndex >= nNewPageCount And nNewPageCount > 0 Then

            dg.CurrentPageIndex = nNewPageCount – 1

        End If

    End Function

 

 

#Region “ListLoad”

    ‘see also CacheHelper.LoadToCacheDictionary

    Public Shared Sub ListLoad(ByVal lst As System.Web.UI.WebControls.ListControl, ByVal sConnString As String, _

         ByVal sSQL As String, _

        ByVal sTextColumn As String, ByVal sValueColumn As String, ByVal sToSelectPrompt As String)

 

        ‘TODO -see also CacheHelper.LoadToCacheAndListControl

        If Not IsNothing(sToSelectPrompt) Then

            lst.Items.Add(New ListItem(sToSelectPrompt, -1))

        End If

        Dim rdr As SqlDataReader = Nothing, sTxt As String

        Try

            rdr = SqlHelper.ExecuteReader(sConnString, CommandType.Text, sSQL)

            While rdr.Read

                ‘RemoveNonPreservedSpace is important for Metabuilder.combobox

                sTxt = HtmlHelper.RemoveNonPreservedSpace(Trim(Coalesce(rdr.Item(sTextColumn), “”)))

                lst.Items.Add(New ListItem(sTxt, Coalesce(rdr.Item(sValueColumn), “”)))

            End While

        Finally

            If Not rdr Is Nothing Then rdr.Close()

        End Try

    End Sub

    Public Shared Sub ListLoad(ByVal lst As System.Web.UI.WebControls.ListControl, ByVal enumType As Type, ByVal sToSelectPrompt As String)

        If Not IsNothing(sToSelectPrompt) Then

            lst.Items.Add(New ListItem(sToSelectPrompt, -1))

        End If

        For Each i As Integer In [Enum].GetValues(enumType)

            lst.Items.Add(New ListItem([Enum].GetName(enumType, i), i))

        Next i

    End Sub

    Public Shared Sub ListLoad(ByVal lst As System.Web.UI.WebControls.ListControl, ByVal sListString As String, ByVal Delimeter As String, _

            ByVal sToSelectPrompt As String)

        If Not IsNullOrEmpty(sToSelectPrompt) Then

            lst.Items.Add(New ListItem(sToSelectPrompt, -1))

        End If

        Dim sValues As String() = sListString.Split(Delimeter)

        For Each sValue As String In sValues

            lst.Items.Add(New ListItem(sValue))

        Next

    End Sub

#End Region ‘”ListLoad”

    ‘Note this overload works only if PlaceHolder belongs to page, not other user control

    Public Shared Function LoadAddUserControl(ByVal PlaceHolder As Control, ByVal sAscxName As String) As UserControl

        Return LoadAddUserControl(PlaceHolder, sAscxName, Nothing)

    End Function

    Public Shared Function LoadAddUserControl(ByVal PlaceHolder As Control, ByVal sAscxName As String, ByVal ID As String) As UserControl

        Dim ctlToAdd As UserControl

        ctlToAdd = PlaceHolder.Page.LoadControl(sAscxName)

        If Not (ID Is Nothing) Then

            ctlToAdd.ID = ID

        End If

        PlaceHolder.Controls.Add(ctlToAdd)

        Return ctlToAdd

    End Function

#Region “Visible/Enabled methods”

 

    ‘visible doesn’t create any html at all, but this make it hidden and keep data in viewState, alternatively use HtmlInputHidden

    ‘TODO overload for HTmlControl

    Public Shared Function HideControl(ByVal ctrl As System.Web.UI.WebControls.WebControl) As Boolean

        ctrl.Style(“visibility”) = “hidden”

    End Function

    ‘visible doesn’t create any html at all

    ‘TODO overload for HTmlControl

    Public Shared Function SetChildVisible(ByVal ctrlParent As System.Web.UI.Control, ByVal ClientID As String, ByVal Visible As Boolean) As Boolean

        Dim ctrl As Control = ctrlParent.FindControl(ClientID)

        If ctrl Is Nothing Then

            Debug.Assert(False, “control not found”)

        Else

            ctrl.Visible = Visible

        End If

    End Function

    Public Shared Function SetChildEnabled(ByVal ctrlParent As System.Web.UI.Control, ByVal ClientID As String, ByVal Enabled As Boolean) As Boolean

        ‘TODO Current version works for WebControl only , handle  for HTmlControl as well

        Dim ctrl As WebControl = ctrlParent.FindControl(ClientID)

        If ctrl Is Nothing Then

            Debug.Assert(False, “control not found”)

        Else

            ctrl.Enabled = Enabled

        End If

    End Function

#End Region  ‘//”Visible/Enabled methods”

 

 

#Region “HideEmptyRows overload methods”

    ‘called from DetailedListPage to hide rows without data

    Public Shared Sub HideEmptyRow(ByVal rdr As DbDataRecord, ByVal item As System.Web.UI.WebControls.RepeaterItem, ByVal ColumnName As String, Optional ByVal trID As String = “”)

        Dim tr As Control

        If trID.Length = 0 Then trID = “tr” & ColumnName

        If IsDBNullOrEmpty(rdr(ColumnName)) Then

            tr = item.FindControl(trID)

            tr.Visible = False

        End If

    End Sub

    Public Shared Sub HideEmptyRowWithLabelControl(ByVal item As System.Web.UI.WebControls.RepeaterItem, ByVal ControlName As String, Optional ByVal trID As String = “”)

        Dim tr As Control

        Dim ctrl As Label = CType(item.FindControl(ControlName), Label)

        If trID.Length = 0 Then trID = “tr” & ControlName

        If ctrl.Text.Trim.Length = 0 Then

            tr = item.FindControl(trID)

            If IsNothing(tr) Then

                DebugHelper.PrintChildren(item)

                Debug.Assert(False, “Unable to find control “ & trID)

            Else

                tr.Visible = False

            End If

        End If

    End Sub

    Public Shared Sub HideEmptyRowWithGrid(ByVal item As System.Web.UI.WebControls.RepeaterItem, ByVal ControlName As String, Optional ByVal trID As String = “”)

        Dim tr As Control

        Dim grd As DataGrid = CType(item.FindControl(ControlName), DataGrid)

        If trID.Length = 0 Then trID = “tr” & ControlName

        If grd.Items.Count = 0 Then

            tr = item.FindControl(trID)

            If IsNothing(tr) Then

                DebugHelper.PrintChildren(item)

                Debug.Assert(False, “Unable to find control “ & trID)

            Else

                tr.Visible = False

            End If

        End If

    End Sub

#End Region ‘”HideEmptyRows overload methods”

    ‘Returns Url from DataGridItem

    Public Shared Function GetHyperlinkUrl(ByVal item As System.Web.UI.WebControls.DataGridItem, ByVal ControlName As String) As String

        Dim lnk As HyperLink = CType(item.FindControl(ControlName), HyperLink)

        If IsNothing(lnk) Then

            DebugHelper.PrintChildren(item)

            Debug.Assert(False, “Unable to find control “ & ControlName)

            Return “”

        Else

            Return lnk.NavigateUrl

        End If

    End Function

    Public Shared Sub SetTargetBlankIfRequired(ByVal item As System.Web.UI.WebControls.DataGridItem, ByVal ControlName As String, ByVal bTargetBlank As Boolean)

        Dim lnk As HyperLink = CType(item.FindControl(ControlName), HyperLink)

        SetTargetBlankIfRequired(lnk, bTargetBlank)

    End Sub

    Public Shared Sub SetTargetBlankIfRequired(ByVal link As HyperLink, ByVal bTargetBlank As Boolean)

        If IsNothing(link) Then Return

        If True = bTargetBlank Then

            link.Attributes.Remove(“target”) ‘ //clear old target if any

            link.Attributes.Add(“target”, “_blank”)

        End If

    End Sub

 

 

    ‘To Clear  all data-entry controls (TextBox or CheckBox) iterative to children /?,ComboBox

    Public Shared Function ClearAllEditControls(ByVal container As System.Web.UI.Control) As Boolean

        Dim ctrl As Control, tBox As TextBox, chkBox As CheckBox

        For Each ctrl In container.Controls

            If TypeOf ctrl Is TextBox Then

                tBox = CType(ctrl, TextBox)

                tBox.Text = “”

            ElseIf TypeOf ctrl Is CheckBox Then

                chkBox = CType(ctrl, CheckBox)

                chkBox.Checked = False

            ElseIf Not (ctrl.Controls Is Nothing) Then

                ClearAllEditControls(ctrl)

            End If

        Next

    End Function

    ‘call FindPageForm(me), where me is a page

    ‘http://groups.google.com.au/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=uxbuSlKfDHA.3216%40tk2msftngp13.phx.gbl

    ‘ recurse controls, favoring NOT to dive deep before finding the HtmlForm

    Public Shared Function FindPageForm(ByVal parent As Control) As System.Web.UI.HtmlControls.HtmlForm

        Dim current As Control

        For Each current In parent.Controls

            If TypeOf (current) Is HtmlForm Then

                Return CType(current, HtmlForm)

            End If

        Next

        For Each current In parent.Controls

            Dim f As HtmlForm = FindPageForm(current)

            If Not f Is Nothing Then

                Return f

            End If

        Next

        Return Nothing

    End Function

    Public Shared Function FindControlAddAttribute(ByVal parent As Control, ByVal sControlName As String, _

            ByVal AttributeKey As String, ByVal AttributeValue As String) As Boolean

            Dim current As Control

        Dim bRet As Boolean = False

        Dim ctrl As Control

        ctrl = CType(parent.FindControl(sControlName), Button)

        If Not IsNothing(ctrl) Then

            If TypeOf ctrl Is WebControl Then

                Dim webCtrl As WebControl = ctrl

                webCtrl.Attributes.Add(AttributeKey, AttributeValue)

                bRet = True

            Else

                Debug.Assert(” Not implemented”)

            End If

        End If

        Return bRet

    End Function

 

    ‘Globally Replace “Response.Redirect(” with “WebFormsHelper.SmartRedirect(Page,”

    ‘I’ve noticed(not confirmed that it happened always) that browser doesn’t refreshed URL in address bar(?)

    Public Shared Sub SmartRedirect(ByVal p As Page, ByVal url As String)

        ‘Smartnavigation breaks Response.Redirect  see http://dotnetjunkies.com/WebLog/petergekko/archive/2003/09/15/1609.aspx

        ‘Obsolete p.SmartNavigation = False

        Dim resp As HttpResponse = p.Response

        ‘TODO try to re-code  Response.Redirect(ByVal url As String, ByVal endResponse As Boolean) to ensure that it works correctly

        ‘Dim page1 As Page = TryCast(Me._context.Handler, Page)

        ‘If (((Not page1 Is Nothing) AndAlso page1.IsPostBack) AndAlso page1.SmartNavigation) Then

        p.Response.Redirect(url)

    End Sub

    ‘e.g RadioButtonList

    Public Shared Function GetSelectedItemValue(ByVal ctrl As ListControl, ByVal sDefault As String) As String

        ‘If by some reason no item is  selected(not sure how it happened????), default should be used

        ‘TODO:? it seems that SelectedValue is better than SelectedItem.Value

        Dim sRet As String

        If ctrl Is Nothing Then

            DebugHelper.TracedLine(  ctrl Is Nothing “)

            sRet = sDefault

        Else

            If ctrl.SelectedItem Is Nothing Then

                sRet = sDefault

            Else

                sRet = CInt(ctrl.SelectedItem.Value)

            End If

        End If

        Return sRet

    End Function

    ’22/5/2006

    Public Shared Function SelectedItemsValuesAsCommaSeparatedList(ByVal ctrl As ListControl) As String

        Dim sRet As String = “”

        If ctrl Is Nothing Then

            DebugHelper.TracedLine(  ctrl Is Nothing “)

        Else

            Dim li As ListItem

            Dim sb As New StringBuilder()

            For Each li In ctrl.Items

                If li.Selected = True Then

                    sb.AppendFormat(“{0},”, li.Value)

                End If

            Next

            sRet = StringHelper.LeftBeforeLast(sb.ToString(), “,”)

        End If

        Return sRet

    End Function

    ‘TODO Create overload to add value, if not exists

    Public Shared Sub SetSelectedValue(ByVal ctrl As ListControl, ByVal value As String, ByVal sDefault As String) ‘As String

        ‘From http://groups.google.com.au/group/microsoft.public.dotnet.framework.aspnet/msg/031390d64b55db17?hl=en

        ‘ Settings “SelectedValue” will select another item in the DropDownList

        ‘while “SelectedItem.Value” will change the value of the currently selected item.

        Try

            ctrl.SelectedValue = value

        Catch ex As Exception

            Try

                ctrl.SelectedValue = sDefault

            Catch exDef As Exception

                ctrl.SelectedValue = “”

            End Try

        End Try

    End Sub

    ’26/10/2005

    Public Shared Function AddTextAndValue(ByVal ctrl As ListControl, ByVal text As String) As ListItem

        ‘The MS ipplementation ListItemCollection.Add Method (String)  assignes null to value

        Dim li As New ListItem(text, text)

        ctrl.Items.Add(li)

        Return li

    End Function

 

End Class

 

 

My StringHelper class

I’ve posted a few code snippets and some people noticed that there are references to unresolved methods.I am using a few helper classes. This post describes my StringHelper class. 
By the way, I recently found (in the article Concatenating Strings Efficiently), that using StringBuilder is often less efficient, than simple concatenation.

Related posts:Helper functions to find pattern contaned in string from pattern List 

ProperCase function in C#  

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace Common
  8. {
  9.         using Microsoft.VisualBasic;
  10.         using System;
  11.         using System.IO;
  12.         using System.Reflection;
  13.         using System.Text;
  14.         using System.Text.RegularExpressions;
  15.  
  16.         public static class StringHelper
  17.         {
  18.  
  19.                 // See also Westwind.Utilities.StringUtils     
  20.                 //’See also FxLib Author: Kamal Patel, Rick Hodder
  21.                 //      ‘Find the first entry of sToFind and returns the string after it
  22.                 //      ‘See also FxLib StringExtract (and StuffString)
  23.                 // Methods
  24.                 #region “String Functions”
  25.  
  26.  
  27.                 public static string LeftBefore(this string str, string sToFind)
  28.                 {
  29.                         return LeftBefore(str, sToFind, false);
  30.                 }
  31.                 //              ‘if sToFind not found, then the full string should be returned
  32.                 //              ‘if sToFind is empty, all string should be returned
  33.                 public static string LeftBefore(this string str, string sToFind, bool EmptyIfNotFound)
  34.                 {
  35.                         StringBuilder builder1 = new StringBuilder(str);
  36.                         if (sToFind.Length > 0)
  37.                         {
  38.                                 int num1 = str.IndexOf(sToFind);
  39.                                 if (num1 < 0)
  40.                                 {
  41.                                         if (EmptyIfNotFound == true) return “”;
  42.                                         else return str;// 6/7/2005 full string should be returned
  43.                                 }
  44.                                 builder1.Remove(num1, builder1.Length  num1);
  45.                         }
  46.                         return builder1.ToString();
  47.                 }
  48.                 //              ‘if sToFind not found, then original string should be returned
  49.                 public static string LeftBeforeLast(this string str, string sToFind)
  50.                 {
  51.                         StringBuilder builder1 = new StringBuilder(str);
  52.                         if (sToFind.Length > 0)
  53.                         {
  54.                                 int num1 = str.LastIndexOf(sToFind);
  55.                                 if (num1 < 0)
  56.                                 {
  57.                                         return str;
  58.                                 }
  59.                                 builder1.Remove(num1, builder1.Length  num1);
  60.                         }
  61.                         return builder1.ToString();
  62.                 }
  63.                 public static string LeftBeforeLast(this string str, string sToFind, intFindNumberTimes)//6/1/2006
  64.                 {
  65.                         for (int i = 0; i < FindNumberTimes; i++)
  66.                         {
  67.                                 str = LeftBeforeLast(str, sToFind);
  68.                         }
  69.                         return str;
  70.                 }
  71.  
  72.                 //              ‘if sBefore not found, then string from the beginning should be returned
  73.                 //              ‘if sAfter not found, then string up to the end should be returned
  74.                 public static string MidBetween(this string str, string sBefore, string sAfter)
  75.                 {
  76.                         return MidBetween(str, sBefore, sAfter, false);
  77.                 }
  78.                 public static string MidBetween(this string str, string sBefore, string sAfter, boolEmptyIfNotFound)
  79.                 {
  80.                         string text2 = RightAfter(str, sBefore, EmptyIfNotFound);
  81.                         return LeftBefore(text2, sAfter, EmptyIfNotFound);
  82.                 }
  83.                
  84.                 /// <summary>
  85.                 ///if sToFind not found, then original string should be returned
  86.                 ///if sToFind is empty, all string should be returned
  87.                 /// </summary>
  88.                 /// <param name=”str”></param>
  89.                 /// <param name=”sToFind”></param>
  90.                 public static string RightAfter(this string str, string sToFind)
  91.                 {
  92.                         return RightAfter(str, sToFind, false);
  93.                 }
  94.                 /// <summary>
  95.                 ///
  96.                 /// </summary>
  97.                 /// <param name=”str”></param>
  98.                 /// <param name=”sToFind”></param>
  99.                 /// <param name=”EmptyIfNotFound”></param>
  100.                 /// <returns></returns>
  101.                 public static string RightAfter(this string str, string sToFind, bool EmptyIfNotFound)
  102.                 {
  103.                         StringBuilder builder1 = new StringBuilder(str);
  104.                         int num1 = str.IndexOf(sToFind);
  105.                         if (num1 < 0)
  106.                         {
  107.                                 if (EmptyIfNotFound == true) return “”;
  108.                                 else return str;
  109.                         }
  110.                         builder1.Remove(0, num1 + sToFind.Length);
  111.                         return builder1.ToString();
  112.                 }
  113.                 //
  114.                 /// <summary>
  115.                 ///if sToFind not found, then original string should be returned
  116.                 /// Otherwise removeBefore
  117.                 /// </summary>
  118.                 /// <param name=”str”></param>
  119.                 /// <param name=”sToFind”></param>
  120.                 /// <returns></returns>
  121.                 public static string RemoveBefore(this string str, string sToFind)
  122.                 {
  123.                         int num1 = str.IndexOf(sToFind);
  124.                         if (num1 > 0)
  125.                         {
  126.                                 return str.Remove(0, num1);
  127.                         }
  128.                         else
  129.                         {
  130.                                 return str;
  131.                         }
  132.                        
  133.                 }
  134.  
  135.                 //’Find the last entry of sToFind and returns the string after it
  136.                 //if sToFind not found, then original string should be returned ‘ 6/7/2005 change
  137.                 //if sToFind is empty, the original string should be returned
  138.                 public static string RightAfterLast(string str, string sToFind)
  139.                 {
  140.                         StringBuilder builder1 = new StringBuilder(str);
  141.                         int num1 = str.LastIndexOf(sToFind);
  142.                         if (num1 < 0)
  143.                         {
  144.                                 return str;
  145.                         }
  146.                         builder1.Remove(0, num1 + sToFind.Length);
  147.                         return builder1.ToString();
  148.                 }
  149.                 public static string RightAfterLast(string str, char chToFind, intnOccurencesNumber)//6/1/2006
  150.                 { //C++ solutions to find n’th occurence see http://www.codecomments.com/forum272/message731385.html
  151.                         string[] aStr = str.Split(chToFind);
  152.                         StringBuilder sb = new StringBuilder();
  153.                         int nPosInSplit = aStr.Length  nOccurencesNumber;
  154.                         for (int i = nPosInSplit; i < aStr.Length; i++)
  155.                         {
  156.                                 sb.Append(aStr[i]);
  157.                                 sb.Append(chToFind);
  158.                         }
  159.                         sb.Remove(sb.Length  1, 1);//1 for char
  160.                         return sb.ToString();
  161.                 }
  162.                 //’Removes the start part of the string, if it is matchs, otherwise leave string unchanged
  163.                 public static string TrimStart(this string str, string sStartValue)
  164.                 {
  165.                         if (!String.IsNullOrWhiteSpace(str) && str.StartsWith(sStartValue))
  166.                         {
  167.                                 str = str.Remove(0, sStartValue.Length);
  168.                         }
  169.                         return str;
  170.                 }
  171.                 //              ‘Removes the end part of the string, if it is matchs, otherwise leave string unchanged
  172.                 public static string TrimEnd(this string str, string sEndValue)
  173.                 {
  174.                         if (str == null) { throw new NullReferenceException(“str is null”); }
  175.                         if (str.EndsWith(sEndValue))
  176.                         {
  177.                                 str = str.Remove(str.Length  sEndValue.Length, sEndValue.Length);
  178.                         }
  179.                         return str;
  180.                 }
  181.                 /// <summary>
  182.                 /// If lenght of the string is greater than max allowed, remove the end
  183.                 /// </summary>
  184.                 /// <param name=”str”></param>
  185.                 /// <param name=”maxLength”></param>
  186.                 /// <returns></returns>
  187.                 public static string TrimLength(this string str, int maxLength)
  188.                 {
  189.                         if (str == null)
  190.                         {
  191.                                 return str;
  192.                         }
  193.                         if (str.Length > maxLength)
  194.                         {
  195.                                 str = str.Remove(maxLength);
  196.                         }
  197.                         return str;
  198.                 }
  199.                 //from http://mennan.kagitkalem.com/CommentView,guid,d8e01e32-49f3-4450-994a-990c4fa0a437.aspx
  200.                 //use the most efficient
  201.                 public static int OccurencesCount(string str, string sToFind)
  202.                 {
  203.                         string copyOrginal = String.Copy(str);
  204.                         int place = 0;
  205.                         int numberOfOccurances = 0;
  206.                         place = copyOrginal.IndexOf(sToFind.ToString());
  207.                         while (place != 1)
  208.                         {
  209.                                 copyOrginal = copyOrginal.Substring(place + 1);
  210.                                 place = copyOrginal.IndexOf(sToFind.ToString());
  211.                                 numberOfOccurances++;
  212.                         }
  213.                         return numberOfOccurances;
  214.                 }
  215.                 //case-incensitive replace from http://www.codeproject.com/cs/samples/fastestcscaseinsstringrep.asp?msg=1835929#xx1835929xx
  216.                 static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType)
  217.                 {
  218.                         if (original == null)
  219.                         {
  220.                                 return null;
  221.                         }
  222.  
  223.                         if (String.IsNullOrEmpty(pattern))
  224.                         {
  225.                                 return original;
  226.                         }
  227.  
  228.                         int lenPattern = pattern.Length;
  229.                         int idxPattern = 1;
  230.                         int idxLast = 0;
  231.  
  232.                         StringBuilder result = new StringBuilder();
  233.  
  234.                         while (true)
  235.                         {
  236.                                 idxPattern = original.IndexOf(pattern, idxPattern + 1, comparisonType);
  237.  
  238.                                 if (idxPattern < 0)
  239.                                 {
  240.                                         result.Append(original, idxLast, original.Length  idxLast);
  241.  
  242.                                         break;
  243.                                 }
  244.  
  245.                                 result.Append(original, idxLast, idxPattern  idxLast);
  246.                                 result.Append(replacement);
  247.  
  248.                                 idxLast = idxPattern + lenPattern;
  249.                         }
  250.  
  251.                         return result.ToString();
  252.                 }
  253.                 /// <summary>
  254.                 /// Uses regex ‘b’ as suggested in //http://stackoverflow.com/questions/6143642/way-to-have-string-replace-only-hit-whole-words
  255.                 /// </summary>
  256.                 /// <param name=”original”></param>
  257.                 /// <param name=”wordToFind”></param>
  258.                 /// <param name=”replacement”></param>
  259.                 /// <param name=”regexOptions”>e.g. RegexOptions.IgnoreCase</param>
  260.                 /// <returns></returns>
  261.                 static public string ReplaceWholeWord(this string original, string wordToFind, stringreplacement, RegexOptions regexOptions = RegexOptions.None)
  262.                 {
  263.                
  264.                 string  pattern = String.Format(@”b{0}b”, wordToFind);
  265.                 string ret = Regex.Replace(original, pattern, replacement, regexOptions);
  266.                         return ret;
  267.                 }
  268.                 /// <summary>
  269.                 /// Find the last entry of sToFind and replace it with sToReplace string
  270.                 /// </summary>
  271.                 /// <param name=”str”></param>
  272.                 /// <param name=”sToFind”>if sToFind not found, then original string should be returned.
  273.                 /// if sToFind is empty, the original string should be returned</param>
  274.                 /// <param name=”sToReplace”></param>
  275.                 /// <returns></returns>
  276.                 public static string ReplaceLast(this string str, string sToFind, string sToReplace)
  277.                 {
  278.                         StringBuilder builder1 = new StringBuilder(str);
  279.                         int num1 = str.LastIndexOf(sToFind);
  280.                         if (num1 < 0)
  281.                         {
  282.                                 return str;
  283.                         }
  284.                         builder1.Replace(sToFind, sToReplace, num1, sToFind.Length);
  285.                         return builder1.ToString();
  286.                 }
  287.                 public static string IfNotEmptyEnsureEndsWith(string str, string sEndValue)
  288.                 {
  289.                         if (String.IsNullOrEmpty(str)) return str; //21/10/2005
  290.                         if (!str.EndsWith(sEndValue))
  291.                         {
  292.                                 str = str + sEndValue;
  293.                         }
  294.                         return str;
  295.                 }
  296.                 public static string EnsureEndsWith(this string str, string sEndValue)
  297.                 {
  298.                         if (!str.EndsWith(sEndValue))
  299.                         {
  300.                                 str = str + sEndValue;
  301.                         }
  302.                         return str;
  303.                 }
  304.                 //converted from http://stackoverflow.com/questions/1250514/find-length-of-initial-segment-matching-mask-on-arrays
  305.                 public static string LongestCommonPrefix(string str1, string str2)
  306.                 {
  307.                         int minLen = Math.Min(str1.Length, str2.Length);
  308.                         for (int i = 0; i < minLen; i++)
  309.                         {
  310.                                 if (str1[i] != str2[i])
  311.                                 {
  312.                                         return str1.Substring(0, i);
  313.                                 }
  314.                         }
  315.                         return str1.Substring(0, minLen);
  316.                 }
  317.                 /// <summary>
  318.                 ///  Adds Prefix, if it is not exist in the string, case sensitive
  319.                 /// </summary>
  320.                 /// <param name=”str”>if null, returns prefix</param>
  321.                 /// <param name=”sPrefix”>if null or empty, returns original string</param>
  322.                 /// <returns></returns>
  323.                 public static string EnsureStartsWith(this string str, string sPrefix)
  324.                 {
  325.                         if (str == null)
  326.                         { //throw new ArgumentNullException(“str”);
  327.                                 return sPrefix;
  328.                         }
  329.                         if (!String.IsNullOrEmpty(sPrefix))
  330.                         {
  331.                                 if (!str.StartsWith(sPrefix))
  332.                                 {
  333.                                         str = sPrefix + str;
  334.                                 }
  335.                         }
  336.                         return str;
  337.                 }
  338.                 public static string AppendWithDelimeter(string str, string sToAppend, string delimeter)
  339.                 {
  340.                         if ((!str.EndsWith(delimeter) & !String.IsNullOrEmpty(str)) &!String.IsNullOrEmpty(sToAppend))
  341.                         {
  342.                                 str = str + delimeter;
  343.                         }
  344.                         str = str + sToAppend;
  345.                         return str;
  346.                 }
  347.                 public static string AppendIfNotContains(string str, string sToAppend, string delimeter)
  348.                 {
  349.                         if (!str.Contains(sToAppend))
  350.                         {
  351.                                 str = AppendWithDelimeter(str, sToAppend, delimeter);
  352.                         }
  353.                         return str;
  354.                 }
  355.                 public static string AppendIfNotEmpty(this string str, string prefixBeforeAppend,stringvalueToAppend,string suffixAfterAppend=“”)
  356.                 {
  357.                         if (!String.IsNullOrEmpty(valueToAppend))
  358.                         {
  359.                                 str += prefixBeforeAppend + valueToAppend + suffixAfterAppend;
  360.                         }
  361.                         return str;
  362.                 }
  363.                 //from http://66.102.7.104/search?q=cache:DSw2bnf_FlMJ:blogs.msdn.com/brada/archive/2004/02/16/73535.aspx+%22EndsWith+char+%22+string+C%23&hl=en
  364.                 //” internal bool EndsWith(char value) in String class. Why it would be internal? Also, there is no bool StartsWith(char value). “
  365.                 public static bool EndsWith(string str, char value)
  366.                 {
  367.                         int num1 = str.Length;
  368.                         if ((num1 != 0) && (str[num1  1] == value))
  369.                         {
  370.                                 return true;
  371.                         }
  372.                         return false;
  373.                 }
  374.                 public static bool StartsWith(string str, char value)
  375.                 {
  376.                         if ((str.Length != 0) && (str[0] == value))
  377.                         {
  378.                                 return true;
  379.                         }
  380.                         return false;
  381.                 }
  382.                 #region Case conversions
  383.  
  384.                 /// <summary>
  385.                 ///
  386.                 /// </summary>
  387.                 /// <param name=”input”></param>
  388.                 /// <returns></returns>
  389.                 /// <remarks>
  390.                 /// from http://dotnetjunkies.com/WebLog/davetrux/archive/2006/05/22/138692.aspx, http://west-wind.com/weblog/posts/361.aspx
  391.                 ///  http://www.logiclabz.com/c/title-case-proper-case-function-in-net-c.aspx
  392.                 /// use TextInfo.ToTitleCase(mText.ToLower());
  393.                 /// Alternative see From http://aspcode.net/propercase-function-in-c/
  394.                 ///     </remarks>
  395.                 public static string ToTitleCase(this string input)
  396.                 {
  397.                         input = input.ToLower();
  398.                         return Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(input);
  399.  
  400.                 }
  401.                 public static string ToCamelCase(this string s)
  402.                 {
  403.                         var sb = new StringBuilder();
  404.                         char[] ca = s.ToLower().ToCharArray();
  405.                         for (int i = 0; i < ca.Length; i++)
  406.                         {
  407.                                 char c = ca[i];
  408.                                 if (i == 0 || Char.IsSeparator(ca[i  1]))
  409.                                 {
  410.                                         c = Char.ToUpper(c);
  411.                                 }
  412.                                 sb.Append(c);
  413.                         }
  414.  
  415.                         return sb.ToString();
  416.                 }
  417.                 /// <summary>
  418.                 /// Convert string from pascal case to human readable string
  419.                 /// <example>pascalCaseExample => Pascal Case Example</example>
  420.                 /// </summary>
  421.                 /// <param name=”s”>The string</param>
  422.                 /// <returns>human readable string</returns>
  423.                 public static string ToHumanFromPascal(string s)
  424.                 {
  425.                         StringBuilder sb = new StringBuilder();
  426.                         char[] ca = s.ToCharArray();
  427.                         sb.Append(ca[0]);
  428.                         for (int i = 1; i < ca.Length  1; i++)
  429.                         {
  430.                                 char c = ca[i];
  431.                                 if (Char.IsUpper(c) && (Char.IsLower(ca[i + 1]) || Char.IsLower(ca[i  1])))
  432.                                 {
  433.                                         sb.Append(” “);
  434.                                 }
  435.                                 sb.Append(c);
  436.                         }
  437.                         sb.Append(ca[ca.Length  1]);
  438.  
  439.                         return sb.ToString();
  440.                 }
  441.  
  442.                 #endregion //Case conversions
  443.                 //Alternatively see http://weblogs.asp.net/sushilasb/archive/2006/08/03/How-to-extract-numbers-from-string.aspx
  444.                 public static string GetStartingNumericFromString(string itmName)
  445.                 {
  446.                         string safeNumericString = “”;
  447.                         foreach (char s in itmName)
  448.                         {
  449.                                 if (s.CompareTo(‘0’) < 0 || s.CompareTo(‘9’) > 0)
  450.                                 {
  451.                                         break;
  452.                                 }
  453.                                 safeNumericString += s.ToString();
  454.                         }
  455.                         return safeNumericString;
  456.                 }
  457.  
  458.                 /// <summary>
  459.                 /// method for removing all whitespace from a given string
  460.                 /// </summary>
  461.                 /// <param name=”str”>string to strip</param>
  462.                 /// <returns></returns>
  463.                 public static string RemoveAllWhitespace(string str)
  464.                 {
  465.                         Regex reg = new Regex(@”s*”);
  466.                         str = reg.Replace(str, “”);
  467.                         return str;
  468.                 }
  469.  
  470.                 /*From http://bytes.com/topic/c-sharp/answers/253519-using-regex-create-sqls-like-like-function
  471.                  * Ex:
  472. *
  473. * bool isMatch =
  474. * IsSqlLikeMatch(“abcdef”, “[az]_%[^qz]ef”);
  475. *
  476. * should return true.
  477. */
  478.                 /// <summary>
  479.                 /// Note that it could be very serious performance hit, if the pattern is started with %.
  480.                 /// </summary>
  481.                 /// <param name=”input”></param>
  482.                 /// <param name=”pattern”></param>
  483.                 /// <returns></returns>
  484.                 public static bool IsSqlLikeMatch(this string input, string pattern)
  485.                 {
  486.                         /* Turn “off” all regular expression related syntax in
  487.                         * the pattern string. */
  488.                         pattern = Regex.Escape(pattern);
  489.  
  490.                         /* Replace the SQL LIKE wildcard metacharacters with the
  491.                         * equivalent regular expression metacharacters. */
  492.                         pattern = pattern.Replace(“%”, “.*?”).Replace(“_”, “.”);
  493.  
  494.                         /* The previous call to Regex.Escape actually turned off
  495.                         * too many metacharacters, i.e. those which are recognized by
  496.                         * both the regular expression engine and the SQL LIKE
  497.                         * statement ([…] and [^…]). Those metacharacters have
  498.                         * to be manually unescaped here. */
  499.                         pattern = pattern.Replace(@”[“, “[“).Replace(@”]”, “]”).Replace(@”^”, “^”);
  500.  
  501.                         return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase |RegexOptions.Singleline);
  502.                 }
  503.  
  504.         /// <summary>
  505.         /// Determines whether [contains] [the specified source] with string comparison.
  506.         /// </summary>
  507.         /// <param name=”source”>The source.</param>
  508.         /// <param name=”toCheck”>To check.</param>
  509.         /// <param name=”comp”>The comp.</param>
  510.         /// <returns>
  511.         ///   <c>true</c> if [contains] [the specified source]; otherwise, <c>false</c>.
  512.         /// </returns>
  513.         public static bool Contains(this string source, string toCheck, StringComparison comp)
  514.         {
  515.             return source.IndexOf(toCheck, comp) >= 0;
  516.         }
  517.  
  518.  
  519.                 #endregion //”String Functions”
  520.  
  521.                 #region “String Array Functions”
  522.                 public static string[] ToLower(string[] sArray)
  523.                 {
  524.                         for (int i = 0; i < sArray.Length; i++)
  525.                         {
  526.                                 sArray[i] = sArray[i].ToLower();
  527.                         }
  528.                         return sArray;
  529.                 }
  530.                 //see also a few methods in http://www.codeproject.com/csharp/StringBuilder_vs_String.asp
  531.                 public static string Join(string separator, params string[] list)
  532.                 {
  533.                         return String.Join(separator, list);
  534.                 }
  535.                 #endregion //”String Array Functions”
  536.  
  537.  
  538.                 #region “String Brackets Functions”
  539.                 //             
  540.                 /// <summary>
  541.                 /// ‘StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).
  542.                 ///             ‘If yes, than removes sStart and sEnd.
  543.                 ///             ‘Otherwise returns full string unchanges
  544.                 ///             ‘See also MidBetween
  545.                 /// </summary>
  546.                 /// <param name=”str”></param>
  547.                 /// <param name=”sStart”></param>
  548.                 /// <param name=”sEnd”></param>
  549.                 /// <returns></returns>
  550.                 public static string StripBrackets(string str, string sStart, string sEnd)
  551.                 {
  552.                         if (CheckBrackets(str, sStart, sEnd))
  553.                         {
  554.                                 str = str.Substring(sStart.Length, (str.Length  sStart.Length) sEnd.Length);
  555.                         }
  556.                         return str;
  557.                 }
  558.                 public static bool CheckBrackets(string str, string sStart, string sEnd)
  559.                 {
  560.                         bool flag1 = false;
  561.                         if ((str != null) && (str.StartsWith(sStart) && str.EndsWith(sEnd)))//19/5/ null handling
  562.                         {
  563.                                 flag1 = true;
  564.                         }
  565.                         return flag1;
  566.                 }
  567.  
  568.                 public static string WrapBrackets(string str, string sStartBracket, string sEndBracket)
  569.                 {
  570.                         StringBuilder builder1 = new StringBuilder(sStartBracket);
  571.                         builder1.Append(str);
  572.                         builder1.Append(sEndBracket);
  573.                         return builder1.ToString();
  574.                 }
  575.                 //    ‘Concatenates a specified separator String between each element of a specified String array wrapping each element, yielding a single concatenated string
  576.                 public static string JoinWrapBrackets(string[] aStr, string sDelimeter, string sStartBracket,string sEndBracket)
  577.                 {
  578.                         StringBuilder builder1 = new StringBuilder();
  579.                         string[] textArray1 = aStr;
  580.                         for (int num1 = 0; num1 < textArray1.Length; num1++)
  581.                         {
  582.                                 string text2 = textArray1[num1];
  583.                                 builder1.Append(WrapBrackets(text2, sStartBracket, sEndBracket));
  584.                                 builder1.Append(sDelimeter);
  585.                         }
  586.                         return TrimEnd(builder1.ToString(), sDelimeter);
  587.                 }
  588.                 /// <summary>
  589.                 ///
  590.                 /// </summary>
  591.                 /// <param name=”thisString”></param>
  592.                 /// <param name=”openTag”></param>
  593.                 /// <param name=”closeTag”></param>
  594.                 /// <param name=”transform”></param>
  595.                 /// <returns></returns>
  596.                 /// <example>
  597.                 ///     // mask <AccountNumber>XXXXX4488</AccountNumber>
  598.                 ///requestAsString  = requestAsString.ReplaceBetweenTags(“<AccountNumber>”, “</AccountNumber>”, CreditCard.MaskedCardNumber);
  599.                 ///mask cvv
  600.                 ///requestAsString = requestAsString.ReplaceBetweenTags(“<FieldName>CC::VerificationCode</FieldName><FieldValue>”, “</FieldValue>”, cvv=>”XXX”);
  601.                 /// </example>
  602.                 public static string ReplaceBetweenTags(this string thisString, string openTag, stringcloseTag, Func<string, string> transform)
  603.                 {
  604.                         //See also http://stackoverflow.com/questions/1359412/c-sharp-remove-text-in-between-delimiters-in-a-string-regex
  605.                         string sRet = thisString;
  606.                         string between = thisString.MidBetween(openTag, closeTag, true);
  607.                         if (!String.IsNullOrEmpty(between))
  608.                                 sRet=thisString.Replace(openTag + between + closeTag, openTag +transform(between) + closeTag);
  609.                         return sRet;
  610.                 }
  611.                 public static string ReplaceBetweenTags(this string thisString, string openTag, stringcloseTag, string newValue)
  612.                 {
  613.                         //See also http://stackoverflow.com/questions/1359412/c-sharp-remove-text-in-between-delimiters-in-a-string-regex
  614.                         string sRet = thisString;
  615.                         string between = thisString.MidBetween(openTag, closeTag, true);
  616.                         if (!String.IsNullOrEmpty(between))
  617.                                 sRet = thisString.Replace(openTag + between + closeTag, openTag + newValue +closeTag);
  618.                         return sRet;
  619.                 }
  620.  
  621.                 //              ‘ Quote the arguments, in case they have a space in them.
  622.                 public static string QuotePath(string sPath)
  623.                 {
  624.                         return ( + sPath + );
  625.                 }
  626.                 public static string DblQuoted(string sWord)
  627.                 {
  628.                         sWord = Strings.Replace(sWord, , , 1, 1, CompareMethod.Binary);
  629.                         return ( + sWord + );
  630.                 }
  631.                 #endregion //”String Brackets Functions”
  632.  
  633.                 /// <summary>
  634.                 /// Returns true, if  string contains any of substring from the list (case insensitive)
  635.                 /// See similar (with SqlLikeMatch support) in ResponseMessagePatternsCache
  636.                 /// </summary>
  637.                 /// <returns></returns>
  638.                 public static bool IsStringContainsAnyFromList(this string stringToSearch,List<String>stringsToFind)
  639.                 {
  640.                         //TODO: create overloads with exact match  or case sencitive
  641.                         if (stringsToFind.IsNullOrEmpty())
  642.                         { return false; }
  643.                         else
  644.                         {
  645.                                 stringToSearch = stringToSearch.ToUpper();
  646.                                 return stringsToFind.Any(pattern =>stringToSearch.Contains(pattern.ToUpper()));
  647.                         }
  648.                 }
  649.         }
  650. }

v