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.
 
Advertisements

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>
        publicstaticbool CopyFleldsFromBaseClass(object from,object to)
        {
            bool rv = false;
            try
            {
                if (from == null)
                {
                    thrownewApplicationException("from is null");
                }
                if (to == null)
                {
                    thrownewApplicationException("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 an 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
Similar Reflection approach to implement ToString is described here

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.