Sunday, May 25, 2025

Top Snippets & Add-Ons for C# Developers

 

📝 CommentsPlus

Purpose: Enhances the readability of your code comments by applying styles based on specific prefixes.

Features:

  • Italicizes standard comments.

  • Applies bold, color, or strikethrough styles to comments starting with special markers like //!, //?, //x, etc.

Download: CommentsPlus on Visual Studio Marketplace


🔍 C# Methods Code Snippets

Purpose: Provides a collection of reusable code snippets for common C# method patterns, enhancing coding efficiency.

Features:

  • Snippets for typical, virtual, static, and extension methods.

  • Quick insertion using shortcuts like method, vmethod, smethod, and xmethod.

Download: C# Snippets on Visual Studio Marketplace


🌈 Rainbow Braces

Purpose: Improves code readability by colorizing matching brace pairs, making it easier to identify code blocks.

Features:

  • Applies distinct colors to matching brackets, parentheses, and braces.

  • Supports both light and dark themes.

Download: Rainbow Braces on Visual Studio Marketplace


🎨 Solution Colors

Purpose: Helps differentiate between multiple open solutions by assigning unique colors to each.

  • Assigns custom colors to solutions or folders.

  • Displays colors in various parts of the Visual Studio interface for easy identification.

Download: Solution Colors on Visual Studio Marketplace


🧠 Visual Studio Spell Checker

Purpose: Ensures the accuracy of your code by checking the spelling in comments, strings, and plain text.

Features:

  • Real-time spell checking as you type.

  • Supports multiple languages and customizable dictionaries.

  • Can check entire solutions, projects, or selected items.

Download: Visual Studio Spell Checker on Visual Studio

Integrating these extensions into your Visual Studio setup can significantly enhance your coding efficiency and maintainability. Whether you're aiming for cleaner code, faster development, or better organization, these tools have got you covered. Happy coding! 🎉

Monday, February 13, 2017

Ending the Great Debate on Enum Flags

This article explains how enumeration and flags work in C#.NET and how to properly use them.

Wednesday, June 03, 2015

How do i create an InstallShield LE project to install a windows service?

The main solution exist  here
But real help is hiding in the comment:
This option does not start the service after installation. To install service and start it, in solution explorer, select 3. Configure Target System > Services 
Regards to Rajeev

Thursday, November 06, 2014

Visual Studio 2012 Crashes at Startup

The solution for famous problem exists here. But my Registry not included all required keys from the article. In the 3rd page of Google  search was found very small but very effective advice:
You would get above error if ieproxy.dll is not registered properly. Re register Ieproxy.dll.
C:\Program Files\Internet Explorer>regsvr32 /u ieproxy.dll
C:\Program Files\Internet Explorer>regsvr32 ieproxy.dll
C:\Program Files (x86)\Internet Explorer>regsvr32 /u ieproxy.dll
C:\Program Files (x86)\Internet Explorer>regsvr32 ieproxy.dll
Full post exists here.
Thank you, Derek Smith!

Thursday, October 02, 2014

Web.config and config file for every project in solution

Suppose a given project solution: core, data access layer and several "plugin" modules. In order to prevent changes in the core all configurations was moved to web.config. Also we would like that every module will use a dedicated config file because a "plugin" can be added and/or removed.

First solution:
In web.config file in the section "appSettings" available attribute "file" for moving segment of web config to another file. It's nice but we need more then one config file and therefore required additional configurations.Create "sectionGroup":

  1. <configuration>
  2.   <configSections>
  3.     <sectionGroup name="Plugins">
  4.         <section name="Module1" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  5.         <section name="Module2" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  6.     </sectionGroup>
  7.   </configSections>
  8. .....


Module1 and Module2 this is a names of our plugins. Create configuration section for group and define key for path of module config file in every named section:


  1.   <Plugins>
  2.     <Module1>
  3.       <add key="ConfigFile" value="App1.config"/>
  4.     </Module1>
  5.     <Module2>
  6.       <add key="ConfigFile" value="App2.config"/>
  7.     </Module2>
  8.   </Plugins>
  9.   

Create 2 new config files "App1.config" and "App2.config". In the properties of files change  "Copy to Output Directory" to "Copy always". The content of module config file look like this one:
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.   <appSettings>
  4.     <add key="AnyKey" value="Bla-Bla-Bla"/>
  5.     <add key="AnyKey2" value="Bla-Bla-Bla"/>
  6.   </appSettings>
  7. </configuration>

