Saturday, January 19, 2013

Bitten by uninitialized DateTime fields in Entity Framework

I was trying my hands with Ninject, Quartz.Net in an MVC 4 project. Everything was working fine. I added a new model to data project. After adding migration and updating database, I pressed F5.

pofff... the page which was working fine well..., stopped being fine anymore.

I was getting following error:

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.

But I was already setting all the date fields and everything was working nicely. After fooling around, it suddenly occured to me that I was not setting a property that is coming from the base class which all the entities were inheriting from.

If the date fields are not initialized (not set), by default it is set to

01-JAN-0001
which of course falls outside the range of the dates acceptable by SQL Server.

The simplest way to get arround is to set the DateTime fields to something acceptable to SQL Server. All worked fine after I added following line:

obj.UpdatedOn = DateTime.Now;

Thursday, December 22, 2011

Displaying items horizontaly in WPF ItemsControl

I am trying my hand on Microsoft Composite Application for few days. I was trying to display list of Actions available from a moudle into a Region using following markup:

  
        
            
                
                    
                
            
            
                
                    
                        
                            
                        
                    
                
            
        
    

This displays items in vertical manner (as is default with ItemsControl and its derivatives like ListBox). I added following code to make it use StackPanel:

    
        
            
        
     

But it did not produce the desired outcome. I tried the WrapPanel also but it was still same. After some more frustration I commented GroupStyle tag:

    
        
            
                
                    
                
           
        
     

Now it worked as desired by displaying Button controls in a single row.

Wednesday, June 22, 2011

Error on Adding WCF Service Reference to ASP.Net Project

I am writing a small website using EF 4 Code First. There are some legacy tables which don't have primary key. This (not having PK) would have created complications with EF, but I needed to only read data from those table. So I decided to create a WCF service to pull the data. I defined [ServiceContract], [DataContract], [OperationContract] etc. and everything was going fine till I tried add reference to my web project. In the Add Service Reference dialog VS did find service, but when I clicked on service to fetch metadata I got following error:

There was an error downloading 
'http://localhost:8732/Design_Time_Addresses/LegacyDataService/DataService/mex'.
The request failed with HTTP status 400: Bad Request.
Metadata contains a reference that cannot be resolved: 
http://localhost:8732/Design_Time_Addresses/LegacyDataService/DataService/mex.

After some head scratching and googling about the error I found out a post on MSDN forum where somebody was putting [DataMember] attribute over an indexer. I checked my [ServiceContract] and [DataContract]s.

My [ServiceContract] read as follows:

[ServiceContract]
public interface IDataService
{
    [OperationContract]
    IList<LegacyUser> GetUsers();
    ......
    ......
}

I tried to comment the IList<LegacyUser> stuff, but the error was still there. It then occurred to me that there was an Address property which returned build user's address by concatenating other fields. After this Address property was commented the error was gone.

Moral of the story is that:
  1. you should not put [DataMember] attribute on Indexers (as mentioned in MSDN post).
  2. you should not put [DataMember] attribute on properties that use other properties with the attribute to calculate return value.

Wednesday, May 25, 2011

MySQL Error 2002

I was reading an article about MySQL replication yesterday. After reading a bit I thought it will be really easy to test it. I setup a remote MySQL server available with a friend and configured it as master. After this I fired up Ubuntu Lucid Lynx VM in VirtualBox and configured it as slave (changed my.cnf file mainly).

Now when I tried to login into MySQL I got following error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
After sifting through many posts on internet forums, I occured to me to check error logs (how intelligent, thought this should have been first thing to do). I issued following command:

tail /var/log/mysql/error.log

110525 23:19:20 [ERROR] /usr/sbin/mysqld: unknown variable 'relay-logn-index=test_slave-bin.index'
110525 23:19:20 [ERROR] Aborting

So it was only an extra 'n' that gave me so much headache. After changing 'relay-logn-index' to 'relay-log-index' it worked fine.

