Sunday 20 December 2009

Date Parsing In C#

DateTime.Parse("Dec 13 18:06");//Results in {06.12.2009 13:18:00}
Why?!

Thursday 3 December 2009

Virtual Desktop Manager For Windows

I got too accustomed to multiple desktops on my home Ubuntu computer, that working under Windows with many open programs without ability to share them among several desktops made me too uncomfortable. VirtuaWin - The Virtual Desktop Manager was the solution :). Now I am happy again.

Sunday 15 November 2009

Add List To App.Config

One can add list and not only a list to App.Config file of the .Net project. That can be done by declaring your own configuration element, say a ProductElement

class ProductElement : ConfigurationElement
{
  [ConfigurationProperty("name", IsKey=true, IsRequired=true)]
  public string Name
  {
    get { return this["name"]; }
  }

  [ConfigurationProperty("price")]
  public int Price
  {
    get { return Convert.ToInt32(this["price"]); }
  }
}

class ProductElementCollection : ConfigurationElementCollection
{
  protected override ConfigurationElement CreateNewElement()
  {
    return new ProductElement();
  }

  protected override object GetElementKey(ConfigurationElement element)
  {
    return ((ProductElement)element).Name;
  }
}

class ProductConfigurationSection : ConfigurationSection
{
   [ConfigurationProperty("products")]
   public ProductElementCollection Products
   {
      get { return (ProductElementCollection)this["products"]; }
   }
}

Use it in your app.config like that:

<configuration>
   <configSections>
      <section name="productConfigurationSection"
        type="MyNamespace.ProductConfigurationSection, MyAssembly" 
        requirePermission="false" />
   </configSections>
   <productConfigurationSection>
      <products>
         <add name="car" price="750000" />
         <add name="milk" price="13" />
      </products>
   </productConfigurationSection>
</configuration>

Note that Name is used as a key, so you cannot create 2 Products with the same name. But you can add more fields to the Product, just mark them accordingly. And from code you can access this section with:

ProductConfigurationSection section = (ProductConfigurationSection) ConfigurationManager.GetSection("productConfigurationSection");

Tuesday 20 October 2009

The Most Intelligent Java IDE — Now Free and Open Source

Hardly anyone will argue, that IntelliJ IDEA is one of the best IDE for Java and Ruby(Rails). And now it is going to be free! Yes, this title is taken from IntelliJ Site. Next version of the product will be free, and it can already be downloaded from the coerced link.

Wednesday 16 September 2009

Convert Different Audio In Command Line in Ubuntu

Converting different audio formats in Ubuntu is quite an easy task. Just start Soundconverter, or first install it, if you don't have.

sudo apt-get install soundconverter

But I needed to do it in command line. Soundconverter can do it either. (What a good boy!) But you just need to know the mime-type of the output file (simply adding the desired suffix doesn't work). For example, to convert "my_favourite mp3" to wav you can use:

soundconverter -b -m audio/x-wav -s .wav my_favourite.mp3

See the full list of mime types.

For the available options see

soundconverter -h

or

man soundconverter

Sunday 2 August 2009

Ruby Shoes

I wanted to try ruby Shoes already long ago, but just didn't know what to start with. Until I found a quiteuseful article about making a game on ruby shoes. I tried it and it was unexpectedly easy. Here are some my subjective thoughts about it.

Good things:

It is very easy to study.
One can begin writing using shoes quite quickly and straightforward. No big manuals or hardly understandable api and howtos.
It is cute. :)
Yes, I really liked it. Different objects are created very easy, such as:
Shoes.app { button("Click me!") { alert("Good job.") } }
You also can draw with provided rect, oval or even arrow methods or import an image as a background. Motion ability is also provided:
Shoes.app do #A star that moves after the mouse pointer.
  @shape = star :points => 5
  motion do |left, top|
    @shape.move left, top
  end
end
Unfortunately there were also some disadvantages:
The whole Shoes application should be in Shoes.app block.
Seem to me to be a little bit uncomfortable.
You have to pass everywhere app variable that denotes the Shoes application.
Well, not just everywhere... But if you create your own class, which objects have to be drawn you also have to pass the application variable, or make it global, which is not really good pattern.
class RedRect

  def initialize( app )
    app.fill red
    app.rect :left => 10, :top => 10, :width => 40 
  end
end

Shoes.app do
  RedRect.new( self )
end
Pity, but it is slow.
The resulting snake in the game responds in about 2 seconds. It is a long period of time, especially on higher levels with higher speed.

In conclusion the authors' words about Shoes are right:"Shoes is a tiny graphics toolkit, designed for beginners". It can be used to create quickly a small application, where speed is not essential.

