Nov 23, 2011

Scroll event not fired in some Telerik Windows Forms Controls (maybe WPF as well)


First of all - this is not quite an issue.
Since the Telerik controls are compound controls (for example the list view has Root Element, List Element, things like that), what scroll are you subscribing to?

Do you subscribe to the whole control?
Do you subscribe to the RootElement? To the ListView?

To remove that kind of questions, Telerik came up with the idea that it will be better to rise the appropriate control scroll, instead the entire control scroll.
Consider this:

radListControl1.Scroll

vs:

radListControl1.ListElement.VScrollBar.Scroll

If you are called like the first one, how do you know who called you?
If you are called in response to the second one, however, you will know that the ListElement (the items placeholder) has changed its vertical scroll so you can respond to this easilly (for example in a case of Virtualization it will mean it may be hungry for some more items ;).

To be honest at first I was a bit frustrated but now when I got it it makes a lot of sense.

Disclaimer: I am not part of Telerik anymore so this is just my guess, why they did it that way and my own explanation. I may be wrong :).

Sep 29, 2011

Kindle Fire is comming! Amazon is taking orders on the new Kindle In Color (Kindle Fire)

Are you ready to get one?
Lot's of rumors that this little thing will be one of the main competitors to the Apple iPad. No one knows yet. With date of release set to 15 november, the Kindle Fire is a long awaited addition to the old Kindle.

Here is the old one (I have one and I'm pretty happy with it):


and here is the new, shiny tablet that Amazon will offer at the end of this year:




Honestly, I am thinking to get one, although pretty happy with the old Kindle, I need to stay in the business :). I would be happy to be able to optimize some of my upcomming products to work well in both - Kindle Fire and the old Kindle, so having both will be of great help to me.
On the other hand if you just need to read stuff, I belive to old Kindle will be enough.


+

= Happy developer.

Sep 2, 2011

