Tuesday, February 26, 2013

C# property names without hardcoded strings


public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Test
{
    protected void InitDropDownList()
    {
        DropDownList ddl = new DropDownList();
        ddl.DataSource = new List<Person> { 
            new Person{ Id = 1, Name = "John Smith" },
            new Person{ Id =  2,Name = "Moshe Perez" } };

        //Old and bad way
        ddl.DataValueField = "Id";
        ddl.DataTextField = "Name";

        //New way
        ddl.DataValueField = GetPropertyName(() => new Person().Id);
        ddl.DataValueField = GetPropertyName(() => new Person().Name);

        ddl.DataBind();
    }

    private static string GetPropertyName<T>
(Expression<Func<T>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}



From here

Wednesday, January 02, 2013

Test value generator

Frequently in the test time required to set random values to variables. The simple class will help you to save a time in the future:

public static class Generator
{
    public static readonly Random RND = new Random();
        
    // Generate IP address
    public static string GetIP(bool isIPv6 = false)
    {
        if (isIPv6)
        {
            return string.Format("{0}.{1}.{2}.{3}.{4}.{5}", RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256));
        }
        return string.Format("{0}.{1}.{2}.{3}", RND.Next(0,256), RND.Next(0,256), RND.Next(0,256), RND.Next(0,256));
    }

    // Generate GPS coordinate
    public static System.Device.Location.GeoCoordinate GetGeo()
    {
        return new System.Device.Location.GeoCoordinate
        {
            Latitude =  GetDouble(90),
            Longitude = GetDouble(90),
        };
    }
    // Generate string
    public static string GetString(int size, int percentOfSymbols = 30, int percentOfDigits = 30)
    {
        StringBuilder builder = new StringBuilder();
        int[] symbol = new[] { 33, 36, 38, 64, 94 };
        int[] digits = new[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 };
        int symbolsAmount =  (int) size * percentOfSymbols /100;
        int digitAmount = (int)size * percentOfDigits / 100;
        for (int i = 0; i < size; i++)
        {
            int switcher = RND.Next(3);
            char ch;
            if (switcher == 0 && symbolsAmount > 0)
            {
                int id = RND.Next(symbol.Length);
                ch = Convert.ToChar(symbol[id]);
                symbolsAmount--;
            }
            else if (switcher == 1 && digitAmount > 0)
            {
                int id = RND.Next(digits.Length);
                ch = Convert.ToChar(digits[id]);
                digitAmount--;
            }
            else
            {
                bool isLower = RND.Next(2) == 0 ? false : true;
                ch = Convert.ToChar(
                        Convert.ToInt32(
                        Math.Floor(26 * RND.NextDouble() + ((isLower) ? 65 : 97))
                            )
                        );

            }
            builder.Append(ch);
        }
        return builder.ToString();
    }
    // Generate Date
    public static DateTime GetDate()
    {
        return DateTime.Now.AddMinutes(  RND.Next(10000000)  * (RND.Next() % 2 == 0 ? -1 : 1));
    }
    //Get double
    public static double GetDouble(int limit = default(int))
    {
        return double.Parse(string.Format("{0}.{1}", limit == default(int) ? RND.Next() : RND.Next(90), RND.Next())) *  (RND.Next() % 2 == 0 ? -1 : 1);
    }
}

kick it on DotNetKicks.com

Sunday, December 23, 2012

Password in SQL


DECLARE @PWD varbinary(128)
SELECT @PWD = PWDENCRYPT ( 'password' )
SELECT @PWD
-- Correct
SELECT PWDCOMPARE('password', @Pwd )  -- 1
-- Failed
SELECT PWDCOMPARE('bla-bla-bla', @Pwd )  -- 0

Tuesday, December 18, 2012

Srink DB log file

USE dbname;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE dbname
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (2, 1);  -- here 2 is the file ID for trasaction log file,you can also mention the log file name (dbname_log)
GO
-- Reset the database recovery model.
ALTER DATABASE dbname
SET RECOVERY FULL;
GO

Sunday, October 28, 2012

Validation is a boxing value is default

I very like my lovely extension IsDefault but unpossible to use it where a value is boxing. A cool feature of C#  default(...)  cannot help because a argument required Type. After long research was created small solution:

static bool IsDefault(object o)
{
    if (o == null)
    {
        return true;
    }
    //Check is type os object is ValueType
    if (o.GetType().IsValueType)
    {
        return Activator.CreateInstance(o.GetType()).Equals(o);
    }
    //ReferenceType
    return false;
}


Also can be implemented as extension.

Thursday, October 18, 2012

An error occurred creating the configuration section handler for system.serviceModel/behaviors: Extension element 'XXX' cannot be added to this element. Verify that the extension is registered in the extension collection at system.serviceModel/extensions/behaviorExtensions.

A web.config of project include next rows:
...
<extensions>
    <behaviorExtensions>
        <add name="ELEMENT" type="YYY.ZZZ,YYY.XXX, Version=1.0.0.0,Culture=neutral, PublicKeyToken=null" />
    </behaviorExtensions>
</extensions>
...
<behavior name="BehaviorName">
          ELEMENT />
</behavior>

In the start project WCF is throwing exception and message:
"An error occurred creating the configuration section handler for system.serviceModel/behaviors: Extension element 'ELEMENT' cannot be added to this element. Verify that the extension is registered in the extension collection at system.serviceModel/extensions/behaviorExtensions."

A problem exists in file AssemblyInfo of YYY.XXX and not in config.
YYY.XXX change build number in every compilation but WCF is require a full name of assembly (AssemblyQualifiedName) and exact assembly file version number.

Open AssemblyInfo and see last 2 rows:
[assembly: AssemblyVersion(...)]
[assembly: AssemblyFileVersion(...)]

If a code looks like this:
[assembly: AssemblyVersion(5.0.1.0)]
[assembly: AssemblyFileVersion(5.0.1.0)]

You not reading current article but if acode looks like this:

[assembly: AssemblyVersion(5.0.1.0)]
[assembly: AssemblyFileVersion(5.0.1.*)]

This is a time to change it and resolve a problem. Enjoy.



Sunday, August 12, 2012

Disable the Browser Back Button

 if (window.history) {  
 window.history.forward(1);  
 }  
A script tested in IE 9, Chrome and FireFox.


From here