Friday 31 July 2009

Access DOM Element Within IFrame

Suppose we have a html page with frame or iframe in it and we need to get an element in it. Simple

document.getElementById("myElement");

will not find it, as it is searched only in the main page, where the frame is set. What we should do, is to find the frame first and then look for needed element in the right frame.

frame = document.getElementById("myFrame"); 
frame.contentWindow.getElementById("myElement");

Thursday 9 July 2009

Concatenate Strings On Group By In Sql

Imagine we have the following table.
CREATE TABLE MyTable (id int, name varchar, value int);

INSERT INTO MyTable (id,name,value) VALUES (1, 'Hello', 4);
INSERT INTO MyTable (id,name,value) VALUES (1, 'World', 8);
INSERT INTO MyTable (id,name,value) VALUES (5, 'Great!', 9);
The result we would like to acquire is:
| id |   name_values    |
+----+------------------+
|  1 | Hello:4; World:8 |
|  5 | Great!:9         |
Names and values are concatenated into strings and grouped by id. We need an aggregate function, that concatenates strings for that. Here are some solutions for different sql databases.
MySql
This case is most easy one. Lucky users already have the GROUP_CONCAT(expr) function. This query should give the answer.
SELECT id, GROUP_CONCAT(name + ':' + value SEPARATOR '; ') AS name_values FROM MyTable GROUP BY id;
PostgreSql
The solution here is a bit more difficult, but nevertheless easy enough. We need to create our own aggregate function and use it in our query.
CREATE AGGREGATE aggr_textcat(
  basetype    = text,
  sfunc       = textcat,
  stype       = text,
  initcond    = ''
);

SELECT id, substring(aggr_textcat(', ' || name || ':' || value) from 2) AS name_values FROM MyTable GROUP BY id;
Here we used already existing function to concatenate text fields textcat, but we could write our own.
MsSql
Since version 2005 it became also possible to write your own aggregate function in MsSql, but here I provide another solution using inner select and xml path.
SELECT id, SUBSTRING((SELECT '; ' + name + ':' + CAST(value AS varchar(MAX)) 
FROM MyTable WHERE (id = Results.id) FOR XML PATH ('')),3,9999) AS name_values
FROM MyTable Results
GROUP BY id

Wednesday 24 June 2009

Insert Large Amount Of Rows Into PostgreSQL

Inserting large amount of data into postgres database may take a lot of time, if you use INSERT command. Consider better COPY command, though it is not so flexible.
COPY my_table_name(int_column, string_column, bytea_column) from stdin;
1    THISisSTRING    \\001\\017\\044
2    THISisSTRING2   \\001\\017\\062
3    THISisSTRING3   \\001\\017\\102

The default delimiter is tab (\t).

To acquire the right format in 1 particular case, you can fill database with some values using INSERT command and dump database with pg_dump. The resulting file will contain the right COPY syntax.

Monday 22 June 2009

Ajax With InnerHTML()

InnerHTML is not a standard, but it is more useful comparing to working with DOM with such functions as createElement and/or appendChild. But there is a problem with it: if you need further to handle the new added data (to refer new elements, to change/add their attributes), innerHTML is not good at all, as innerHTML simply visually adds new elements, but it does not really insert them in the DOM structure of the document. Attempting to do a document.getElementById() on a tag inside of code that was added using innerHTML just doesn't work. At least it didn't work for me in Firefox 3.

The folowing code can be accepted as the workaround.

var newDiv = document.createElement("div");//create new div
newDiv.innerHTML = xhr.responseText;//add response into new div
var container = document.getElementById("container");//find place where the response should be placed to
container.parentNode.insertBefore(newDiv, container);//add new div before the container
newDiv.parentNode.removeChild(container);//remove container

This way we get the same resulting document, but we can further work with DOM.

Friday 12 June 2009

Master Degree Acquired

Yes, at last. Now I am the Master of the Information Technology :) Sounds good!

Wednesday 10 June 2009

Microsoft Excel 2007 Problems

It is a must read, if you want to know what problems you may encounter, when exporting to excel 2007: "Microsoft Office XML formats ? Defective by design"

Sunday 7 June 2009

Array To String

Oh, how I hate String.join(string, string[]) in mscorlib. And it is because of string[] argument. Why couldn't they make it accept array of objects and, before joining, cast every object with ToString() method?

Had to make it myself:

public string ListJoin<T>(string separator, T[] objs)//C# v3
{
  return string.Join(separator, Array.ConvertAll(objs, item => item.ToString()));
}

public string ListJoin<T>(string separator, T[] objs)//C# v2
{
  return string.Join(separator, Array.ConvertAll<T,string>(value, new Converter<T,string>(delegate(T i){return i.ToString();})));
}