LinkedIn API - request failed with 401 - unauthorized (cause #1 of N)


If you experience that, make sure you are encoding your request properly. For example http://api.linkedin.com/v1/people-search:(people:(id,first-name,last-name,picture-url,headline,location:(name)),num-results)?keyword=" + HttpUtility.UrlPathEncode(user.FullName).

In the above example if the user full name is Pavel Donchev, if you use HttpUtility.UrlEncode(user.FullName) the result will be Pavel%Donchev.
It should be Pavel%20Donchev, which is result of calling HttpUtility.UrlPathEncode instead HttpUtility.UrlEncode.

Almost unnoticeable difference mixed with generic message that may cause lots of head aches for you.

Aug 16, 2011

SQL Server–have another instance redirecting to existing SQL Server

I was in a need to have an SQL instance renamed.

This is because I have SQL instance on my server and wanted to have it on other computers as well so I don’t need to change the Connection Strings each time I deploy.

I first tried to rename it but to no avail. Then I found this little neat trick to have another instance that can “redirect” to the original server (e.g. you have (local)\Instance and want it to redirect to (local)).

To do this follow the instructions bellow:

1. Go to Start Menu => Microsoft SQL Server 2008 => Configuration Tools => SQL Configuration Manager.

image

2. In the SQL Configuration Manager expand the SQL Native Client 10.0 configuration node

image

3. Right click Aliases node and select “New alias”

image

4. In the Alias – new popup, in the Alias Name field type the name you want to have for redirection, in the server field type the server the alias will redirect to:

image

5. Go to management studio and type the new instance name in the server name text box to test the connection:

image

It worked pretty well for me, hopefully it will work for you as well!

Aug 9, 2011

A book is born!!!

As most of you know, I was involved in writing a book about C# programming (we were 30 authors, each had to write a chapter and edit a chapter).You can click on its cover in order to be taken to download the PDF version:

Hope you will enjoy it.

Oh, almost forgot – it is in BULGARIAN Winking smile. There were some plans to have it translated but as I am not a part of telerik anymore, I don’t have any information from the kitchen how far this project went.

Please be sure to say a great thanks to telerik for sponsoring this book!

Jul 14, 2011

Application suddenly becomes slow

I experienced this while I was developing my application in Visual Studio.
It happened for no apparent reason (I didn't remember to make any signifficant changes in this application).

It was really frustrating. The thought that I may need to rething the whole application was a nightmare.

I was in panic and started to think what the problem for this sudden degradation might be.

And guess what?
It appeared to be because of a conditional breakpoint I have set in one of the complex modules.

The program flow was passing through this line of code hundreds of thousand of times so Visual Studio was kind of slow determining if the condition for the breakpoint is true or not.

So remember this for the rest of your life:
"Conditional breakpoints may slow your application considerably, before doing stupid things in case of sudden performance degradation - be sure to remove your breakpoints first (Debug Menu => Disable All Break Points), then check the performance again.".

Jul 13, 2011

SVN Server - problem connecting to the SVN server

I had a problem today connecting my laptop to the SVN Server on my PC (a.k.a the Server).

The Tortoise SVN was saying something like "OPTIONS:" and then a long message saying the remote server didn't returned the information it needed.


I tried to browse with Internet explorer and instead a folder structure of my SVN repositories, I got a white page.

After a while of wondering I identified the problem - i forgot the "s" in https.

I didn't considered this as a possible problem because I expected to be presented "Remote server not found" or something like that in this case.

Have a great coding!

Jul 12, 2011

Sitefinity E-Commerce module is out (in Beta)!

There was a lot of passion about this module.
Some of the partners may not be really happy (those that offer their own E-Commerce modules).
Others will be as they will not need to worry which 3rd party module they need to buy and integrate and what head aches will there be while integrating.

Anyway - Telerik announced the availabillity of the long awaited E-Commerce module.

It is currently in Beta.

More information can be found on this
forum.

Jul 7, 2011

Me, Telerik, Introduction To C# programming book (some personal updates)

Ok, lot's of things happened recently.

First of all - I quit Telerik and got back to Veliko Tyrnovo.
A brave decision I have chosen in order to try to deliver more than it was expected from me ;).
This one was really though to decide as I really enjoyed being part of Telerik. A LOT!

Anyway, sometimes we need to sacrifice things in order to try to get to the next level.

And the next level for me is to try to do something for Veliko Tyrnovo (it is not my birth place, but I spent signifficant part of my life here and really love this city).

I thought it may be beneficial to the city if I quit Telerik and try to establish a company here + try to engage young potential developers attention so they get direction and momentum at a very early stage of their lives (not quite sure if you know or it is the same way in your country but here, it feels like there is a lot of depression).

It feels like the young people are somehow smashed and forced to belive they are no good, hence they become sellers in stores, car wash workers, gas station workers and stuff like that, just because they weren't directed at an early stage. They are vibrating at very low frequencies. Their frequencies are enough to just get them to graduate and find any job that will give them some money. No dreams at all.

To be specific - my company and my future initiative to try to help young developers have nothing in do one with each other so far.
Currently I am not an employer, I am not even a business entity yet.
All I have is some money (as usual - not enough for everything I think I need), some ideas, some dreams and a lot of energy.
The initiative with the young people is something I will do aside from my other activities. I imagine giving them materials, helping them answering questions, founding some user groups and things like that.

To be honest, I realise I have very limited capacity, I don't expect to make a revolution and make Veliko Tyrnovo "the silicon hills :)" but still, if I can help 1 or 2 young developers a year, that will be awesome and I believe it will lead in a signifficant improvement over the long run.

I am rising some money now for my company (well, yes, if you wish, count this as a marketing material, I am not asking anyone for anything, I am working toward this but will not return anyone with a good offer ;).

With all the friends (or should I use my network to look more like pro :) I think it is possible for me to get started and do some of the things I dreamed of.

Last but not least, I was involved in writing a book (I was one of the 30 authors) at Telerik. Leading this book was part of the work of Svetlin Nakov (check his blog to see more information about the Telerik Academy he is currently leading).
They updated us that the book is in pre-release stage (actually it is available for free download but I am really eager to see my name in a printed book ;).

That's all for now.
Wish you a great and productive day!!!

Jul 1, 2011

Awesome Presentation Framework from Telerik Silverlight Divisions

For LOB applications it is important that the users have their preferences saved (and later - loaded) once they have them set.

Telerik is now addressing this issue by unveiling awesome Persistance framework for the Silverlight Controls.

More information can in the
Telerik Presentation Framework blogpost by the Silverlight Division.

Ofcourse it was possible to achieve that before, but it tooks way more plumbing than now.

Currently the PersistenceManager class will take all the plumbing itself (probably you may need to implement another provider if you want to store the UI information in place other than the IsolatedStorage but still), letting you focus on the really important, application specific problems instead on plumbing...

It is really worthy to go with Telerik :).