An using code:

  1. class Test
  2. {
  3.     private static readonly Configuration config = ConfigurationManager.OpenMappedExeConfiguration(
  4.         //Get config file
  5.         new ExeConfigurationFileMap()
  6.         {                                                                              //Web.config part   //File name                                         
  7.             ExeConfigFilename = ((NameValueCollection)ConfigurationManager.GetSection("Plugins/Module1"))["ConfigFile"]
  8.         },
  9.         ConfigurationUserLevel.None);
  10.  
  11.     private void Foo()
  12.     {
  13.         var value = config.AppSettings.Settings["AnyKey"].Value;
  14.         Console.WriteLine(value);
  15.     }
  16. }


Second solution:
Add  new section "Plugin". We are use the type DictionarySectionHandler in order to get values as Dictionary:
  1. <configuration>
  2.   <configSections>
  3.     <section name="Plugin" type="System.Configuration.DictionarySectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  4. </configSections>

Add values:

  1. <Plugin>
  2.     <add key="ConfigFileOfModule1" value="App1.config"/>
  3.     <add key="ConfigFileOfModule2" value="App2.config"/>
  4. </Plugin>

Create 2 new config files "App1.config" and "App2.config". In the properties of files change  "Copy to Output Directory" to "Copy always". The content of module config file look like this one:
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.   <appSettings>
  4.     <add key="AnyKey" value="Bla-Bla-Bla"/>
  5.     <add key="AnyKey2" value="Bla-Bla-Bla"/>
  6.   </appSettings>
  7. </configuration>

An using code:

  1. private static readonly IDictionary section = (IDictionary)ConfigurationManager.GetSection("Plugin");
  2. private static readonly  System.Configuration.Configuration config =
  3.     ConfigurationManager.OpenMappedExeConfiguration(
  4.                         new ExeConfigurationFileMap()
  5.                         {
  6.                             ExeConfigFilename = section["ConfigFileOfModule1"].ToString()
  7.                         }, ConfigurationUserLevel.None);
  8. private void Foo()
  9. {
  10.     var value = config.AppSettings.Settings["AnyKey"].Value;
  11. }



Enjoy!





Tuesday, September 16, 2014

How to include value types AND strings in generic constraint.

I'm very like to use generics in the code. Usually generic implementation is working smoothly but exists one small problem with generic value types: cannot use string typed value because System.String is a class.

  1. Foo<string>("abc");



  1. private void Foo(T value) where T : struct
  2. {
  3. //...
  4. }
 
The simple solution is creating overwrite method:

  1. private void Foo(T value) where T : string
  2. {
  3. //...
  4. }

Nice, but not perfect. The beautiful idea was offered by KeithS instead to restrict a value to struct change it to IConvertible. Next types implemented an interface IConvertible but now String can be included in the constraint:
Boolean   
Byte   
Char   
DateTime
Decimal   
Double   
Int16   
Int32   
Int64   
SByte   
Single   
String   
Type   
UInt16   
UInt32   
UInt64 


Final:

  1. private void Foo(T value) where T : IConvertible
  2. {
  3. //...
  4. }



Tuesday, August 26, 2014

C# generation: from '?' via '??' to '???'

C# include several usable but not famous operators. Today we'll consider the generation of  operator '?'.
The first and known from language C old operator '?' was appeared in C# 1.0 in the Visual Studio 2002. An operator using for condition instead to block  if-else:
  1. Random rnd = new Random();
  2. //Long way
  3. bool isLessTo50;
  4. if (rnd.Next(100) < 50)
  5. {
  6.    isLessTo50 = true;
  7. }
  8. else
  9. {
  10.    isLessTo50 = false;
  11. }
  12.  
  13. //Short way
  14. bool isLessTo50 = rnd.Next(100) < 50 ? true : false;

The next '??' was offered 3 years later in Visual Studio 2005. The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand:
  1. DateTime? dt = GetDate();
  2. //Regular way
  3. if (dt != null)
  4. {
  5.    return dt;
  6. }
  7. else
  8. {
  9.    return DateTime.Now;
  10. }

  11. //Short way
  12. return (dt != null) ? dt : DateTime.Now;

  13. //New way
  14. return dt ?? DateTime.Now;

