SQL's "like" patterns to compare in .Net

I wanted to use   SQL's "like" patterns to compare in .Net.
I found the good C# implementation of  function in thread Using Regex to create a SQL's "like" like function.
The function  IsSqlLikeMatch works fine, but I've noticed that the search is case-sensitive.
It's also doesn't match % if there are multiple lines.
But it was easy to change by modifying IsMatch call to

return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

Comment in JavaScript code doesn't comment the server command

 Comment in JS code doesn't comment the server command. It is correct, but can be visually confusing. I had the following line in markup ASCX file. 

// var trs = document.getElementById('<%=pnlOutsideSearch.ClientID %>').getElementsByTagName('TR');

Visual Studio showed it as green comment.
However when server control pnlOutsideSearch was renamed, the errors were generated, and it took me some time to realize, what wrong with the line, tha it was look like just comment.
 

Refer to Activity from workflow in the same project.

I have a project with a few workflows. I  created a custom activity and I've added it to the same project.
But then I found that I am not able to insert/drag it to my workflow.
The only solution, that I found, was to create a separate Activity Library, move my custom activity to the library, and add a reference to the library from Workflow Project. 
It looks like that you unable to Refer to Activity from workflow in the same project.


 

Command prompt utility to copy files for specified time range

 I've tried to find an utility that will allow to copy files from big folder for specified time range.
 The  discussion in experts-exchange suggested to use RoboCopy
 
Robocopy FolderFrom FolderTo /MINAGE:20091125 /MAXAGE:20091124
 
Note that for 1 day selection  MINAGE should be one day BIGGER than required date.
 
 
I still wish to find utility that will allow to specify time, rather than full date.
The same discussion has batch file example, that possibly can be used to filter time as well.


 

"The project type is not supported by this installation" for Workflow project

Download from ActivityExecutionContext in Workflows
caused  "The project type is not supported by this installation" when opened the solution.
On my machine I have Workflow only for VS 2008, but not for VS 2005, but the download solution was in 2005 format.
I've explicitely started VS 2008 and then converted solution from 2005 to 2008. Error disappeared. 
Similar problem with Moral: If you are trying to develop with .NET 3.0 maybe it’s a good idea to check that .NET 3.0 is installed first... described here.

Using of Workflow Dependency properties.

In our Workflow application it was created a lot of  Workflow level Dependency properties that was used  to interchange data between different activities.
    Workflow.PropertyA=  Activity1.PropertyA
    Activity2.PropertyA=Workflow.PropertyA
We believed that is a safe way to avoid concurrency problems. But it was WRONG.
 
Article ActivityExecutionContext in Workflows explains, that Workflow properties as a shared data between activities is not a safe method and can cause concurrency errors in case of CAG or similar usage.
Best solution is to use custom activities Dependency properties and direct binding between activities.
Activity2.PropertyA=  Activity1.PropertyA
 
The primary advantage to dependency properties is that they allow binding of property values to instance data at runtime. For example, you can bind the input property of one activity to an output property of another. The actual property values resulting from the binding is determined at runtime. Dependency properties are required when you want to bind properties from one activity to another. However, if you are binding an activity property to a workflow property, the workflow property is not required to be a dependency property. In this case, a normal C# property on the workflow class works fine.
Performance Characteristics of Windows Workflow Foundation tells to avoid using dependency properties if not necessary:
A dependency property is a powerful mechanism that helps you expose activity properties so they can be bound and shared within a workflow instance. There is a small performance overhead associated with this property type, especially when many dependency properties are being accessed from the workflow, but in most cases the overhead should be minimal.
 
Related links: DependencyProperty Class
           wdp snippet

LongestCommonPrefix function for 2 strings

The function that finds  Common Prefix for 2 strings
//converted from http://stackoverflow.com/questions/1250514/find-length-of-initial-segment-matching-mask-on-arrays
             public static string LongestCommonPrefix(string str1, string str2)
             {  
                 int minLen = Math.Min(str1.Length, str2.Length);
                 for (int i = 0; i < minLen; i++) 
                 {
                     if (str1[i] != str2[i])
                     { 
                         return str1.Substring( 0, i);     
                     }
                 }
                 return str1.Substring( 0, minLen);
             }