Jun 28, 2011

Visual Studio AddIn - never put dots in a command.

I was following an article on how to create a command and add it to the Code Window context menu, it was going really well until some point.

I ran the code and Visual Studio was crying with E_INVALID_ARGS error on the

this._applicationObject.DTE.Commands.AddNamedCommand

This one is widelly used and pretty standard method so I thought the problem is somewhere in my code.

I realized that almost all the parameters I am passing to this method are pretty common as well so the problem must be at ....

Well, the command name I used was containing dots, that's why the error.
If you receive this message, please check the command name for dots (the second parameter you are passing to this method).

Since Visual Studio and other addin types seem to be working with very similar framework (the so called "extensibillity framework"), I suspect this rule is also applicable for other types of addins such as Outlook, Excel, Word, etc.

WebForm_InitCallback is not defined error (and some resolutions)

I was happilly working while all the sudden I started to get this message.
It took some googlin' in order to understand what is going on.

It was because my development server date was wrong (few months in the past).
Synchronizing it resolved the issue.
Also I read you may experience this problem in case you are changing the current thread culture.

Hope this helps ...

Jun 21, 2011

Sitefinity 4.1 SP2 is out!

A service pack for my favourite CMS has just been released.

The list of features and bugfixes can be found at:

http://www.sitefinity.com/devnet/forums/sitefinity-4-x/general-discussions/sitefinity-4-1-sp2-is-released.aspx

Can't wait to finish my ongoing work in order to get some time and try it.

Jun 10, 2011

Convert string to a known type (using its default converter)

I was in a need to get a type, instantiate it and then fill its properties (I'm currently doing an engine that will give me an instant CRUD UI).

So what I basically needed was to be able to fill a new object instance out of a Hashtable (the key is the name of the property and the value is its string representation).

I wanted to be able to convert that string value into the type it needs to be.
Here is some code to help you get it:

foreach(string strPropertyName in htValues.Keys)
{
PropertyInfo pi = entity.GetType()
.GetProperties()
.ToList()
.FirstOrDefault(property => property.Name == strPropertyName);
}
(this is kind of pretotype so don't blame me if you don't like the code :).

In the above code I am iterating in the keys of the hashtable, so if I have an user object it will strPropertyName will hold "FirstName", then "LastName".
So far so good, I am able to fill the object and send it to the EntityFramework for DB Persistance.

The problem was when the strPropertyName was holding "BirthDate" as it is a DateTime and the EntityFramework or the Reflection (not quite sure which one) was crying it can't Convert the string to the respective type for me.

Here is how I solved the problem:
// Create a new Instance of the given type.
object entity = Activator.CreateInstance(this.EntityType);
// Iterate through all the properties.
foreach(string strPropertyName in htValues.Keys)
{
// Get the property with that name:
PropertyInfo pi = entity.GetType()
.GetProperties()
.ToList()
.FirstOrDefault(property => property.Name == strPropertyName);
// Get the default type converter for the given property type:
TypeConverter converter = TypeDescriptor.GetConverter(pi.PropertyType);
// Set the value by converting non-values to the given type
// and setting null where it is a null value.
pi.SetValue(entity, htValues[pi.Name] == null ? null : converter.ConvertFromString(htValues[pi.Name].ToString()), new object[] { });
}

Basically the thing you (and I!) need to remember is that the TypeDescriptor class has a GetConverter() method that takes a type and returns a TypeConvertor for that type.

Now in order to be able to convert from string to that type you just need to call .ConvertFromString(string value) of the TypeConverter returned by the TypeDescriptor.

Hope this helps someone out there. To me it seems it can give you a great deal of abstraction and I (for some reason) believe this is heavilly used in nowadays OR/M's.

Jun 9, 2011

Get the underlying type out of a Nullable

It appeared to be really simple actually, this post title suggest the solution:

Type nonNullableType = null;
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
nonNullableType = new NullableConverter(property.PropertyType).UnderlyingType;
else
nonNullableType = property.PropertyType;

What we actually do is to check if the type is nullable or not, if so - we are getting its Underlying type, and if not - we are getting the type itself.

Check if a type is Nullable or not

I was in a need to determine if the type of PropertyInfo is a nullable or not.
Here is what I've found on MSDN about this:

property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)

