January 19, 2010 Errors, SQL 20 comments
January 19, 2010 Errors, SQL 20 comments
I was editing some script in SQL Server Management Studio.
And then suddenly this error appeared:
My script looked like one below:
–insert statements
—failure on one of inserts because of not existing column
SET IDENTITY_INSERT [TABLE_NAME] ON
The script failed on one of the inserts, because of a missing column.
I added a column to fix the problem but then I started getting this error: IDENTITY_INSERT is already ON for table [Table_Name].
I tried to run inserts independently but error persisted.
IDENTITY_INSERT works in scope of one session. If you read corresponding MSDN page it says: “At any time, only one table in a session can have the IDENTITY_INSERT property set to ON.”
You just need another session. I simply reconnected to the same database and it run without any issues.
Of course I changed the script to set IDENTITY_INSERT to OFF in the end.
January 17, 2010 Ruby 7 comments
Of course not. There is a lot of interesting stuff in Ruby. But at least I tried that quick list here:
http://www.ruby-lang.org/en/documentation/quickstart/
To print something you just need to write puts keyword.
You could calculate online:
Lets define method to calculate price of one of the Dell notebooks here in Ukraine if price is in Dollars, but you want to know how much it is in Hryvnas.
Lets use it:
But Ruby is object-orient language. So here is my Exchanger class and I want to initialize it with exchanging rate:
@rate is field of that class. Don’t you see that syntax very sweet? I see.
Next, we will create instance of our class with a bit lower rate. And use that instance of class:
“In Ruby, you can open a class up again and modify it. The changes will be present in any new objects you create and even available in existing objects of that class. “
That is amazing as per me, because you could just write code after you have declaration of your class and change intent of it.
You need to try play with Ruby, that is very sweet language!
January 17, 2010 Design Patterns, Java 10 comments
Imagine that you are developing some gaming software. Your write Web client and on each of response you are parsing entire XML to get your game Units. You have some set of types of Units, for example 50 different animals, but when you parse your XML you can get dozens of instances of the same Unit and few dozens of instances of other Unit.
If User of the game is very passionate gamer, he could send requests very frequently. In this case your application will be creating dozens of instances for each of the Unit. But, your units have some static descriptions. For example, Dragon has Attack, initial Health level, and also you need to keep image of the dragon in the object of Dragon.
This all lead to intensive and not efficient memory usage. How could you share common information for all types of Units without creating instances for each individual Unit?
1) Simplest way with creating objects each time.
We have base class Unit:
And two derived – Dog and Dragon. To make those objects more weightfull I added to them picture. In my case that is only very long string.
And our parser executes code which looks like:
We want to create only 150 Dragons and 600 Dogs and this takes 28 Mb of memory.
2) How does FlyWeight work?
Lets introduce UnitsFactory. Responsibility of this factory is to manage creation of the concrete flyweight objects (Dogs and Dragons). It verifies if the object has been already created and in this case it just returns created and if not it creates new one and returns it. See:
Lets take a look on UML diagram of our code:
UnitsFactory corresponds to FlyweightFactory, Unit – for Flyweight. Dog, Dragon corresponds to concrete Flyweights in the GoF FlyWeithgt naming.
Now we will do change to our parser to use Factory and will see how much of memory will it take.
But now we are going to create 1500 Dragons and 60000 Dogs, probably your gamer is quite more quick as you think.
And this takes only about 5 Mb of memory:
What have I learned regarding to of Java?
I know that corresponding to C# Dictionary is Map in Java, and there are few concrete maps like on this good picture:
Hope this was a good story!
Go to: My Design Patterns Table
January 17, 2010 Success No comments
Among my goals for this year is to become well-known employee in my company. To accomplish this I’m preparing different presentations and looking for some opportunities once they will appear.
On Thursday I provided presentation for my team workers on Domain-Driven Design.
As per me presentation went well, and I much improved my skills doing presentations. I know this at least because we have surveys to evaluate how the presentation went. And rates there were much higher than last time I did presentation on IoC.
I want to list few things that are flying in my mind after that presentation. They are also some tips to how provide effective presentation. (This is not full list, just associated with this presentation.)
DO
DO NOT
REMEMBER
January 16, 2010 Design Patterns, Java 2 comments
Imagine that you need to develop application for shipping Orders. Your Orders could be in few states: New Order, Registered, Granted, Shipped, Invoiced, Cancelled.
And there are some rules which allow your Order to migrate to another state. This means that for example you cannot ship not registered Order.
Also there are some behavioral rules. For example you cannot add new Product to your Order when it is in Cancelled state. Also behavioral rules could mean changes in state.
How could you accomplish this requirements easily?
We could encapsulate behavior which belongs to current object’s state into separate classes derived from some parent class. Each of the concrete will be responsible for allowing changing state from one to another.
State Pattern UML
How does it work?
At first our Order class has a reference to its _state, to have more real example Order also has _products.
private OrderState _state;
private List<Product> _products = new ArrayList<Product>();
public void setOrderState(OrderState state){
_state = state;
}
Order delegates some state-specific requests to the current state.
– If the current state is Granted, it changes Order‘s state to Shipped and if needed do some surrounded work or delegates it.
This code represents concrete implementation of the OrderState. Constructor of base class has Order parameter, so this allows us have reference to holding Order: _order in derived classes.
public Granted(Order holdingOrder) {
super(holdingOrder);
}
public void ship(){
_order.doShipping();
//next line changes Order’s state
_order.setOrderState(new Shipped(_order));
}
If you are care what method ship() is doing in Order class it could be like shipping :).
– If current state is Registered, most likely that class has no implementation of method ship(), it has only addProduct(), grant(), and cancel(). So method of super class will be called. OrderState has all bulk of methods but they all throw exceptions, which says that changing state in current situation is not allowed.
protected Order _order;
public OrderState(Order holdingOrder){
_order = holdingOrder;
}
public void ship(){
raiseNotAllowableOperation(“ship”);
}
//other methods like register(), grant(), etc… here..
//they look like the ship() looks
private void raiseNotAllowableOperation(String operation) throws IllegalStateException {
String stateName = this.getClass().getName();
System.out.println(“ERROR: Operation [“+operation+“] is not allowed for current order state: “ + stateName);
//of course in real system you will probably throw exception
//throw new IllegalStateException(“This operation is not allowed for current order state.”);
}
Example of Usage of Order class
Now we navigating to customer code. Our OrderingSystem creates new Order, adds some beer as product and all in correct way:
Output:
Ok, now we added code, which tries to add more beer when order has been already shipped.
Output:
Other ways to solve problem without State Pattern
One of the disadvantages of this you could see many of the classes needed to have:
Yes, but this is the way to greatly encapsulate your behavior. Also there are other ways to resolve problem. For example usage of the table [state|method|state] which is populated with all allowable transitions. You could also resolve issue with having switch-case method. About all of this you could read in Jimmy Nilsson’s book “Applying Domain-Driven Design and Patterns“.
What have I learned?
I hope you enjoyed this story.
Go to: My Design Patterns Table
January 15, 2010 Design Patterns 3 comments
Imagine that you need some global logging system in your application.
You need to be able log your messages to some file at any point of your application, but also you need to numerate your messages.
How can you accomplish this?
Class which is represented below is example of Singleton Desing Pattern.
private LoggerSingleton(){}
private int _logCount = 0;
private static LoggerSingleton _loggerSingletonInstance = new LoggerSingleton();
public static LoggerSingleton GetInstance(){
return _loggerSingletonInstance;
}
public void Log(String message){
System.out.println(_logCount + “: “ + message);
_logCount++;
}
}
You are going to start execute your doHardWork method and you want to log that you just started doing hard work and what occured doing it.
So your functional system could look like below:
logger.Log(“Hard work started…”);
processor.processTo(5);
logger.Log(“Hard work finished…”);
}
As you see there is some class called HardProcessor. We should not really care how it works. All about we should care is that when it is created we want to log this and also we want to log when it is done with some calculations.
public HardProcessor(int start){
_start = start;
LoggerSingleton.GetInstance().Log(“Processor just created.”);
}
public int processTo(int end){
int sum = 0;
for(int i = _start; i <= end; ++i){
sum += i;
}
LoggerSingleton.GetInstance().Log(“Processor just calculated some value: “ + sum);
return sum;
}
}
Here is output of your programm:
I wrote this example when was in train with my friend. And I showed him my story and he said that I wrote Monostate. -“Me? Where?”. We took a look at my code and the only one variable I was using _logCount was static initially.
What is the difference between Singleton and Monostate?
Singleton is way to ensure that class has only one instance. Monostage if see globally on it do the same as GOF Singleton. All variables of it are static and this allows you to have many instances of monostate, but of course they will share the same data.
This also resolves many issues with multiconcurrecy usage of Singleton.
Lets take a look at my example once again. Could be that your logger is no so trivial, maybe on start of application you want to open some log file and get latest message number, so logger will continue to write to file with correct numbers.
Also your application is not so trivial. Maybe you are accessing your Singleton not only from just different places in your code but from different threads.
But since your constructor interacts with IO it takes time to construct your instance. So GetInstance() in reality in such situation could create TWO instances. Not really good for your application.
For our luck there are many ways to resolve this issue. Commonly we use Double-Checked Locking.
private ThreadSafeLoggerSingleton() {
//reads data from some file and gets latest number of message
//_logCount = got value here…
}
private int _logCount = 0;
private static ThreadSafeLoggerSingleton _loggerInstance;
public static ThreadSafeLoggerSingleton GetInstance(){
if (_loggerInstance == null) {
synchronized (ThreadSafeLoggerSingleton.class) {
if (_loggerInstance == null)
_loggerInstance = new ThreadSafeLoggerSingleton();
}
}
return _loggerInstance;
}
public void Log(String message) {
System.out.println(_logCount + “: “ + message);
_logCount++;
}
}
The way is not single and not all implementations of the DCL work! Read this good article on this: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Also as you see in method Log I’m using variable of my class and do operation on it, which is almost atomary. But if operations will be more complex you will need synchronization there also.
Go to: My Design Patterns Table
January 15, 2010 Design Patterns No comments
Creational Patterns
|
Structural Patterns
|
Behavioral Patterns
|
---|---|---|
Abstract Factory | Adapter | Chain of Responsibility |
Builder | Bridge | Command |
Factory Method | Composite | Interpreter |
Prototype | Decorator | Iterator |
Singleton | Facade | Mediator |
Flyweight | Memento | |
Proxy | Observer | |
State | ||
Strategy | ||
Template Method | ||
Visitor |
*As of Jan 2010 this blog post has this at the beginning:
[One of the goals for this year is to familiarize with Java. To accomplish this I have two possilities. First
one is my Master Diploma work in which I’m going to significantly
improve calculations in Self-Organizing Maps with efficient usage of
concurrency in Java Second one is my decision to write my own all of the GoF Design Patterns. And as you guess I want do this with Java. Next
table represents collection of Design Patterns and will have links to
my posts on each of the Pattern. I will fill it soon, no doubts.]
January 14, 2010 .NET No comments
There could be a lot of stupid troubles with references once you work with set of solutions which of them contains lot of projects.
Here is one of them.
I worked with one simple testing tool (TT) which lives in solutionT.
Testing Tool uses projects B and C in the solution1, i.e. has references to B and C.
(Please note that we are using references by assemblies locations.)
Project B also has reference to some commont project named A.
We moved our common projects both with project A to some other solution2.
Of course we changed references of projects B.
Very nice.
I did a bit of change to the A and wrote test for the B.Tests project and it works well in solution1.
But when I started my TT I got exception I fixed back again. I was thinking how could it be…
I rebuilt all solutions carefully but the same occurred.
Do you know what the problem is?
The problem is that the latest project in the graph i.e. my Testing Tool of course has a reference to a project A and that reference is obsolete, since it has old location…
Bottom line:
When you have troubles with references ensure that latest assembly in your references graph (executable one) has all references which are up-to-date and they are rebuilt. (file timestamp should be enough).
January 10, 2010 Book Reviews No comments
Book Domain-Driven Design Quickly is good resource to get consistent and short explanation to DDD.
I was doing my presentation on DDD and was looking for some source to build presentation quickly. And this book is such source.
I already read Applying Domain-Driven Design and Patterns by by Jimmy Nilsson and almost read Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans after that reading of this book was so much enjoyable and quick (I read it for 3 hours and English is not my native language.)
This book is quick readable summary of Eric Evan’s Domain-Driven Design. And it helps to refresh your memory if you already read that book. But if not:
You could read this book to get a good vision of what is Domain-Driven Design in very short term. If wiki or quick google search doesn’t satisfy you and you have not time for big books, this book is exactly what you need. Enjoy it.
January 8, 2010 Success 5 comments
Here is my short list:
• Read books
• Subscribe to RSS Feeds and read magazines
• Try out different features you hear about
• Go to seminars and do your own presentations
• Learn everything that can help you move
• Teach others since this teaches you
2. Establish what your goal is and keep the right way
3. Every challenge is an opportunity
4. Be positively charged
5. Find a mentor
6. Be more public
7. Track your activities; be sure that you are on track
8. Do your gym :)
So, let any of your axes be #.