Thursday, January 6, 2011

Making Selected Row Visible in UltraWinGrid

I was facing a problem with Infragistics UltraWinGrid object. There were about 15 rows in the grid. Due to size of form only 8 were visible at a time. The first rows was fixed, so it cannot be moved by scrolling.

To edit row a popup form is opened on double clicking the row and a button on the form. On successful saving of editing information in popup form, parent form's grid is refreshed from database.

Upon refreshing if the very first row (just below the fixed row) was selected or popup was opened by clicking on button when selected row was not visible, it is not scrolled to view.

Unfortunately windows grid does not contains a method like web grid which scrolls selected row to view (ScrollToView).

After some hit and trail I found the following solution:

myGrid.ActiveRowScrollRegion.FirstRow = row;//row is selected row (can get using myGrid.ActiveRow)

Wednesday, October 27, 2010

Ruby On Rails: rspec failing with [no such file to load -- spec_helper]

I have started reading www.railstutorial.org. It is wonderful tutorial for learning Ruby on Rails (ror). I am at chapter 3 currently and tried to setup the unit testing.
After creating project and generating controllers, I installed growl for windows and then autotest, autotest-growl gems. But when I issued the following command:

rspec .\spec\controllers\pages_controller_spec.rb
I got following error:

:29:in `require': no such file to load -- spec_helper (LoadError)
 from :29:in `require'
 from F:/Code/Learning/ruby/todo/spec/controllers/pages_controller_spec.rb:1:in `'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/configuration.rb:306:in `load'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/configuration.rb:306:in `block in load_spec_files'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/configuration.rb:306:in `map'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/configuration.rb:306:in `load_spec_files'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/command_line.rb:18:in `run'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/runner.rb:55:in `run_in_process'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/runner.rb:46:in `run'
 from D:/Ruby192/lib/ruby/gems/1.9.1/gems/rspec-core-2.0.1/lib/rspec/core/runner.rb:10:in `block in autorun'

Going through much pain of reinstalling quite a few gems and banging my head, I went back to read the tutorial page again from beginning and make list of what I have already done as given in page. I found out that I had missed to execute following command:

rails generate rspec:install
It did the folowing:
create .rspec
  exist  
 create  spec/spec_helper.rb
 create  autotest
 create  autotest/discover.rb

Now I had got spec_helper.rb in my spec folder and was able to execute the tests (happily ever after ^_* ).

Also remember to install win32console-color gem to get colorfull info with autotest.
Happy Coding!

Tuesday, February 2, 2010

A way to resolve bugs

I just found a nice blog post by Chris Missal titled "How I Approach a Defect" via a tweet by Elijah Manor.
Chris outlines the systematic approach he takes when solving programming bugs (defects, as he calls them). He underlines the fundamental notion that you should actually fix the problem not just get the right answer for a particular case.
Like Five Ws (5Ws) Chris Missal's defect solving framework tries to ascertain that proper solution has been applied to remove defect by answering following questions:

Does This Solve the Problem? 

Is This Flexible, Maintainable, Clear and Simple?

Does This Leave the Code Better Than I Found It?

Is It Covered with Tests to be Future-Proof?

Is There Any Code that was Commented Out or Stale?

Do Any Named Variables or Classes Exist that Aren't Clear?

Are All Changes Relevant to the Fix?

Please read his post for details of what these questions mean.
Happy Coding!

Monday, November 9, 2009

Free .Net Profiler

I got link for free (as in beer) .Net profiler from eqatec.
It works with many languages:

LanguageVersionPlatform
C#
VB.NET
Managed C++
F#
C or C++
Java
.NET 3.5
.NET 3.0
.NET 2.0
.NET CF 3.5
.NET CF 2.0
.NET 1.1
WinXP, Vista
Windows Mobile
Windows CE
XP embedded
PocketPC, PDA
Linux

Tuesday, October 13, 2009

I got Google Wave Invite!!!

Wow, I got invitation for Google Wave.

Googlewave
preview
Thank you for signing up to give us early feedback on Google Wave. We're happy to give you access to Google Wave and are enlisting your help to improve the product.


can't wait to have a look. Will sure my experiences. Keep watching.....!

Dealing with TimeStamp columns with SubSonic 3 and MS Sql Server

Today someone asked a question at StackOverflow
regarding problem with SubSonic, not allowing to update record in table with "TimeStamp" typed column. I've been SS enthusiastic since long. I was quick to reply:

You don't need to worry about this. SubSonic is intelligent enough to handle this! Just create new object and assign values to properties and save it.
I then created a table to test it and it worked like charm.




User commented back that he is not able to make it work. It then occurred to me that he might be using SubSonic 3. I tested with SS3 and he was right there was something funny. I got following error:



What is this? SubSonic failed to take into account that a TimeStamp datatyped column should not be explicitly set in Insert or Update statements.

I fired .Net Reflector and opened SubSonic.Core.dll. It took me to the following method in SubSonic.Extensions.Database class:
public static ISqlQuery ToInsertQuery(this T item, IDataProvider provider) where T: class, new()
{
    Type type = typeof(T);

    ITable tbl = provider.FindOrCreateTable();

    Insert query = null;

    if (tbl != null)
    {
        Dictionary hashed = item.ToDictionary();

        query = new Insert(provider).Into(tbl);

        foreach (string key in hashed.Keys)
        {
            IColumn col = tbl.GetColumn(key);

            if ((col != null) && !(col.AutoIncrement || col.IsReadOnly))
            {
                query.Value(col.QualifiedName, hashed[key], col.DataType);
            }
        }
    }
    return query;

As you can see in this line:

It was checking if column was null or auto-increment, and was omitting it from column list for query. By default TimeStamp typed column should be readonly. But even if it was readonly the line above is not checking for ReadOnly property. I also tried to set it to null but it did not work.

I went to GitHub and forked subsonic source code. I was sure putting another check in if statement above will work:

if ((column != null) && !column.AutoIncrement && !column.IsReadOnly)

But when I opened the code the above method read something like this:
public static ISqlQuery ToInsertQuery(this T item, IDataProvider provider) where T : class, new()
{
    Type type = typeof(T);
    ITable tbl = provider.FindOrCreateTable();
    Insert query = null;
    if(tbl != null)
    {
        var hashed = item.ToDictionary();

        query = new Insert(provider).Into(tbl);

        foreach(string key in hashed.Keys)
        {
            IColumn col = tbl.GetColumn(key);
            if(col != null)
            {
                if(!col.AutoIncrement && !col.IsReadOnly)
                    query.Value(col.QualifiedName, hashed[key], col.DataType);
            }
        }
    }
    return query;
}
Hmm, the problem is already sorted out. The questioner is also using dll from some old build. I compiled, added reference and re-ran the test code. No luck. It confronted me with same error. I put break point at save statement to delve deeper. The column was never set as ReadOnly :(

I scourged the generated code and saw what it generated for TestTimeStamp table. It read:

public class TestTimeStampTable: DatabaseTable {
    public TestTimeStampTable(IDataProvider provider):base("TestTimeStamp",provider){
    ClassName = "TestTimeStamp";
    SchemaName = "dbo";
    ………………
    ………………

    Columns.Add(new DatabaseColumn("RowVersion", this)
    {
        IsPrimaryKey = false,
        DataType = DbType.Binary,
        IsNullable = false,
        AutoIncrement = false,
        IsForeignKey = false
    });
}

So problem was somewhere here! When creating column, SS was not putting if the column is readonly or not. I checked structs.tt T4 template.

It has following code:
<# foreach(var col in tbl.Columns){#>
    Columns.Add(new DatabaseColumn("<#=col.Name#>", this) {
         IsPrimaryKey = <#=col.IsPK.ToString().ToLower()#>,
         DataType = DbType.<#=col.DbType.ToString()#>,
         IsNullable = <#=col.IsNullable.ToString().ToLower()#>,
         AutoIncrement = <#=col.AutoIncrement.ToString().ToLower()#>,
         IsForeignKey = <#=col.IsForeignKey.ToString().ToLower()#>
    });

<# }#>

It is not even bothering to check if column is readonly or not :( I put following line after IsForeignKey line:
IsReadOnly = <#=col.DataType.ToLower().Equals("timestamp").ToString().ToLower() #>

On saving the file the code was regenerated. TestTimeStamp class now read:

Columns.Add(new DatabaseColumn("RowVersion", this) {
    IsPrimaryKey = false,
    DataType = DbType.Binary,
    IsNullable = false,
    AutoIncrement = false,
    IsForeignKey = false,
    IsReadOnly = true
});

I tried my luck again. It ran without any error. I ran it again, opened SQL Server Management Studio and executed SQL Query:

Select * From TestTimeStamp

Now it returned:

RowIDRowDescriptionRowVersion
---------------------------------------------------------
1Hello world!0x00000000000007D1
2Hello world, Again!0x00000000000007D2
(2 row(s) affected)
Happy Coding!

Friday, October 17, 2008

Showing HTML Content over Flash Movie - quick and dirty way!

I had faced a nasty problem few days ago. I was to show user a modal-popup (in html page) for Terms and Conditions for registration on a site. Popup was coming okay, but There was a flash movie at top of the page which was hidding upper portion of the dialog. The tested and widely used method is to put an Iframe at place where you want to show your content and absolute position your content and IFrame. For example, if you want to show a div above a flash movie, then place a IFrame like follows:
        <iframe style="position:absolute;top:250;left:150;"></iframe>
Then position the div exactly above this iframe like:
        <div style="position:absolute;top:250;left:150;"></div>

I was using jquery on the page to show dialog using ui.dialog plugin.
After fooling around sometime I devised following simple solution.

1)  put id attribute on movie element to uniquely identify the movie object. Like,
<object id="movie1"></object>
2)  before showing the dialog (or other content for that matter) call a javascript function to hide the movie. Like,
$("#movie1").css("display","none");

3)  now show dialog. Like,
$("#dialog").dialog("open");

4)  after closing the dialog, show the movie again. Like,
     $("#dialog").dialog("close");
$("#movie1").css("display","inline"); 

that's all folks, Happy Coding

Monday, January 28, 2008

Working with Anthem.NET and AJAXControlToolkit CalendarExtender

I've wasted almost complete day to debug what now seems very trivial. I'm using Anthem.NET in my project. I almost exclusively use Anthem.NET in my ASP.Net applications for AJAX. Almost because I've to rely on AjaxControlToolkit for some capabilities, like Calendar and ListSearchExtender.
I'm using Anthem ListBox box, and some textboxes on a page. Listbox generates a callback and textboxes are populated async'ly. One of the textboxes is for date input. I've used CalendarExtender control to show dropdown (I just love it for this thing) calendar. When page first loads calendar shows nicely, but as soon as callback is generated, it stops working.
After looking at generated page, I found code responsible for creating client side calendar. It is this one:
Sys.Application.add_init(function() {
$create(AjaxControlToolkit.CalendarBehavior, {"format":"dd/MMM/yyyy","id":"MyCal"}, null, null, $get("ctl00_ContentPlaceHolder1_txtPurchaseDate"));


So, it seemed very simple register a PostCallback function for ListBox, with $create method in it, to recreate calendar everytime a callback occured.

So far so good, but it cropped up control with duplicate id problem. I tried $dispose method from ajax.net library, but it told me that element I'm looking for is unavailable. Then I tried prototype to remove the said element from the DOM tree, but it was also not able to find element.

Then after googling many times for many things (in the meantime reading scripts in AjaxControlToolkit source code, using reflector to go through System.Web.Extensions.dll and using firebug extensively) I got to Ajax.NET reference on asp.net (now, don't laugh at me that it is not in my delicious, as I've been relying mostly on Anthem.NET).

There I found the whole story at page for Sys class [here]. I used $find method to get my element and used removeComponent to remove previous instance before creating new one.
Sys.Application.removeComponent($find("MyCal"));

Thursday, October 11, 2007

Setting focus to control in Asp.NET 2

I'm building a website (as i told in my previous post). In one form i used wizard control. The problem was that the form is in master page, which itself contains navigation bar as header of the site. When page loaded, the control will go to links and controls on the master form first and then to controls in this form.

I googled and found nice snippets of Javascript and even a control class on codeproject. But I tried to go the easier way first. So in page_load event I tried like dropdownlist1.Focus() and voila it worked.

Next was to see on which step the wizard is, which I was already doing to validate the inputs from user, and set the focus to first control on next page of wizard.

There was a postback also, where a dropdown list changes and loads another one. In postback handler (dropdownlist2_selectedindexchanged) at the end, I wrote dropdownlist3.Focus() and it was working here too.

Hope it helps you.

Saturday, October 6, 2007

Another reason for "Failed to Update Database ..\App_Data\aspnet.mdf because database is readonly

I am currently working on ASP.NET 2 project. After working for 2 days and creating an outline for the site and flow for user interaction, I decided it was right time to put it into source control.

After I added it to source control it started giving me giving strange "database is read-only problem". I googled a bit about it. The solutions offered ranged from giving IIS process, ASPNET user and don't remember who else to give access to app_data folder. But it did not work.

Then there was an elaborate solution using command line sseutil . It recommended to detach the database and reattach it. After some futile attempts, I had to close VS, and restart Sql Express.

Again today some how I checked in all the files in solution and it again gave gave me same problem when I tried to create a Stored Procedure. Then occurred to me that maybe it is because the database file is checked in source control and is read-only (it was checked in). I detached it (with sseutil of course), checked out the file (aspnet.mdf) and it is working again alright.

Monday, August 27, 2007

Running Firebird Embeded Database in .NET 2

I wanted to create a small application to keep track of my daily expenses. Me and my friend (we are also room mates) think that we are expending too much because we are unstructured. So I thought to give it time this Sunday.

I decided to use embedded Firebird server for easy portability.

Go to Firebird site and it says that embedding Firebird is a breeze. Me to thought so. But it might be little cumbersome as many things have changed in Firebird version 2.
I downloaded Firebird embedded package. Copied fbembed.dll and Firebird.Data.FirebirdClient to my executable directory, but every time I tried to execute
FbConnection.CreateDatabase()
I got 'Unable to load DLL "fbembed"' error.

Googling for it yielded no results except advice for copying fbembed.dll and FirebirdClient assembly to the folder where executable is.

I copied everything from embedded package and it worked. But time and again it is mentioned that every thing from package is not needed. So now again I removed the embedded stuff and started things one-by-one.

  • First fbembed.dll and FirebirdClient assembly --> It did not work.


  • Then I added all the dlls (i*.dll) from embedded package with firebird.msg --> It did not work.<.li>
  • Then I added intl folder --> It worked!!!



No I coppied these files to bin folder and added the intl folder and the dlls to my .NET Project and set their build action as content and Copy to Output Directory as Copy Always.

It is working fine and I don't have to copy it to release or debug folders.

Happy Codding ;-)

Wednesday, August 8, 2007

Why Open Source Works

I'm studying Apache OFBiz for some time, because my company Vismaad is expecting a project in which we will be using it.
I ran into some problems and had to ask for help on ofbiz mailing list. It usually takes under 40 minutes to get an answer and if problem is not severe (means only you are doing something in wrong way) you can solve it in under 2 hours.
Great!!
Many commercial help desk services cannot give you this kind of support.
Now compare it to this:
I ran into a problem with ASP.NET 2.0 AJAX website when I was using CSS Adapters for controls. I posted my problem on official ASP forum. But even after many days I'm still to get any answer.
The myth that there is no money in open source is unfounded. You only need to look at the frantic activity in mailing lists and open source software forums. All those people are not doing the work only for hobby. Yes people are cooperative and guiding, but that does not means that they don't need money or make money. Many new features and changes get thoroughly discussed in these forums and lists. So it many users have problem configuring a feature or if something important is missing you can step in or request the follow users to have it fixed in next release or at least get a patch for it.
On the other hand if you look at closed source or propriety solutions you cannot force them to make any changes, and it they have some kind of monopoly or great market share (hey! don't make any guesses) it is impossible.
So moral of the story is that open up for opensource. See, Learn and if you like it use it and give back to community by promoting it, helping other in forums and mailing lists and contributing to source code.

Long Live Open Source

Why Open Source Works

I'm studying Apache OFBiz for some time, because my company Vismaad is expecting a project in which we will be using it.
I ran into some problems and had to ask for help on ofbiz mailing list. It usually takes under 40 minutes to get an answer and if problem is not severe (means only you are doing something in wrong way) you can solve it in under 2 hours.
Great!!

Many commercial help desk services cannot give you this kind of support. But still people relay on commercial services.

Tuesday, July 31, 2007

Where do I belong?

It is weekend and after 6 days of the rut you feel like unwinding a little. I like to describe here a little that our idea of unwinding is not as goes. We rented DVD of Sherek 3. It was 1 AM when the movie finished. After movie we went out for a little stroll.

Only 3-4 hundred meter from where we stay were some policemen. They stopped us and started asking about the identity prof. Now you don't carry your I-Cards, Driving Licenses, or passports with you, when you go for a stroll. So if you don't have ID prof then let someone from you higher ups talk to us. This is not the time of the day when you call up your boss and ask him to tell the policemen who you are.

The logic given by the cops for stopping us at that time was that there are all kind of people going around. But if we were such kind of people then we may have settled with somebody to be our "BOSS" to verify our antecedents.

So we asked them that if we really look like terrorists them we can walk up to our rooms and get our I-Cards. Somehow they believed in use and asked us to walk back because it was very late.

It really hurts when this type of thing happens with you in your own country. Where you are working and living since few years. I've been to abroad also but no body ever asked about my identity proofs at dead of the night when there is not even an emergency.
But you cannot argue with a cop and at that in middle of the night. Because if it hurts (not physically, just his ego) you can well be a terrorist by the morning or a hardcore criminal or a drug peddler. Because it is INDIA not Australia where police will say that they were at fault.

An amusing thing happened just when we were walking back. A car came from other side and our cops signaled them to stop. Most probably they were also coming after letting their hairs down. But they cheered and sped off.

Wednesday, July 25, 2007

Farewell to Kalam

Today Pratiba Patil is sworn in as 13th President. Hope she comes clear of all the muck that was raised on her in run up to the elections. The way we got out 13th president speaks of the nadir we our politicians have reached.

In the first place thinking of anybody else instead of Kalam as presidential candidate was treachery with the peoples and specifically youth's will. He is in very good health. He is well educated (really educated-not degree holder like many of the fools who run our country). He did lot for the country (he didn't even find time to get married because he was so busy making missiles to defend our country). He is truly secular. Mrs. Patil may serve well as a token of rise of women in India, but it never occurred to anybody that Kalam is Muslim. He is Indian and our president first.

His biggest contribution to the nation is the inspiration he imparted to the youth. His truthfulness, purity and intelligence always charmed the children and young people. He has visions about the future of country and its children.

I hope that Mrs. Patil will be able to stand up to the high office of the President of India. I wish Kalam a long and healthy life, so that he continues to inspire the youth and contribute to the development of India.

PS:- Let us see if BJP and allies win majority and Mr. Vajpayee does not swear in as PM, because he did not believe that same person should be given second term in Rashtarpati Bhawan.