So you basically need to determine if the type is generic (makes sense as nullable is a type that takes T (Nullable)) and then to check if the type is a Nullable then.

Now, I really wondered do I really need both checks?
As it was coded that way at MSDN I first didn't look at that, but I wanted to tackle it a bit more.

First I thought that the first one is needed to protect you from the null value returned by the GetGenericTypeDefinition() method.
But what's the problem even if it does?
Well, you get InvalidOperationException saying "This operation is only valid on generic types.".

So you definetelly need both checks ;).
It is kind of ugly for me, maybe it will be better to create an extender to the Type type. Something like "IsGeneric()", but the Is prefix always suggests property while this is a method.

Anyway, I'll go with that.
In the next post I'll show you how to get the type out of a Nullable<>.

May 27, 2011

Programming - Rule #1 follow your data from the UI to the Database and back

It can save you a lot of time :).
I had to fix a bug with a value not updating on the UI.
I attached with the debugger and followed the code to the Save() method of the manager.
Then I started looking for some problems in the database (asynchronous triggers failing etc.).

I wasn't quite sure where the problem is for a while.
Then I decided to hit F11 on the Save() method of the manager with the hope to see what query it was generating.

Guess what?
It wasn't the query but the fact that the Manager was overriding the Base Manager Save() method, as it needs to convert a DTO object to DataObject in order to save it.
Well I didn't even need to read through all the properties to know for sure that the property that wasn't updating was missing in the list of assignments in the convert method (in order to defend myself I would say that 99.9% of our managers aren't overriding save methods, it is very unlikely so I didn't considered that to be the problem).

Happy coding and remember Assumptions are your worst enemy :). They are the things that waste most of your time.

May 26, 2011

Serializing object to JSON returns empty string?

Consider the following code:

string JSONObject = string.Empty;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(this.GetType());
using (MemoryStream ms = new MemoryStream())
{
    serializer.WriteObject(ms, this);
    // Donchev - we need to reset because the write has gone to the end of the stream
    // and the StreamReader.ReadToEnd() won't seek to the beginning of the stream again.
    using (StreamReader sr = new StreamReader(ms))
    {
        JSONObject = sr.ReadToEnd();
        sr.Close();
        sr.Dispose();
    }
    ms.Close();
    ms.Dispose();
}
return JSONObject;

It seems perfectly correct but have a few problems.

And the first one is very important – it is based on wrong assumption and it is returning empty string because of that.

I will let you tackle it for a while to see if you can find where the problem is.

Ready?

If not – I’ll tell you – the problem is that when I wrote this code, I was expecting the ReadToEnd() method of the StreamReader class to auto reset the stream to its beginning, it sounds for some reason to me that this method it is saying - “Read the whole thing.”.

Unfortunately this assumption evaluated to false.

The method actually says - “Read from where you are to the end of the thing.”.

So before calling JSONObject = sr.ReadToEnd();

I needed to simply call:

ms.Seek(0, SeekOrigin.Begin);

In order to reset the pointer to the beginning of the stream.

Voilla!

The other question I asked myself is why the pointer is at the end of the stream (after the string is empty and not some portion of the stream, it should be at the end).

The answer – the serializer.WriteObject() method is probably not resetting it to be at the beginning after it completes its job.

Not quite sure who is responsible for resetting the stream – the caller or the callee, we can have a long discussion about this.

Anyway – just wanted to share this with you. I know it is very old thing but I am trying to write for much of the things that made an impression on me.

May 23, 2011

Silverlight 4 - catching uncaught exceptions from external components

I was playing with an external component in Silverlight 4 and got an unhandled exception while debugging.

The problem was that I wasn't able to see what's going on because the debugger won't show anything (it doesn't have the source of the exception) and because the exception was triggered internally in event in the component trying to catch it to see what is the exception had no effect as well.

