Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Parse string having comma separated integers August 1, 2011

Filed under: .NET Framework,C# — ppetrov @ 8:01 pm
Tags: ,

I’ve read a blog post about splitting a string containing comma separated integers and then creating an array. It’s a very short and simple code but there’s a little problem – it uses the Split() method and the result is an array, potentially big array. What if you only need the first 10 results out of ten thousand integers ? You will do the work to split ten thousand integers and you will consume a lot memory then you need and finally you will create a lot of garbage. I’ve written a class to solve this issues.

public class IntConverter
{
private readonly char _separator;

public IntConverter()
: this(',')
{
}

public IntConverter(char separator)
{
_separator = separator;
}

public IEnumerable<int> From(string input)
{
if (input == null) throw new ArgumentNullException("input");

return FromImplementation(input.Trim(), _separator);
}

public string To(IEnumerable<int> numbers)
{
if (numbers == null) throw new ArgumentNullException("numbers");

var buffer = new StringBuilder();

foreach (var n in numbers)
{
if (buffer.Length > 0)
{
buffer.Append(_separator);
}
buffer.Append(n.ToString());
}

return buffer.ToString();
}

private IEnumerable<int> FromImplementation(string input, char separator)
{
if (input == string.Empty)
{
yield break;
}

var buffer = new StringBuilder();

var symbols = input.ToCharArray();
for (var i = 0; i < symbols.Length; i++)
{
var symbol = symbols[i];
var isSeparator = (symbol == separator);
if (isSeparator)
{
yield return int.Parse(buffer.ToString());
buffer.Length = 0;
}
else
{
buffer.Append(symbol);
}
}

yield return int.Parse(buffer.ToString());
}
}

I wish there will be an overload of int.Parse or int.TryParse witch accepts StringBuilder as input to reduce even more the memory usage in this scenario.

 

Free Typemock licenses – ASP.NET bundle launch May 19, 2009

Today I’ve read this Get Free Typemock licenses – ASP.NET bundle launch on the official Typemock blog. I thought to myself : Is it possible for me to win a FREE license ? Why not. After all it’s Typemock and it’s an official blog post.  I hope I’ll be in the group of these 60 lucky bloggers. I need to hurry :)

Unit Testing ASP.NET? ASP.NET unit testing has never been this easy.

Typemock is launching a new product for ASP.NET developers – the ASP.NET Bundle – and for the launch will be giving out FREE licenses to bloggers and their readers.

The ASP.NET Bundle is the ultimate ASP.NET unit testing solution, and offers both Typemock Isolator, a unit test tool and Ivonna, the Isolator add-on for ASP.NET unit testing, for a bargain price.