Thursday 14 May 2009

Export String Values To Excel 2007

If you encounter a following error, while exporting to Excel 2007 (.xlsx)

Errors were detected in file MyFileName.xlsx. Repaired Records: Cell information from /xl/worksheets/sheet1.xml part

then, probably, you are exporting string values in wrong format. The right structure in this case is

<sheetData>
  <row>
   <c>
     <v>99999</v>
   </c>
   <c t="inlineStr">
     <is>
       <t>My Text</t>
     </is>
   </c>
  </row>
</sheetData>

Note, that there is no <v> tag in <c> as it should be with numbers. Instead you have to make an inline string (<is>) tag and put text (<t>) tag with needed text in it. Do not forget to add the t="inlineStr" attribute to <c> tag.

More info can be found developer:network.

Monday 27 April 2009

Method with arbitrary number of parameters in C#

One can also create a method with variable number of parameters in C#. It is needed, for example, when you have such logic, where you need to take value from one place, if it is not null, or from the other, or from the third place, if the first two are nulls, and so on. This can help:

public static T FirstNotNull<T>(params Nullable<T>[] objects) where T : struct
{
  foreach (Nullable<T> obj in objects)
    if (obj.HasValue) return obj.Value;
  return default(T);
}

Reserved word params shows, that we deal with an array of parameters. This parameter can only be the last one in a function. You can put other types of parameters before, but no after.

The function can be called like that:

HelperClass.FirstNotNull<int>(firstValue, secondValue, thirdValue, fourthValue);

The first not null value of these four is returned, or default value of the type, if all are nulls.

Tuesday 31 March 2009

System.Reflection To the Rescue

Many people ask if there is a possibility to call a method, if we have its name as string. Actually, it is very useful feature. Imagine we have an Object with several properties which represent the same thing, but in different languages.

class MyClass
{
    public string State_EN;
    public string State_DE;
    public string State_RU;
}

We want to show the state of MyClass object in proper language. We create a method for that

public string State(string language)
{
}

Language is the 2-letter code representation of language ("EN", "DE", "RU"...). So what should be inside the State method? Solutions with "if" and "switch" are not good - if you have to add more languages, you must rewrite the State method. But we are lazy and don't want to do that. What we need here is System.Reflection.

using System.Reflection;
[...]
public string State(string language)
{
    PropertyInfo property = typeof(MyClass).GetProperty("State_" + language);//find the property
    if (property != null)
        return (string)property.GetValue(this, null);//get value of the property
    return null;
}

The same way we can search for method, if we know the method's name (with GetMethod instead of GetProperty). And call it with "Invoke" and proper parameters.

Wednesday 18 March 2009

Using Generics With System.Nullable<T>

When we have a Nullable type value and we want to assign it to some control, then we need to check if is not null first.

SomeLabel.Text = object.MyProperty.HasValue ? object.MyProperty.Value : String.Empty;

But if we have many nullable properties? I don't want to copy/paste this check on every line. So we need a method, that checks for nulls. But I also don't want several methods for every type. So we need to use generics.

I created some methods for myself

public static string ValueOrEmptyString<T>(Nullable<T> obj) where T : struct
{
  return obj.HasValue ? obj.Value.ToString() : "";
}

public static T ValueOrDefault<T>(Nullable<T> obj, T defaultValue) where T : struct
{
  return obj.HasValue ? obj.Value : defaultValue;
}

public static T ValueOrDefault<T>(Nullable<T> obj) where T : struct
{
  return obj.HasValue ? obj.Value : default(T);
}

"where T : struct" - is needed for compiler to understand that this method is allowed only for types that belong to System.ValueType.

I can use these methods like that

SomeLabel.Text = ValueOrEmptyString<int>( object.MyIntProperty );
SomeDateTimeControl.Date = ValueOrDefault<DateTime>( object.MyDateTimeProperty );
SomeReferenceControl.SelectedObjecId = ValueOrDefault<int>( object.MyIntProperty, -1 );

Wednesday 18 February 2009

How To Split Audio CD Image (.flac) Into Several Tracs In Ubuntu

$ sudo apt-get install cuetools shntool flac #install needed tools
$ cuebreakpoints sample.cue | shnsplit -o flac sample.flac #read breakpoints from cue and give them to splitter
$ cuetag sample.cue split-track*.flac #add tags to newly created files
More info is there.

Friday 13 February 2009

Eee Control Tray For Ubuntu

eee-control-tray is a package that one can install on Ubuntu (or other Debian system) to obtain an easy interface to configure Fn shortcuts and other useful options.