Then I opened the App.xaml file and found the following:

if (!System.Diagnostics.Debugger.IsAttached)

Pretty neat, huh? :).
The method signature was as following:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)

All I needed to do now was to put a breakpoint on the if statement and then expect the ApplicationUnhandledExceptionEventArgs.ExceptionObject to see what the exception was.

Thought you may have some hard times debugging problems with Silverlight.

May 19, 2011

Tip : how to identify which dll to reference?



I had a bad experience today.
I was moving a project from one PC to another, it was referencing dlls from my old PC.

I started to remove references one by one and adding them again, this time from a common location.
I missed on of them (deleted it from the project without first remembering which one it was).

So lesson number one - you can create a screenshot before deleting the references so you can restore them later.

But here is how I did I found the reference I needed (in my case I wasn't quite sure in which assembly was the RadWindow for Silverlight):

1. Go to your project and open some of the files the control resides.
2. Open the Toolbox (View => Toolbox).
3. Find the control in the toolbox and drag it to the design surfice.

In most cases Visual Studio will create a reference to the correct dll.

May 10, 2011

Server Explorer is not responding in Visual Studio 2010 (as well?)

 

imagesCAZWHD7Q

 

I think this problem was present in the previous versions of Visual Studio as well, anyway, here is what happens:

1. You have some connections / servers in Visual Studio 2010 Server Explorer.

2. Something changes for example server was renamed / removed, or a connection no longer works, not quite sure what exactly should happen…

3. When you try to select the server or connection in server explorer in order to delete it, you get the Hourglass icon, you can’t do anything and waiting doesn’t help.

 

To resolve this, as I found in Google you may want to try this (Windows 7):

1. Close ALL instances of Visual Studio

2. Go to “C:\Users\your_user\AppData\Roaming\Microsoft\VisualStudio\version\ServerExplorer”

     Where your_user is your user and “version” is the version of Visual Studio, in my case, Donchev and 10.0.

3. Delete the file “DefaultView.SEView”.

Note: You may want to just edit the file, removing or changing problematic connections, I wanted my Server Explorer reset so I deleted the entire file, it is faster and safer.

May 9, 2011

Very old stuff – convert System.Drawing.Color to HTML.

When I was with Delphi, I wrote utility to do this myself (I mean Delphi in its early days) as I wasn’t aware for built-in mechanism to achieve that.

Now with .NET there is utility to do this for you but I often forgot which class has static method to convert System.Drawing.Color to Html string.

Here it is:

System.Drawing.ColorTranslator.ToHtml(color)

I think wouldn’t it be smarter to have an extender attached to System.Drawing.Color to do this for me from now on … :).

May 6, 2011

Have WCF Service hosted on windows service.

This one is quite old, anyway, as I am using my blog for adding notes to myself as well, I will repeat the solution so I can later find it :).

Maybe you will find it useful as well.

To host a WCF service on top of Windows service you need to do the following:

1. Create the windows service that will host the WCF Service.

2. In the windows service add references to the following assemblies:

2.1. System.ServiceModel

2.2. System.ServiceProcess.

3. Declare the following in the Service class:

ServiceHost host = null;

4. In the OnStart method of the service, instantiate the host variable and the WCF Service instance:

protected override void OnStart(string[] args)
{
    if (host != null)
    {
        host.Close();
    }


    SomeService.ServerAgent server = new SomeService.ServerAgent();
    host = new ServiceHost(server);
    host.Open();
}

5. We need to handle Service stop as well, add the following code to the OnStop method of the Windows Service:

protected override void OnStop()
{
    host.Close();
    host = null;
}

6. All we need to do now is to set some bindings / endpoints. NOTE: They should go to the app.config file of the WINDOWS service. Just copy them from the WCF Service web.config.

You are done.

Install and start the windows service and navigate to the Url Address you added as endpoint. You should be able to browse it.

Coding Practice : Always refresh the 2nd Visual Studio Solution :).

I had a problem with some code in a Visual Studio, the errors were something like when you have a missing file, or a missing method or stuff like that.

They were happening all the time and I was wondering what is going on.