Typemock Isolator is a leading .NET unit testing tool (C# and VB.NET) for many ‘hard to test’ technologies such as SharePoint, ASP.NET, MVC, WCF, WPF, Silverlight and more. Note that for unit testing Silverlight there is an open source Isolator add-on called SilverUnit.

The first 60 bloggers who will blog this text in their blog and tell us about it, will get a Free Isolator ASP.NET Bundle license (Typemock Isolator + Ivonna). If you post this in an ASP.NET dedicated blog, you’ll get a license automatically (even if more than 60 submit) during the first week of this announcement.

Also 8 bloggers will get an additional 2 licenses (each) to give away to their readers / friends.

Go ahead, click the following link for more information on how to get your free license.

 

Stop posting images of the code, post the code ! April 14, 2009

Filed under: General notes — ppetrov @ 10:08 am
Tags: ,
Windows Vista Source Code

Windows Vista Source Code

First there is no Copy/Paste so the reader can’t easily copy the code to try it and/or test it.

Second there is no search available on the page.

Third for a search engines it’s impossible to mine the data represented by the image. You won’t have a match event if the user keywords perfectly match your (image)contents.

 

ForEach method on IEnumerable January 22, 2009

Filed under: .NET Framework,C#,Extension methods — ppetrov @ 5:37 pm
Tags: , ,

I’ve noticed that when I use IEnumerable<T> very often I have a construction like this

.ToList().ForEach(x=> ...)

in my code. I’ve thinked about it and I’ve realized that ToList() will create (probably) a large list just to iterrate over it and perform some action. That’s just because IEnumerable<T> doesn’t have ForEach method. Using an extension method I’m able to fill this gap. So here’s the ForEach method on IEnumerable<T> :

public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
{
    foreach (var v in values)
    {
        action(v);
    }
}

It’s possible to return the values reference to allow method chaining  but personally I think the foreach must be the last thing to perform, otherwise it will lead you to a bad practice. Let me explain what I mean. Imagine we have this Person class and a method that returns all Persons.

public static IEnumerable<Person> GetAllPersons()
{
    // ...
    yield break;
}
public class Person
{
    public long Fortune { get; private set; }

    public void SlowMethod()
    {
        Thread.Sleep(1000);
        // ...
    }
}

Take a look a the fowling two methods that retrieves all rich persons

var richPersonsSlow = GetAllPersons().ForEach(p => p.SlowMethod()).Where(p => p.Fortune > 1000000);
var richPersonsFast = GetAllPersons().Where(p => p.Fortune > 1000000).ForEach(p => p.SlowMethod());

Take this scenario : we have 3600 persons and only one have more then one million.

The first line will take an hour to return the millionaire.

The second line will take only one second to return the millionaire because p.SlowMethod will be called only on the millionaire.

There’s a little semantic difference in the example but I think you get the point. Using the ForEach returning void eliminates this possible issue.

I hope the BCL Team will include this method (not necessarly my implementation) in C# 4.0 .

 

SCOPE_IDENTITY() vs @@IDENTITY – 1:0 September 19, 2008

Filed under: Note to self,SQL — ppetrov @ 4:55 pm
Tags: , ,

@@IDENTITY returns the most recently created identity for your current connection, not necessarily the identity for the recently added row in a table. Always use SCOPE_IDENTITY() to return the identity of the recently added row.

 

Usuful methods – 11 of N – Copy/Move Directory September 12, 2008

Today I have to copy an entire directory including all files, sub directories and all sub files to another directory. The .NET framework doesn’t provide such method (at least I don’t know of it) so I have coded one myself. Here’s the implementation of the CopyDirectory method.

        public static void CopyDirectory(string source, string destination)
        {
            if (destination[destination.Length - 1] != Path.DirectorySeparatorChar)
            {
                destination += Path.DirectorySeparatorChar;
            }
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
            var entries = Directory.GetFileSystemEntries(source);
            foreach (var e in entries)
            {
                if (Directory.Exists(e))
                {
                    CopyDirectory(e, destination + Path.GetFileName(e));
                }
                else
                {
                    File.Copy(e, destination + Path.GetFileName(e), true);
                }
            }
        }

MoveDirectory is very simple when we have CopyDirectory. I know it’s not as fast as it can be ( if we use File.Move()) but still it gets the job done.

        public static void MoveDirectory(string source, string destination)
        {
            CopyDirectory(source, destination);
            Directory.Delete(source);
        }
 

SQL Server 2008 – FILESTREAM feature is disabled. August 15, 2008

Filed under: Uncategorized — ppetrov @ 4:21 pm

Yesterday I have installed SQL Server 2008. I have downloaded the product samples from codeplex and I have tried to restore the Adventure Works 2008 Sample Database but I’ve this error :

System.Data.SqlClient.SqlError: FILESTREAM feature is disabled. (Microsoft.SqlServer.Smo)

OK the FILESTREAM is disabled but the question is how can I enable it ? The solution is very simple but it took me some time to find in on google. Here’s the link to the SQL Server 2008 Books Online on MSDN – How to: Enable FILESTREAM

Just fire SQL Server 2008 Management Studio and type

EXEC sp_configure filestream_access_level, 2
RECONFIGURE

I don’t know why Microsoft doesn’t provided this link as help. Instead of this they suggested m

ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: FILESTREAM feature is disabled. (Microsoft.SqlServer.Smo)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.0.1600.22+((SQL_PreRelease).080709-1414+)&LinkId=20476

which is useless.

The final result is that I have FILESTREAM enabled and I have my AdventureWorks 2008 database restored.

Now I can continue with my tests.

 

 
Follow

Get every new post delivered to your Inbox.