Showing posts with label Useful. Show all posts
Showing posts with label Useful. Show all posts

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

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

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.

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);
        }
    }

Saturday, December 25, 2010

Log Viewer Pro

Many years I’m use the best file manager Total Commander (Windows commander in the past). In the home site was found link to the site http://www.totalcmd.net which include additional plugins and utilities. But I would  present only one very usability utility – Log Viewer Pro.  Current application dedicated to viewing logs and available to using in every text file . Every level of Log may be define in different color, a program is free (for home users) and not required install.

Screenshot:

Main features of viewer:
Fast scrolling, eats low memory.
Supports any file size (4 Gb and larger).
Multitabbed interface.
Auto-reload file, Follow tail mode.
Allows to highlight some lines (e.g. "errors", "warnings").
Allows to view encodings: ANSI, OEM, Unicode LE, Unicode BE etc.
File search (both forward and backward).

Download here.

Size: 650 KB
Author: Alexey Torgashin

Sunday, December 05, 2010

Snippet editor

In my work I'm often use snippets, but by old habit I created every time new snippet manual. Today found nice solutions to my  suffering -  Snippet Editor by BillMcC. Snippet editor ready to work with all version of Visual Studio, support C# and VB snippet, easy interface and big help to programmer.
Link to download.

Tuesday, June 29, 2010

Generate random string

Current code is generate string in defined length and include chars, numbers and symbols.

public static string GetRandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
int[] symbol = new[] { 33, 36, 38, 64, 94 };
int[] digits = new[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 };
int symbolsAmount = size / 3;
int digitAmount = size / 3;
for(int i = 0; i < size; i++)
{

int switcher = random.Next(3);
char ch;
if(switcher == 0 && symbolsAmount > 0)
{
int id = random.Next(symbol.Length);
ch = Convert.ToChar(symbol[id]);
symbolsAmount--;
}
else if(switcher == 1 && digitAmount > 0)
{
int id = random.Next(digits.Length);
ch = Convert.ToChar(digits[id]);
digitAmount--;
}
else
{
bool isLower = random.Next(2) == 0 ? false : true;
ch = Convert.ToChar(
Convert.ToInt32(
Math.Floor(26 * random.NextDouble() + ((isLower) ? 65 : 97))
)
);

}
builder.Append(ch);
}

return builder.ToString();
}

Monday, June 21, 2010

Tuesday, April 27, 2010

VS 2008 SP1 deletes .dbml designer file – a solution

Also me was surprised after installation Visual Studio 2008 SP1. every little change in dbml hierarchy give raise to deleting designer file. Short googling return elegant solution:
In partial class move all using statements after namespace
Linq

Original code:
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;

namespace Test
{
partial class DataClassesDataContext
{
//...
}
}



New Code:

namespace Test
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;

partial class DataClassesDataContext
{
//...
}
}



Right click on the .dbml  file and run “Run Custom Tool”.

Enjoy!

Thursday, February 11, 2010

Twice calling Render in ASP.NET page

I have web page, which use HtmlTextWriter for creating HTML in client. List<T> get data from DB and start in loop to add HTML tags, attributes and more.  I hoped to create page with div’s, images and text, but in the debug phase i saw the Render() method called twice. After long tests and researches was found out what is a problem. In creating image <img>, a attribute “src” get value from DB and in one images “accidently” a value was …null. You can say “so what?” A problem exist not in HTML page, a problem concealing in IIS. If page has attribute <…src=”” …/> or<… src=”#” …> that makes IIS load the page twice. Good luck!


kick it on DotNetKicks.com

Wednesday, June 17, 2009

Debug windows service

In the time, when you work on development a windows service not possible to debug it. A solution is a converting service to console application or creating additional service runner or anymore. I want to present very simple, effective and easy way how to resolve this. In debug mode will run application and in not debug mode will run service.

[RunInstaller(true)]
public partial class ServiceRunner : ServiceBase
{
[STAThread]
static void Main()
{
#if !DEBUG
//Run Windows Service
Run(new ServiceRunner());
#else
//Run Application
new YourServiceBody();
#endif
}
public ServiceRunner()
{
InitializeComponent();

}
protected override void OnStart(string[] args)
{
new YourServiceBody();
}

protected override void OnStop()
{}
}

Good luck!
kick it on DotNetKicks.com

Tuesday, March 18, 2008

Monday, February 18, 2008

Enum Utilities

In this article I will discuss some classes I've written to simplify working with enumerations. The primary thrust of these classes is added functionality, but in some cases there are performance improvements as well.

Click here

Download source

The zip file contains:
EnumDefaultValueAttribute.cs
EnumTransmogrifier.cs
LibEnum.cs
build.bat
csc.rsp
EnumDemo1.cs
EnumDemo2.cs
EnumDump.cs
MonthEnum.cs
PolyglotAttribute.cs
WeekdayEnum.cs

Once you extract the files to a directory you should be able to execute build.bat to compile the demo programs. (They are console applications.)

To use the methods in your own projects, simply add the appropriate files.

Sunday, February 10, 2008

Static Extension Methods

DateTime d = DateTime.Yesterday();
//...
public static DateTime Yesterday<this DateTime>()
{
return DateTime.Today.AddDays(-1);
}
 


Via Mabstrerama

Monday, January 28, 2008

The Chart free generation for Web Application from Google

Google Provided addition tool for Web developers  - The Google Chart API.

You can create a charts in very simple way - build necessary URL and will receive chart in one of 5 types (Line, Bar, Pie, Venn or Scatter).

A simple "pie" for example:

URL = "http://chart.apis.google.com/chart?cht=p3&chco;=4C8ED6&chs;=250x120&chl=Sun|Mon|Tue|Wed|Thu|Fri|Sat&chd;=s:ABCDEFG"

and a result:

 

 

In your control next chart parameters: Data, Type, Colors, Labels, Style, Character mappings and several optional parameters.

To Home Page click HERE

Thursday, January 17, 2008

Example & Tutorial of Rhino Mocks

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to test the behavior of a car during an accident.

 Wikipedia 

To full guide in code examples about Rhino Mocks Click Here

Full guide how to configuring VS 2008 for debugging .NET Framework Source Code

Click here to read a article.