The problem was that I was having 2 Visual Studio instances running with different solutions loaded in them, I was coding in the first solution and touched a shared project (.csproj).

The second Visual Studio asked me to refresh. I answered no and the old code was in the Visual Studio #2.

To overcome this, you may:

1. Always answer “Yes” to the refresh dialog (bad practice) as you may forget sometimes or accidentally click “No”.

2. Click refresh on the solution file in the second visual studio (bad solution, it is a bit slow and you may forget to do this).

3. Go to Options –> Environment –> Documents –> and check the following checkboxes:

   3.1. Detect when file is changed outside the environment (check).

   3.2. Auto-load changes, if saved : (check)

I will go with approach #3 and see if it has some shortcomings as I can’t think any right now.

A screenshot bellow shows the exact settings:

image

Having column display name in RadGrid Column chooser but not in the header of the grid

A little bit of background for this one.

I had a Telerik RadGrid that was having few columns ...

It had the column chooser enabled. Few of the columns were icons (for example “Answered”, “Rating”).

I wanted to have them without header text so I added the Template column and everything was just fine.

Until I right clicked on the header in order to show the column chooser. It was displaying the columns with auto generated names like “GridTemplateColumn7”, “GridTemplateColumn10”.

My goal was to keep the header of the grid clean (e.g. no label) because the icons were 16x16 and that’s all the space I needed to occupy with those columns, having a header “Answered” would extend the entire column. So to solve this case here is what I did:

Solution:

1. Added header text to the column and saw that the header text is appearing in the column chooser.

2. To hide it from the header of the column I added an empty <HeaderTemplae>.

The column should look like this:

<telerik:GridTemplateColumn HeaderText="Bookmark">
    <HeaderTemplate>
    </HeaderTemplate>
    <ItemTemplate>
    </ItemTemplate>
</telerik:GridTemplateColumn>

 

This would solve the problem for Template columns (and all column types that allow you to define HeaderTemplate). This will not work for GridBoundColumn for example as this type doesn’t have HeaderTemplate.

 

Hope this helps someone out there …

Apr 17, 2011

Unable to start debugging on the server.

Lot's of such errors, lots of resolutions.
I had another one, the full message is:

Unable to start debugging on the server. An authentication error occured while communicating with the web server. Please see Help for assistance.

It looks like it is an issue with permissions but the problem is that I disabled the "HTTP Keep-Alive" signals for the web site.

Hope this saves few minutes of research ;).

Feb 2, 2011

Copy XmlNode from one XmlDocument to another

This one is more for the archive, but it is not widelly used so you may not know it.

In case you need to copy XmlNode from one XmlDocument to another, you need to do two things.

1. Import the XmlNode from the source XmlDocument to the target XmlDocument, using Import(XmlNode node, bool deep) method of the target node,
2. Get the result from this method (it is XmlNode) and use AppendChild method of the node that should be parent of the node to be transfered.

In other words:
XmlDocument sourceDocument = new XmlDocument();
XmlDocument targetDocument = new XmlDocument();

sourceDocument.LoadXml("");
targetDocument.LoadXml("");

XmlNode nodeToImport = sourceDocument.SelectSingleNode("//nodes/sourceNode");
XmlNode importedNode = targetDocument.ImportNode(nodeToImport, true);
XmlNode parentTargetNode = targetDocument.SelectSingleNode("/nodes/targetParentNode");
parentTargetNode.AppendChild(importedNode);

is enough to import the sourceNode with all its child nodes under the targetParentNode of the target document.

Jan 21, 2011

Limit Microsoft SQL server memory usage

I had to work with a fairly large database on my PC.
It became very unresponsive so I checked what's going on.
I clicked on the Performance tab in Windows Task Manager and noticed that the RAM was more then 7 GB (too much for a personal computer, don't you think?).

I realized that 4 of those 7 GBs were used by the MSSQL server.
I went to management studio, right clicked the server and choosed options.

Then I clicked on the Memory page and saw that MSSQL Server was allowed to take up to 2048 TB of memory (couldn't even imagine that):

I limited the server to 1 GB and my PC was healthy again (the queries I do may take a bit longer but at least my ALT + TAB key combination is working again :).

Limit MS SQL Server memory usage.


Simple thing that improved my experience a lot.