ASP.NET Validators should be visible to do validation

Validators are disabled, if they are not visible. They can be not visible, if any of their containers is not visible.
In general, they should be always visible, but the message will be shown only if they will be NOT valid.
Also consider to set BaseValidator.SetFocusOnError=true.
In big pages use ValidationGroup combined with CausesValidation property set to true.

Declare local variable within the loop instead of using loop variable in Linq methods

I've noticed in my LINQ code Resharper Warning "'Access to modified closure'". The search pointed that there is very confusing potential error.
If  for/foreach loop variable is used only in Linq methods (more general, only as a parameter for delegates) , only the last value of the variable will be used for all calls.
It always required to create local variable inside loop and use the local variable instead of loop variable.
 

Implement Copy constructor using Serialization or Reflecton

and was adviced by Tim Hibbard to use reflection like this.
I've created Copy method to copy Fields(not only properties, and found that  the private fields of any base class are not copied.
The article Where are my fields? « Andrew Smith explains that it's required to iterate base classes.
But when looking in the Google for the solution,I've found the suggestion for serializable objects:
 
MemberInfo[] sm = FormatterServices.GetSerializableMembers(typeof(From));
 object[] data = FormatterServices.GetObjectData(from, sm);
 FormatterServices.PopulateObjectMembers(to, sm, data);

 

It seems to solve my requirement better than the reflection approach:


        /// <summary>
        /// Inspired by http://geekswithblogs.net/thibbard/archive/2007/05/04/Architecture-thoughts-and-Reflection.aspx
        /// </summary>
        /// <param name="from"></param>
        /// <param name="from"></param>
        /// <returns></returns>
        public static bool CopyFleldsFromBaseClass(object from,object to)
        {
            bool rv = false;
            try
            {
                if (from == null)
                {
                    throw new ApplicationException("from is null");
                }
                if (to == null)
                {
                    throw new ApplicationException("to is null");
                }
                //http://agsmith.wordpress.com/2007/12/13/where-are-my-fields/
                System.Type typeFrom = from.GetType();
                System.Type typeTo = from.GetType();
                BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ;
                //Debug.Assert(typeTo is typeFrom);
                //iterate through each property of this
                foreach (FieldInfo prop in typeFrom.GetFields(bindingFlags))
                {
                    //get the name of the current property
                    string memberName = prop.Name;
                    //make sure this property is writeable and the obj property is readable
                    //if (prop.CanRead && to.GetType().GetFields(memberName).CanWrite)
                    if (typeTo.GetField(memberName, bindingFlags) != null)
                    {
                        //Get the value of this current property from obj
                        object objValue = typeFrom.GetField(memberName, bindingFlags).GetValue(from);
                        //Set the value of this property from obj
                        prop.SetValue(to, objValue);
                    }
                }
                //if we are here, everything worked
                rv = true;
            }
            catch (Exception exc)
            {
                Debug.Assert(false,exc.ToString());
 
                //something bad happened, return false
                rv = false;
            }
            return rv;
        }
 
By the way, my original idea was to create a derived class, when I have on object of base class. 
Later I understood that it's better to create the derived object using factory at the start, 
rather than create the base class and then convert it to derived one. 
Related link on Rick Strahl's Blog    Simplistic Object Copying in .NET 

Text from SQL Management Studio reformatted by Google Docs when using IE.

When I am using Google Docs, quite often I am copying the portion of code  from Visual Studio or SQL Management Studio.
but the text is reformatted to become messy.
E.G.
 ALTER PROCEDURE [dbo].[CheckNotProcessed]
    @limit int = 10
AS

declare @StartDate datetime
declare @EndDate  datetime
declare @NotProcessedCount int
is shown as

ALTER

 

PROCEDURE [dbo].[CheckNotProcessed]

@limit

int = 10

AS

declare

 

@StartDate datetime

declare

 

@EndDate datetime

declare

 

