"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)

Scheduled Tasks tool should validate username/password combination

Schedule Tasks in Windows  required to specify username and password. However it doesn't verify that the combination is correct.

Scheduled Tasks tool should have an option to verify username/password combination and this validation should be forced when user saved(clicked OK) the task.

I've noticed the issue on Windows 2003 server. Not sure, is it implemented on newer windows versions.

Do not check-in DEBUG specific code.

We are using .Net Remoting to interact beteeen client and back end server. I needed to call a method from services class.
For debugging purposes I decided to create the class directly. It was easier to debug without starting extra back-end process.
The code was like the following:

IMyServices services = (IMyServices)RemotingHelper.GetObject(typeof(IMyServices));
#if DEBUG
    services = new MyServices();
#endif
// Process the task
services.ProcessItems(ItemsCollection); 

During the development I checked that the method done the required processing and changed the parameter object as expected.

And I've checked in the code, assuming that in Release mode the application will work the same way just by instantiating proxy instead of full object.
However in Release mode changes in parameter inside calling method were not returned back.
Of course, If parameter is serializable, it is passed by value. and correct implementation will use return value

 ItemsCollection = services.ProcessItems(ItemsCollection);

But more general recommendation before check-in remove/comment-out any DEBUG specific shortcuts and test the code  as it will be in production.



Call eventTimer_Elapsed method asyncronoulsy OnStart of Windows Service

We have   eventTimer in Windows Service  (similar as described in  Timer Objects in Windows Services with C#.NET 
and Using Timers in a Windows Service) to run the  relatively long-running process repeatedly.
 
NOTE: It is NOT a good idea to Use a Windows Service just to run a scheduled process, but I have to maintain a legacy application, that was written as a Windows Service .
 
The process called each time when eventTimer_Elapsed. But I want to run it immediately(not to wait until timer will elapsed)  when service started or Continued.
However I wanted to call it asynchronously from OnStart method, because otherwise Start command seems to hang until process is finished.
Thanks to asyncronous calls for delegates, I 've created a function to invoke eventTimer_Elapsed from any place asyncronously and my service has the following methods:
 
private void BeginInvokeElapsedEvent(object sender, ElapsedEventArgs e)
{// Initialize the first update asynchronously
ElapsedEventHandler dlgt = eventTimer_Elapsed;

dlgt.BeginInvoke(sender,e);

}
protected override void OnContinue() 
{
 this.eventTimer.Start();
BeginInvokeElapsedEvent(this,null);// MyLongProcess();
base.OnContinue ();

}

protected override void OnStart(string[] args)
{

Initialise();

// Initialize the first update asynchronously// MyLongProcess();
BeginInvokeElapsedEvent(this,null);

}

private void eventTimer_Elapsed(object sender, ElapsedEventArgs e)
{

MyLongProcess();

}

Related links:Comparing the Timer Classes in the .NET Framework Class Library

LINQ to XML -How to use XPass for elements selection

I am just starting to work with LINQ to XML and tried to find child document similar to the following:
 xml.Element("client/child");
But it throw exception
System.Xml.XmlException: The '/' character, hexadecimal value 0x2F, cannot be included in a name.
The reason is that LINQ to XML doesn't directly support XPAth
Fortunately there are extensions, that allow to use XPath for XElement search/selection.

using System.Xml.XPath;

and then

var clients = xml.XPathSelectElements ( "client/child" );

Consider, if required ,an XPathSelectElements overload  with namespace management.

Note, that XPath extensions are actually backward compatibility feature, and Microsoft recommends to use native XElement methods, such as Descendants ,Elements,Element etc.  See Comparison of XPath and LINQ to XML
 However K. Scott Allen  prefers to mix LINQ and XPath  to have concise code.

See also Concepts LINQ to XML for XPath Users

Useful tip:where clause and "Possible System.NullReferenceException"

«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345