Friday, May 15, 2009
Tuesday, January 27, 2009
Nice - Boo 0.9 is here!
mano akį patraukę dalykai:
- Pattern matching [BOO-1106] - simple but powerful object pattern matching with the match/case/otherwise macros
- Support for generic extension methods [BOO-937] - LINQ style extension methods
Wednesday, December 17, 2008
throwing exceptions should not be done ad-hoc
System.Drawing.Image.FromFile("file.mp3")
Notice that i deliberately pass a non-image file to this function. Do you expect you will get InvalidImageFormatException? I would expect that, but as Microsoft documentation says it will return OutOfMemoryException.
Since when out of memory has something to do with image format? That's a rhetoric question of course, since .Net2 is many years on the production already :)
Monday, December 15, 2008
Reading XmlNode.AppendChild Method documentation
If I have the following code, what would be its result?
XmlNode parentNode = new XmlNode(...);
XmlNode childNode = new XmlNode(...);
parentNode.AppendChild(childNode);
parentNode.AppendChild(childNode);
Console.WriteLine(parentNode.Childs.Count)
By reading the code i would tell that we would get two children. But by reading the documentation you can find that it will be one. Take a careful look at the following sentence in official Microsoft documentation.
If the newChild is already in the tree, it is removed from its original position and added to its target position.
How the in the world I can understand from the method name "AppendChild" that it not only appends, but removes and then appends?
So yes, naming your functions correctly is very important for clean code.
Wednesday, December 10, 2008
Asynchroniaus data fetching with NHibernate
How does ISessionFactoryHolder react to multiple threads? Does it generate one session factory holder or one for each thread?
Looking at ThreadScopeInfo.cs:26 we see this code
[ThreadStatic] static Stack stack;
This clearly tells that we have a new stack of of session scopes for each thread.
Googling around i've came to this post. It suggested to just register your own thread-safe implementation of IThreadScopeInfo.
While I think that is OK and might solve the problem, but why reinvent, whenc Castle.ActiveRecord already provides the following implementations of IThreadScopeInfo:
- AbstractThreadScopeInfo - this is used as an abstract implementation, not useful
- HybridWebThreadScopeInfo - the docs say: This is used for scenarios where most of the you need per request scope, but you also does some work outside a request (in a thread pool thread, for instnace).
- ThreadScopeAccessor - This is just an accessor, and does not provide single scope for all threads
- ThreadScopeInfo - this is the default implementation, which has static instances per-thread
- WebThreadScopeInfo - this implements a Session Per Request pattern pattern, So not useful
So, no helpful implementation, so will do the same as suggested here. But, really, i hate copy-paste things, that's pure evil
Tuesday, November 25, 2008
Isolator for Sharepoint : Unit testing for sharepoint made easier
And here's the adverticement:
Typemock are offering their new product for unit testing SharePoint called Isolator For SharePoint, for a special introduction price. it is the only tool that allows you to unit test SharePoint without a SharePoint server. To learn more click here.
The first 50 bloggers who blog this text in their blog and tell us about it, will get a Full Isolator license, Free. for rules and info click here.
Thursday, June 19, 2008
Eagerly load two or more collections
this link has exactly what i needed for.
As a proof of concept I wrote this unit test to check that collections are loaded eagerly. Domain model is a client has a collection of prders. An Order has a collection of bills
Client client = null;
using (new NHibernateSession())
{
ISession session = NHibernateSession.GetISession(typeof(Client));
client = session.CreateCriteria(typeof(Client))
.SetFetchMode("Orders", FetchMode.Join)
.UniqueResult();
session.CreateCriteria(typeof(Client))
.CreateCriteria("Orders")
.SetFetchMode("Bills", FetchMode.Join)
.List();
}
// Assert that orders and order.Bills are eagerly laoded
foreach (RisingStar.BLL.Model.Order order in client.Orders)
{
order.Bills.Count.ToString()
}
Wednesday, May 7, 2008
Dynamic assembly generation
Microsoft has confirmed it is a bug
I encountered this bug while trying to compile boo code with boo compiler
[Test, ExpectedExceptionAttribute(typeof(NotSupportedException))]
public void GetExportedTypes_NotSuportedInDynamicAssembly()
{
string assemblyText = @"
class Foo:
x as int
";
BooAssemblyCompiler compiler = new BooAssemblyCompiler("test", assemblyText);
Type[] types = compiler.CompilerContext.GeneratedAssembly.GetExportedTypes();
}
BooAssemblyCompiler is just a helper class, which inside just does these steps
// creates a boo compiler
m_compiler = new BooCompiler();
// adds a CompileToMemory step to the compiler pipeline
m_compiler.Parameters.Pipeline = new Boo.Lang.Compiler.Pipelines.CompileToMemory();
// defines that an output should be a library
m_compiler.Parameters.OutputType = CompilerOutputType.Library;
// finally, compiles boo text
StringInput input = new StringInput(assemblyName, booText);
m_compiler.Parameters.Input.Add(input);
m_compilerContext = m_compiler.Run();
Thursday, April 10, 2008
How to to effective error handling using Exceptions
I've never actually grasped enough how to work with Exceptions. It was a mystery for me when to throw them and when to catch them. Lately, i have done some improvisation with the code, and I got some new ideas.
As far as I know there are two main approaches to error handling.
- One is c/c++ style, where error codes are returned with return codes and optionally passing aditional info in other parameters
- Second approach is to throw and catch Exceptions
To begin working with exceptions effectively one must first decide which way to go. Exceptions and error codes can not go together, as this will make the code spaghetti like, and people will get confused. Important thing is to remember is that code is for people, not for machines
My preference is to go Exceptions way, for these reasons:
- Exceptions allow you indicate an error in any place, and error handling can occur in any other place
- Using error codes forces every function to also return an error code, which is very intrusive. Error handling should not force you to change your existing or new code in any way.
- Exceptions can be catched on a very high granularity (having that there is a proper exception hierarchy). One can catch internal errors in service layer, and UI related exceptions in UI layer
- Exceptions can be used to carry a very brief error message, and, what is even more important, information how to solve the problem
- Exceptions can even be catched, stuffed with more detailed exception text (for example context-specific information) and rethrown again
Saturday, December 22, 2007
Microsoft and ACL permission changes
Microsoft recommends that you only use ACCESS_ALLOWED_ACE because Microsoft does not extensively test ACCESS_DENIED_ACE.
This is from an official Microsoft support page - http://support.microsoft.com/kb/326902/
Friday, December 21, 2007
Quartz.Net composite keys
Clustering and load balancing is what we really need, and do not want to invest my precious time doing same bicycle again.
So far so good, until you come to database, and notice that all Quartz.Net database structure has taken a somewhat strange way to define primary and foreign keys.
Let us have an example :
CREATE TABLE QRTZ_JOB_DETAILS (
JOB_NAME VARCHAR(60) NOT NULL,
JOB_GROUP VARCHAR(60) NOT NULL,
DESCRIPTION VARCHAR(120),
JOB_CLASS_NAME VARCHAR(128) NOT NULL,
IS_DURABLE VARCHAR(1) NOT NULL,
IS_VOLATILE VARCHAR(1) NOT NULL,
IS_STATEFUL VARCHAR(1) NOT NULL,
REQUESTS_RECOVERY VARCHAR(1) NOT NULL,
JOB_DATA BLOB,
CONSTRAINT PK_QRTZ_JOB_DETAILS PRIMARY KEY (JOB_NAME,JOB_GROUP)
);
Everythin is sping'n'span except two columns "JOB_NAME" and JOB_GROUP, which apparently describe an ID of JobDetail. And it goes for all tables like this where JobDetail, Trigger (which is the main concept of whole scheduler), and listeners.
Why do I care about it? Because it makes more difficult to use such database in our project:
- Having a composite primary key (name and group) makes mapping of tables to POCO more compliated
- Primary key is not auto-generated by database, but rather controlled by client-side, which puts more responsibility on it.
- More responsibility means more code. More code means more stuff look after and more time spent on maintaining it
- Primary keys should NOT have any business meaning attached to it. Now properties Name and Group definetely carry meaning
- Say, you have a group of triggers. That group contains 1000 triggers. If business situation changes, and new business rules require you to immediately pause 100 of those triggers, what you have to do is to change group name for those triggers. Now if you change the group of a trigger, you will get unexpected behaviour, since your foreign keys will become incosistent. One example would be TriggerListeners not referencing those 100 triggers
- A name of a jobDetail should be it's name, and not a primary key. It's like saying that Darius is an ID of my person. Who knows, maybe I will change my name in some distant future
That's the first impression that pops in my mind when I see such database structure. (Yes, impression change in the long run, especially if someone gives very strong arguments of why I should do so)
Tuesday, December 18, 2007
Monday, December 17, 2007
Generic collection and argument matching
FilterResults(List < object> objects, IList < IFilterRule> filters)
{
...
}
IList < ConcreteRule> filters = new List < ConcreteRule>();
FilterResults(..., filters);
Is it possible to pass IList
Wednesday, December 5, 2007
Gues what does it mean?
Failures:
1) SourceGrid.Tests.TestRangeData.WriteData_FromSourceGridToSourceGrid :
expected: <1>
but was: <1>
at SourceGrid.Tests.TestRangeData.WriteData_FromSourceGridToSourceGrid() in e:\Projects\csharpexamples\SourceGrid\trunk\SourceGrid4\SourceGrid.Tests\TestRangeData.cs:line 122
p.s.
And yes, it is not the case when one one is string, another one is int
Monday, December 3, 2007
TDD anti patterns
Here is a link to presentation, and link to code, illustrating those anti patterns.
Monday, November 26, 2007
ETL
I was reading many of Ayende Rahien posts about ETL, but never understood what's is that ETL about. Now I know it:
Extract, Transform, and Load (ETL) is a process in data warehousing that involves
* extracting data from outside sources,
* transforming it to fit business needs (which can include quality levels), and ultimately
* loading it into the end target, i.e. the data warehouse.
Basically what ETL stands is a process of getting oen source of information into destination. This might be an integration of two systems, say a CMS system and a Payment system, or that might be just importing data from spreadsheet into your database.
We have started doing our own implementation of import/export tool a month ago. I don't think this is a waste. The insight we gained from creating our own solution is very valuable, and now we have a choice of either stick with our solution, or use Rhino.ETL . Before that we had no choice, and that's bad
Rhino.ETL can be found here
A vision of enterprise platform Hot & Distributed Deployment
Ayende now has a month of a vision of enterprise systems I think it's really cool what he writes.
Please read it: A vision of enterprise platform Hot & Distributed Deployment
Sunday, November 11, 2007
Scheduling solutions
Scheduling solutions @ Ayende Rahien
He puts his opinion about four solutions:
* Castle.Components.Scheduling
* Quartz.NET
* Rhino Scheduling
* Task Manager
Tuesday, October 9, 2007
How to build a document plugin system
Which way do you prefer to specify documents:
Example number 1:
[DocumentRepository]
public class DocumentRepository
{
[Documents]
public void RegisterSheets()
{
m_documents.Add(typeof(Client[]), "ClientBook.odt", "Books/second level book", "Client book", "Print client book");
m_documents.Add(typeof(Contact), "ClientSheet.odt", "Sheets", "Contact sheet", "Print contact sheet");
}
}
Or number two:
[DocumentAttribute(typeof(Client[]), "ClientBook.odt", "Books/second level book")]
public class PrintClientBookClone2 : BasePrintingCommand
{
public PrintClientBookClone2() : base("Client book", "Print client book")
{
}
protected override void Invoke(object sender, EventArgs e)
{
WindowOpener.Default.OpenDocument(new DLC.Core.UI.Documents.GenericBookDocument(this, DataRoot));
}
}
[DocumentAttribute(typeof(Contact), "ClientSheet.odt", "Sheets")]
public class PrintContactSheetClone2 : BasePrintingCommand
{
public PrintContactSheetClone2()
: base("Client sheet", "print client sheet")
{
}
protected override void Invoke(object sender, EventArgs e)
{
WindowOpener.Default.OpenDocument(new GenericDocumentForm(this, DataRoot));
}
}
Both examples achieve the same functionality: two print buttons are created. One is placed under menu "Books/second level book/Client book", the other under "Sheets/Client sheet". Slash here denotes that the menu is composed of some sub-menus.
So which do you choose?
I choose both cases, since the first one is extremely short, and allows you to add documents very quickly. However, the other, while being cumbersome and ugly, allows you to achieve maximum flexibility in case you need it. And we know bussiness people need it alot.
Thursday, October 4, 2007
Microsoft to release source code of part of .Net libraries
We'll begin by offering the source code (with source file comments included) for the .NET Base Class Libraries (System, System.IO, System.Collections, System.Configuration, System.Threading, System.Net, System.Security, System.Runtime, System.Text, etc), ASP.NET (System.Web), Windows Forms (System.Windows.Forms), ADO.NET (System.Data), XML (System.Xml), and WPF (System.Windows). We'll then be adding more libraries in the months ahead (including WCF, Workflow, and LINQ).
You can deep-scan slashdot and google for the details. I just want to state my opinion about this:
First, it is not an open source license at all. You can SEE the source, but you can not do anything with it. It's just for your eyes, studying, debugging, etc.
If there were programmers who did not get what are the differences between open source and free software, now can see it that here is a big coneyed meaning difference. In essence, open source and free software are 99 percent the same.
However, when people talk about free software, they tend to think that this is about
the cost of the program, which is not true. Free software is about freedom.
When business men talk about open source, they often convey deliberately or mistakenly that open source is all about source code, that is, if you see source code, then it is open source. That is SO untrue. Open source is also about freedom. You not only see source code, but also can modify it, ehance it, fix bugs and release the code to the world.
Sorry folks, but .Net libraries are not open source. But i still hope they sometimes will be.
Second, you can not copy-paste code from .Net libraries to your projects, since .Net source is not released under open source, or free software license.
Third, it still a good thing
Fourth, I strongly believe that Mono will soon reach such a level, that we could move away from .Net platfrom and go into Mono platform. Why to do this? Simple - I see bussiness value in it. And the value comes primarily from the ability to choose. With Mono, our customers will get more options as where to run their software. Should they choose Linux or Windows, it will run on both machines.
Fifth, open source profoundly increases both productivity and research in IT industry. Personally, I can not see myself programming with libraries, where I can not see the code, and all of our libraries except .Net framework are open source.