@NotProcessedCount int 

 
I've tried to manually insert in HTML view <PRE></PRE> tags and then paste text between tags.
But  in "Edit Html" under IE7  I am not able to "Update" - it causes JavaScript  "Invalid Argument" error.

In Firefox I can paste the plain text.
Unfortunately, it doesn't have syntax colours, that I would like to preserve from SQL Management Studio.

Custom alert on the SQL Database

 I wanted to create a custom alert on the SQL Database when number of records with some values(considered as invalid) exceeds the expected limit. 

First of all you need to Set up Database Mail for SQL 2005 and follow procedure
IMPORTANT: don't forget to Restart SQL Agent to activate settings. 

Similar to the article Define custom error messages in SQL Server 2005
I've defined the error
EXEC sp_addmessage 60001, 1, N'Number of not-processed  tasks %d exceed the limit on %s.'
and SP:
 
ALTER PROCEDURE [dbo].[CheckNotProcessed]
	@limit int = 10
AS

declare @StartDate datetime
declare @EndDate  datetime
declare @NotProcessedCount int
set @EndDate  =GetDate()
set @StartDate =DATEADD (day ,-1, @EndDate) print @StartDate print @EndDate select @NotProcessedCount=count(*) from dbo.[MyTBL] where [ProcessState] <> 99999 and createdDate between @StartDate and @EndDate if( @NotProcessedCount>@limit) begin declare @CurrentDBName varchar(60) set @CurrentDBName=DB_NAME() RAISERROR (60001, 10,1,@NotProcessedCount, @CurrentDBName) WITH LOG END /* -- ============================================= -- Example to execute the stored procedure -- ============================================= EXECUTE DBO.CheckNotProcessed 10 */

Note that if you have more than one similar database on the same server, it's important to specify  DB_NAME()
 
I've also created Job to call the SP on a regular basis.
Then I've created an alert using an error number (Enterprise Manager)

I fould that this approach is very powerful and allow to send monitor regular business pricesses, as well as get notifications about some  data conditions, that required investigation/debugging.

MSbuild Task FileUpdate to replace content in text files

I wanted to replace some strings in files using my deployment MSbuild script.

I've noticed that MSBuild Community Tasks Project has RegexReplace task.

But when I've looked in documentation 

(By the way, it will be good if Reference help will be available online, not only from download)

I've realized that the task is applicable for strings(e.g file names) not to content within a file.

Almost accidently in one of the posts i've found a reference to FileUpdate
task, that support Regex and does content replacements within a file.

The following examle (from downloaded help) search for a version number and update the revision.

 
            <FileUpdate Files="version.txt"
                Regex="(\d+)\.(\d+)\.(\d+)\.(\d+)"
                ReplacementText="$1.$2.$3.123" />

Note: don't forget to insert in to your project

<

MSBuildCommunityTasksPath >.</MSBuildCommunityTasksPath>
<
Import Project="MSBuild.Community.Tasks.Targets" />
You may require to change MSBuildCommunityTasksPath if it is not in current directory.

MSDN documentation -methods that have corresponding operators shouldn't be called directly

In our old code I'vew noticed a few examples of code like the following:
 MyFortune = Decimal.Add(MyFortune, .01m);
I was wandered, why they didn't use "+" sign, and didn't find any explanation.
The MSDN reference documentation doesn't explain, that methods like Add, Subtract,Multiply,Divide usually should not be called explicitely. 
Instead of using Add method it's simpler to use + sign ( Addition Operator ).
E.g.
    MyFortune = Decimal.Add(MyFortune, .01m);
can be rewritten as 
    MyFortune += .01m;

Comment like this should be added to all methods, that have corresponding operators.

I've posted a suggestion to MS Feedback


DNN ability to 'Publish Web Site'

3 years ago I've posted a workaround regarding DNN
BUG App_GlobalResources and 'Publish Web Site' in VS2005 
 
The issue is still not resolved and I recently received an email

I would like to thank you a lot for your post on a DNN forum which explain how to use DNN in precompiled mode.

( AppGlobalRessources...... )

T H A N K S !!!!!!!!!!

 I am glad that the workaround is still useful, but DNN team should create a new version(even with breaking changes)

«February»
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
28123456
78910111213