The last operator '???' was announced in Visual Studio 2012. I'm very like it because he is cutting the validation of object:
  1. class Person
  2. {
  3.  public string Name { get; set; }
  4.  public int ID { get; set; }
  5. }
  6.  
  7. //The program
  8.  Person person = InitPerson();

  9. //Old way
  10. if (person != null)
  11. {
  12.   return person.ID;
  13. }
  14. else
  15. {
  16.   return default(int);
  17. }
  18.  
  19. //New way
  20. return person.ID ??? default(int);

In Visual Studio 2014 the operator '?..' did not receive renewal but maybe in next versions we'll see '????'  and even '?????' :-).

Tuesday, October 15, 2013

Repair IE8 (IE7) and IE9

Unbelievable! After 2 days of research in Microsoft's sites why IE doesn't work the solution was found in non-Microsoft site.
Thank you very much Mr Kai Schätzl!

Link to article

Monday, September 30, 2013

How to blink text in all browsers

Javascript:
<script type="text/javascript" language="javascript">
 window.onload=blinkOn;
 
function blinkOn()
{ document.getElementById("blink").style.color="Red";
  setTimeout("blinkOff()",1000);
}
 
function blinkOff()
{  document.getElementById("blink").style.color="";
  setTimeout("blinkOn()",1000);
} 
</script>


HTML
<div id="blink">Hello, World!</div>

Thanks to Steven McConnon

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

Shrink 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

Sunday, August 05, 2012

Culture in .NET. All in one

By inspiration from article Hidden Gems inside .Net Classes I created static class that include short methods for quick retrieval object or properties of Cultures and Time Zones. All data based on build-in functionality of Framework 4.0


 public static class Culture
    {
        #region Consts
        private static readonly StringDictionary cultureDetails;
        private static readonly ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones(); 
        #endregion
        
        /// <summary>
        /// Ctor
        /// </summary>
        static  Culture()
        {
            #region Init culture datails
            cultureDetails = new StringDictionary();
            foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
            {
                RegionInfo regionInfo = new RegionInfo(cultureInfo.Name);

                if (!cultureDetails.ContainsKey(regionInfo.EnglishName))
                {
                    cultureDetails.Add(regionInfo.EnglishName, regionInfo.Name);
                }
            } 
            #endregion
        }
        /// <summary>
        /// Get culture name by Country
        /// </summary>
        /// <param name="countryName"></param>
        /// <returns></returns>
        public static string GetCulture(string countryName)
        {
            return cultureDetails.ContainsKey(countryName) ? cultureDetails[countryName] : string.Empty;
        }
        /// <summary>
        /// Get Culture info by culture name
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static CultureInfo GetCultureInfo(string cultureName)
        {
            return CultureInfo.GetCultures(CultureTypes.SpecificCultures).FirstOrDefault(item => item.Name == cultureName);
        }
        /// <summary>
        /// Get month names by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static string[] GetMonths(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? null : region.DateTimeFormat.MonthNames;
        }
        /// <summary>
        /// Get day names by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static string[] GetDays(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? null : region.DateTimeFormat.DayNames;
        }
        /// <summary>
        /// Get first day of week by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static DayOfWeek GetFirstDayOfWeek(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? default(DayOfWeek) : region.DateTimeFormat.FirstDayOfWeek;
        }
        /// <summary>
        /// Get datetime format by culture
        /// </summary>
        /// <param name="cultureName"></param>
        /// <returns></returns>
        public static string GetDateTimeFormat(string cultureName)
        {
            var region = GetCultureInfo(cultureName);
            return region == null ? string.Empty : region.DateTimeFormat.FullDateTimePattern;
        }
        /// <summary>
        /// Get TimeZone info by DisplayName
        /// </summary>
        /// <param name="displayName"></param>
        /// <returns></returns>
        public static TimeZoneInfo GetTimeZoneByDisplayName(string name)
        {
           return timeZones.FirstOrDefault(item => item.DisplayName == name);
        }
        /// <summary>
        /// Get TimeZone info by Standart Name
        /// </summary>
        /// <param name="displayName"></param>
        /// <returns></returns>
        public static TimeZoneInfo GetTimeZoneByStandartName(string name)
        {
            return timeZones.FirstOrDefault(item => item.StandardName == name);
        }
    }