Jul 29, 2009

telerik radReporting, am I missing something?

I was playing with the radReporting tool. I had a datasource with 1 master item, which has about 2500 child data items.
I was trying to generate a master / detail report with the telerik radReporting.

Here is what I have so far.
First of all - using their videos is a great help. I had everything I needed in order to start.
Second - the designer is really great. I am not designer and it really pisses me off when I had to do any kind of design but with the deep Visual Studio integration and all those little yellow overlap indicators even a guy like me can do the report design.

But then the ultimate test came - the speed.
I want to clarify that I am in the begining and I am more like rookie in the telerik reporting and the reporting at all so it may be my mistake and not their. But I did follow a video to show me how to do the master / details report and I feel I did everything as it was on the video so I was expecting some performance.

Unfortunatelly with the configuration above - 1 master item and about 2500 detail items I had to wait about 5-6 minutes for the report being generated as HTML in the report viewer.
It's OK, I can live with that. There is a lot of data, their matrixes are complex and it takes time to do all the calculations. So 5-6 minutes are OK. Then I selected Rich Text format from the export type dropdown to export my report to an RTF. I was expecting it to pass with the same speed or a bit slower but it took about 25 minutes to load. And sometimes the system was going in out of memory exception...

I wrote my own RTF epxort, which wasn't using telerik radReporting designer but some generations I did instead. I was the one to care about the overall layout. And guess what?
With the remakrs made above (that I need to manually create a class for the report and do the matrixes my way) it took about 10 - 15 SECONDS to load the report. This is about 150 TIMES faster.
When I managed to get a report from the telerik radReportViewer (I needed few tries until the server was in a good enough mood to provide me with one :) it was about 10 MB, while mine which is minimized and set up for just that layout was about 1 MB.

Again - I don't blame telerik as I am not quite sure if I did everything right when I was generating the reports with their designer. I am just learning how to walk in the field of reporting so I may be missing way too much things.
I can only check that my data is comming in 2-3 seconds (so it is not a slow DB issue I guess).
If I am right I may be having an idea that may be considered by them to speed up the performance. I am also now looking if I can connect to some event or override some method that will let me inject my reporting solution instead using their.
If I find a way to do this I will write another post.
If not - I will use telerik radReporting only to open the HTML report in the report viewer and replace the RTF generation with mine so the user can be happy.


Anyone who has some remarks / ideas / help is welcome to comment this post.

Jul 12, 2009

Nice example on the Sieve of Eratosthenes algorithm

On the following address you can find a good example on how the Sieve of Eratosthenes works on the first 100 numbers.

http://en.wikipedia.org/wiki/File:Animation_Sieve_of_Eratosth-2.gif

Brief Explanation of the picture:


1. Take the first number (2), it has 2 divisors - 1 and 2 itself. So mark all the numbers that divide by 2 (the red color).
2. Take the next number (3), that is not marked by the previous step (number 3). It has 2 divisors - 1 and 3 itself, mark all the numbers that divide by 3 (green color).
3. Take the next number that is not marked by the previous steps and check if it had exactly two divisors - 1 and the number itself (the chance this number to be prime number is bigger as all the numbers that may be divisors to this number are already marked). Mark all the numbers that divide by the number choosen.
4. Repeat step 3 until the number choosen is less than or equal to the limit you want to find the prime numbers for.


Note : I would like to excuse for my poor scientific english :).

Jun 3, 2009

Telerik Style Builder

It is available, yes.
You can test it on the following address:

Telerik Style Builder



I think this is a great service, that will help the collaboration between designers and developers a lot.
Currently only few of the controls have the fine tune interface implemented but I think it is a very good start.

radGrid - check if there was a row selected, before selecting another one [2]

The previous post on this topic was about pointing some solution, which doesn't always work.
I think I was able to identify the problem for this issue.

It is becasue the chain of events is the following when you select a new row:

1. RowDeselected.
2. RowSelecting.
3. RowClick.
3. RowSelected.

I am not quite able to find the logic here.
I think in normal english I should be able to say:

"I am clicking on a row."
"I am in a process of selecting a row." (if not canceled)
"I am deselecting the old row."
"I have selected the new row."

At least the RowClick in my opinion should be fired prior the events described above as it occurs before everything else. You are initiating the above chain of events by clicking on a row so all of them should follow in my opinion.

To me the fact that RowDeselected is before RowSelecting is not such a bad solution. I just can't get why the RowClick is between RowSelecting and RowSelected events.

Any clues?

Jun 2, 2009

radGrid - check if there was a row selected, before selecting another one.

Okay, we had the radGrid with AllowMultiRowSelection property turned off.
But we needed to check if there is already a selection in the grid (on the client side), then get the item and do some calculations.

So far so good.
But it appeared that it is very difficult to get the previous item selected in a grid when selecting a new one.

The OnRowSelected event as you may suspect is raised too late in order to get this information as the selection is already changed.
So I thought the OnRowSelecting event will be the best time to perform this.

Guess what? It wasn't. At least for me.
Each time I checked the

sender.MasterTableView.get_selectedItems().length > 0

The statement evaluated to false (which means to me that when the OnRowSelecting event is raised AFTER the selection is Clear()).

So I found a workaround to help myself persist the previous selected item of the grid:

var lastRow = null;

function RowDeselected(sender, eventArgs) {
lastRow = sender;
}

function RowSelecting(sender, eventArgs) {
if (lastRow) {
    
// There was a selection before we try to select. Do whatever you need here.
}
    
else {
    
// There wasn't any selected item, this is the first one.
     }
}

To me it seems that problems may arise. I will test some more to see for side effects and will report back.


Any comments are appreciated.

May 29, 2009

telerik radGrid - be careful with the virtual scrolling under Firefox

Again some issues under Firefox.
We have found a great example of how to populate on demand a radGrid (when scrolling grid scrollbar down to the end it will make ajaxRequest and ask for some more items to fill in the grid with).

We loved this feature and decided to incorporate it into one of our projects.
Unfortunatelly I discovered it won't work pretty well under the FireFox browser.
Let me briefly explain what does the code and then what is the problem, then I will suggest a simple fix.

Here is the demo:
http://www.telerik.com/help/aspnet-ajax/grdvirtualscrollpaging.html

Now, it shows you how to request the items and then reload the grid. So far everything works perfect.
If you however reach the end of the grid items (meaning you are at the last page, or the page count is 1), when you pull the scrollbar down to the bottom, firefox will execute the function which should pull some more records.
Then it will append them and.
So far everything is great!
But it will then magically decide to fire the OnScroll event once again, it will not pull any more records as you already have them in the grid.
And then it will append them.
Then it will again fire the OnScroll event ....
... then it will again fire the OnScroll event ...


Hm, sounds like endless trips to the server and back. That's what happened when we tested.

Now here is the code we had to achieve this:

<ClientEvents OnScroll="HandleScrolling" />

And here is the JS HandleScrolling function:

function HandleScrolling(sender, eventArgs) {
if (eventArgs.get_isOnBottom()) {
$find(
"<%= RadAjaxManager.GetCurrent(this.Page).ClientID %>").ajaxRequest(sender.get_masterTableView().get_name());
}
}

Now to be hones - I never have even dream of achieving such functionality with 4 lines of code. Kudos to telerik team for architecting the controls this way.
The fix to this issue also bring another feature ;) (not bad but good) - you will not need to go to the server when you already have all the records in your radGrid.

Here is the fixed version of the HandleScrolling javascript function:

function HandleScrolling(sender, eventArgs) {
if (eventArgs.get_isOnBottom() && sender.get_masterTableView().PageCount > 1) {
$find(
"<%= RadAjaxManager.GetCurrent(this.Page).ClientID %>").ajaxRequest(sender.get_masterTableView().get_name());
}
}

Did you spot the difference?
All i did was to add logical "and" operator to check if the masterTableView page is only one (which means that we don't have anything on the server which should be loaded on the client) and voilla!


Hope this helps someone!

Firefox with Plugins may lead to some problems with telerik controls

I had an issue with the telerik radTabStrip control.
It wouldn't switch the tabs. In some cases you are only able to navigate between the first and the last tab, in some cases you may not be able to change tabs at all.

I was very surprised as telerik is famous for supporting cross browser functionality for all the controls.
I thought the problem may be in my TV but wasn't able to find anything.
A collegue of mine also had some problems using firefox full of plugins with the telerik controls but we never thought the problem may be in the plugins.

In my case the problem was in Interclue add-on used to preload a page for you (when you point a link, the plug in will give you a screenshot of the page that stands behind the link).


So if you ever have problems using telerik controls under FF - please check your plugins first.

May 20, 2009

Some casing problems I experienced.

As far as I understand, the settings for the code format are in the following Visual Studio menu:

Tools -> Options ->Text Editor

There you have the ability to change things.
I was having some problems reguarding the way my markup is formatted (few of the tags are made lowercase when I hit CTRL + K + D (format whole document)).
So I think the settings for this should be under the HTML -> Format, or the whole path for the menu should be :

Tools -> Options ->Text Editor -> HTML -> Format

I then checked the "Server Tag:" dropdown. It says "Assembly definition", the other options are "As entered", "Lowercase", "Uppercase" but I don't like them :).
Now the issue comes when I have a radGrid with <ClientSettings> or <PagerStyle> sections. To me they must be in Pascal notation (as all other sections and properties), but when I hit CTRL + K + D they are re-formatted to be lowercase.
The issues may be in
1. The telerik assembly itself.
2. Some AddIn conflicts.

It is not a big issue, just decided to share with you.
Please share your thoughts if you faced such issues.

May 19, 2009

5 minutes C# - get windows special folders path

Just a two lines of code in order to retrieve the path to a special folder of your choice (My Documents, ApplicationData etc):

string strAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
DirectoryInfo diMyDocuments = new DirectoryInfo(strAppData);

Here is the Environment.SpecialFolder Enum:

Environment.SpecialFolder.ApplicationData - the data which some applications store about the current user (mostly used for personalized settings), this is for roaming users.
Environment.SpecialFolder.CommonApplicationData - Application data which is common for all users.
Environment.SpecialFolder.CommonProgramFiles - "The directory for components that are shared across applications"
Environment.SpecialFolder.Cookies - The folder where the user cookies are stored.
Environment.SpecialFolder.Desktop - The logical desktop.
Environment.SpecialFolder.DesktopDirectory - this is the directory which is used to store file objects on the desktop.
Environment.SpecialFolder.Favorites - Current user favorite items.
Environment.SpecialFolder.History - Current user Internet History.
Environment.SpecialFolder.InternetCache - Internet cached files.
Environment.SpecialFolder.LocalApplicationData - As the first one but for non-roaming users.
Environment.SpecialFolder.MyComputer - I'll let you figure this out ...
Environment.SpecialFolder.MyDocuments - I'll let you figure this out too ...
Environment.SpecialFolder.MyMusic - ... and this one ...
Environment.SpecialFolder.MyPictures - ... and this one ...
Environment.SpecialFolder.Personal - this one is more important, this directory is used as a repository for documents...
Environment.SpecialFolder.ProgramFiles - this one is clear, I believe
Environment.SpecialFolder.Programs - Contains user program groups.
Environment.SpecialFolder.Recent - Users most recently used documetns.
Environment.SpecialFolder.SendTo - This directory is used for the Send To > item in the context menu. By adding folders here, they will appear in the Send To -> item when you click on a file or folder.
Environment.SpecialFolder.StartMenu - Contains the Start Menu items.
Environment.SpecialFolder.Startup - The Startup group (Start Menu -> All Programs -> Startup).
Environment.SpecialFolder.System - The system directory (%Windir%\System32)
Environment.SpecialFolder.Templates - Document templates repository.


Hope I helped a bit.
Have a great coding.

telerik radGrid - select a row without using select links / buttons and allow it to postback

I was in a need to enable the user to select a row by clicking on it (not by clicking on some Select link or image or button).
I also wanted this click to postback so I can do some processing on the server side.

It is not so hard to achieve, but I was puzzled for quite a while so I decided to share it.

In order to allow the grid to select a row by clicking on the row, you need to add the ClientSettings to the radGrid and configure the following:

<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true" />
</
ClientSettings>

AllowRowSelect is the property to enable / disable row selection.
EnablePostBackOnRowClick will tell the grid to post back on row selection. It is really strightforward when you think of it, but checking so much properties / section to find out if the radGrid has the one you need is annoying sometimes.

Anyway, I am glad that the radGrid has this functionality built-in.

May 15, 2009

Visual Studio Tips & Tricks 1- Re-register the controls in the .designer.cs file (recovering .designer.cs file)

Okay, I suppose all of you know what the .designer.cs file is, but I will shortly explain...

When you add a control to the page (via the markup editor), this control is also registered in the .designer.cs file, so you can have a reference to it in the code behind class (.cs).
So if you have a page Test.aspx, you will have a group of 3 files in it:

1. Test.aspx - this is the markup code, containing HTML and ASP markup, defining the control, css and so on.
2. Test.aspx.designer.cs - the designer file, where all controls are registered as a variables so you can reference them,
3. Test.aspx.cs - the code behind where you add your code. There you can use the controls, referencing them by the ID you gave them in the markup.
What happens behind the scene is that each runat="server" control is registered as a variable in the designer class like this:

protected global::System.Web.UI.WebControls.DetailsView dvMine

I recently did the following mistake - after added a lot of controls, then a lot of code, and a lot of changes to other files, I accidently got the latest version of the designer file (from the source control) of one of my aspx pages. This way I was having the controls markup, but the control registrations were lost. I wasn't able to CTRL + Z until I got my things back as I had already closed / opened the Visual Studio few times.

As a result When I hit F5 to start in debug mode, I got about 20 compilation errors, stating that I am referencing objects that don't exist.
I didn't want to re-register those controls manually in the .designer.cs, neither to delete them in the markup and re-create them (thus registration in the .designer.cs file will be automatically created).

I was wondering what to do, so I finally got the idea. I hit CTRL + K + D (which should reformat your markup) and the missing controls were auto re-created in the .designer.cs file.

Hope this helps someone out there.

May 13, 2009

Nice tool to help you build IE ready sites

I found accidently this tool:



It can help you make your site run smoother under all versions of IE.
It's name is DebugBar go to the official site here.

May 12, 2009

MindFusion Diagramming Trick 1 - Create transparent brush

As I wasn't able to find a way to create a transparent brush for the mindfusion diagrams, I thought this may be helpful for someone struggling to do the same thing.
Here is a code you can use in the code behind to create a transparent brush (in the following example I am setting the brushes for all tables to be transparent).

Here is the magic line:

DiagramView1.Diagram.TableBrush = DiagramView1.Diagram.ScriptHelper.CreateSolidBrush(System.Drawing.
Color.Transparent.A, System.Drawing.Color.Transparent.R, System.Drawing.Color.Transparent.G, System.Drawing.Color.Transparent.B);

(it is kind of long but I think you will get the idea - i tought if I assign the Transparent color properties in the brush constructor, it may produce a transparent brush for me).

Note: this is for the code behind, not in JavaScript, but I think there is a way to do the same thing with JavaScript.


I think the System.Drawing.Color.Transparent.A is the field that makes the magic, this field carries the alpha channel value.

MindFusion diagramming Part 5 - Changing pen colors with JavaScript (ClientMode)

In order to change the pen (borders) of a shape you first need to instantiate a pen class.
It is in the com.mindfusion.diagramming namespace (Java class).

So you need to do the following:


var pen = new Packages.com.mindfusion.diagramming.Pen();


Now, to set the color of the pen we need a java.awt.Color instance. Luckily there are static properties which will return a color instance for the most used colors. See what I mean:

var blackColor = Packages.java.awt.Color.black;
var greenColor = Packages.java.awt.Color.green;

Now, to set the pen color to the color we will use setColor() method:

pen.setColor(Packages.java.awt.Color.green);

To set the width to be 1 pixel we need to use the floating point 0.1, not 1:

pen.setWidth(0.1);

Here is the function return a pen with 1 px border and green color:
function getGreenPen()
{
var pen = new Packages.com.mindfusion.diagramming.Pen();
pen.setWidth(0.1);
pen.setColor(Packages.java.awt.Color.green);
return pen;
}

You can now use an instance of a shape and set its pen. For example, you can use the OnNodeActivatedScript and add the following function:

function onNodeActivated(diagram, args)
{
var node = args.getNode();
node.setPen(getGreenPen());
}


Hope it helps a bit.

Apr 30, 2009

Instantiate Java class in JavaScript

I know I am mostly writing about C# and .NET and so on and you may wonder way do I write about java but I found this interesting and useful even in .NET projects.
I was playing with the mindfusion diagram latelly (you can check my posts under the Mind Fusion Diagramming in the blog categories) and found myself in a situation where I needed to instantiate a class from the mindfusion package (i think it was table cell but this doesn't matter right now).

So in order to instantiate Java class in JavaScript you may do this from the Packages object.
For example if you have a class like:
java.MyClass

you can instantiate it this way in javascript:

var myClass = Packages.java.MyClass();

Let's suppose the class has Name property, you can call it like this:

alert(myClass.Name);
// If the class has a property "Name", call it ...

Hope this helps somebody out there...
So long and thanks for al the fish ;)

NOTE : I haven't tested this under browsers other than Internet Explorer 7. Hopefully it will work ...

Apr 23, 2009

Operation could not be completed message when trying to open Linq to SQL (dbml) designer

That was really strange.

The annoying Operation could not be completed error message appeared each time I tried to open the dbml designer.

I did some search and found that I need to start the Visual Studio 2008 Command prompt and type the following command:

devenv/resetskippgs

But this didn't helped a lot. The annoying message was still appearing.
Then I found something which made me laugh. It was so unexpected...
If you had the same problem and the devenv/resetskippgs couldn't resolve it, try going to Control Panel -> Administrative Tools -> Event Viewer.
Select the Application node and right click it. Then delete all events.

This would hopefully resolve your problem.

Funny isn't it?

Apr 16, 2009

To shim or not to shim, or why telerik radContextMenu will not show over applet in FireFox?

It was a nightmare last night.
I have a Java applet in my pages and needed to display telerik context menu over it when the user right clicks it. So far so good, the component had nice JS events to attach to. I was able to atach to its Click event, find the telerik radContextMenu and call it's showAt(x, y) method. It worked like a charm. I was very happy to have done this in less than 20 minutes as I know mixing different technologies often cause headaches.
I started the project in IE 8, worked just as expected ...
... until I run it in FireFox to see how it looks there.

The telerik radContextMenu wasn't displaying. It take me about an hour to understand that it is displaying but under the Applet DOM object (an hour is relatively fast for me ;). No problems, I will kick some z-indexes and everything will be just fine.
This didn't worked either. So I googled. And google told me what I consider one of the worst news a developer can read - the Applet object is something like the browse button - it exist there and only there and only the way it is and the way the browser developers decided. Or in other words - it will be on top of everything no matter what z-Index will you put there ...
I decided to search for some hacks to apply. And guess what? I found. And guess what the hack is? (it is known as "shim IFrame" or "Shim" or "IFrame shim" not quite sure)
1. You add an IFrame the size of the div you will display over the applet, the IFrame is the only element which respects the z-Index style ...
2. Then you put a div with greater z-Index over the IFrame and this DOM mess should fly ...

Do I look kind of angry? That's ok, because I want to look like I am angry, because I am ...

3-4 hours and still couldn't make it work. I suppose this may have something to do with the layout of my page. When I have some spare time I will try to fix this thing.
One more time - this works perfectly in IE ...

And one more time - it is not Telerik fault too ...

Apr 13, 2009

MindFusion diagramming Part 4 - Cancel link creation between specific kinds of shapes

You can check between what kind of shapes the link is created and remove it if you need to do so. I will give you an example on how to cancel the connection between Actor and Actor shapes.

First - add LinkCreatedScript to your diagram and make it point a JavaScript function, here is mine declaration:

    
<ndiag:DiagramView ID="diagramView" runat="server" Style="left: 0px; width: 800px;
        
position: absolute; top: 0px; height: 505px" Behavior="DrawControls" BackColor="White"
        AllowInplaceEdit="true" LinkCreatedScript="onLinkCreated" />

Now add the onLinkCreated function in the page head :

  
<script type="text/javascript">
     function onLinkCreated(diagram, args) {
        
var link = args.getLink();
        
var shapeOrigin = link.getOrigin().getShape();
        
var shapeDestination = link.getDestination().getShape();
        
if (shapeDestination.getDisplayName() == 'Actor' && shapeOrigin.getDisplayName() == 'Actor') {
           diagram.getLinks().remove(link);
           alert(
'Cannot crate link between ' + shapeOrigin.getDisplayName() + ' and ' + shapeDestination.getDisplayName());
        }
     }
  
</script>

1. What we did is - we get the link that was just created from the args.
2. We get the Origin and Destination shapes from the link.
3. We then checked their display names and verify they are Actor and Actor.
4. We asked the diagarm object to remove a link, to be more specific - our link, the one that was just created.


I think there may be more elegant ways to achieve this, but currently this is the only I could think of.
Hope it helps somebody out there ...

MindFusion diagramming Part 3 - adding Overview control to the form.

Here is the third part of the tutorial.
Adding overview isn't realy a big deal. You only need to add the following markup in your page (the solution we created in the previous two samples):

<ndiag:Overview Style="position:absolute; top: 320px; height: 180px; left:810px; width:160px;" runat="server" DiagramViewID="diagramView" />

The thing you need to obey here is to give the diagram overview control a correct DiagramViewID property, which should be the ID of the DiagramView control you have on your form.

Here is what we have so far (the tree tutorials combined):


Apr 6, 2009

MindFusion diagramming Part 2 - adding shapes list

In the previous example, I show you how to add simple diagram to your web forms. Now I am going to show you how to add a simple shapes list, containing all the shapes that comes with the MindFusion product.

It is very simple, actually, only 1-2 lines of markup:

<ndiag:ShapeListBox ID="shapeList" runat="server" Style="left: 810px; width: 160px; position: absolute; top: 1px; height: 320px; background-color: white" />

This should be added to the code you built in the previous example : http://donchevp.blogspot.com/2009/04/mindfusion-diagramming-part-1-adding.html.

Let's see what we got now:





MindFusion diagramming Part 1 - adding simple diagram to the form.

We worked quite a bit with this product and I must say it is a good one.
It can be used to easilly draw diagrams. It has a lot of built-in shapes and a designer to draw new one.
Let's add a digaram on the form.
First of all, download the product from here : http://mindfusion.eu/download-netdiagram.html and install them.
Add the following lines to your web.config:

In page / controls section, add the following:
<add tagPrefix="ndiag" namespace="MindFusion.Diagramming.WebForms" assembly="MindFusion.Diagramming.WebForms"/>

Then add reference to :
MindFusion.Common
MindFusion.Diagramming
MindFusion.Diagramming.WebForms

Open your page and add the following markup to create a diagram:

<ndiag:DiagramView ID="diagramView" runat="server" Style="left: 0px; width: 800px;
position: absolute; top: 0px; height: 505px" Behavior="DrawControls" BackColor="White" AllowInplaceEdit="true" />

I added few additional properties to decorate and set behaviours. We will discuss them later. I also allowed InplaceEdit, which means that when you double click on a shape, you will be able to edit the text.
Finally, copy the JDiagram.jar into your root directory (you can place it in a directory of your choice, but you will need to set the
JarLocation property to point to this file.

Let's see what we did so far:





Pretty nice for 1 minute of work, huh?
There is more ;). This product seems to come from Bulgaria, so there will be no problem with it :).

Make telerik controls work with IE 8

A friend of mine told me she has problems running telerik controls under Internet Explorer 8. I recalled reading somewhere there is a tag you need to add to your page in order to force IE 8 behave like IE 7 (where telerik controls work great), I did some search and here is the tag:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

Add it to your pages head section and you should be ok with telerik controls.

Edit: as Veskoni commented out, telerik controls are fully compaitable with IE 8 since Q1 2009 SP1, so it will be a lot better to upgrade to that version (or above).

Using JavaScript functions over a string in C#.

I needed to find a way to invoke the real escape / unescape javascript function over a string in C#.
It appeared to be easy to do so by using the Microsoft.JScript namespace classes.

Add a reference to it and then you can simply do something like this:

string escaped = Microsoft.JScript.GlobalObject.escape("This will be JS escaped for sure!");

"escaped" variable will then have the value of :

This%20will%20be%20JS%20escaped%20for%20sure%21

I am still very new to this namespace, there were a lot of things to find out there ...

Check it out. It may appear to be very useful for those of you who are processing JS on-the-fly...

Mar 31, 2009

ASP.NET PRO readers choice awards

You can vote for ASP.NET readers choice awards here:

http://www.aspnetpro.com/awards/default.asp

give a hand to your favorite components, controls, utilities, editors and so on!

Nice UML Diagram

Here is a very nice and informative UML diagram I created while I was bored ;)






Just kidding :)

Removing the left "placeholders" in telerik radMenu (where the images should be)

I needed to remove this placeholder as our menu was without icons. First I thought it is impossible, but then I found very helpful thread in telerik forums.
It says you need to apply the following CSS to your form:

.RadMenu_[SkinName] .rmGroup .rmLink
{  
  
padding-left: 0px !important;  
}  
    
.RadMenu_[SkinName] .rmGroup .rmLink .rmText
{
  
padding-left: 5px !important;  
}  
.RadMenu_[SkinName] .rmGroup
{
  
border: 1px solid #979797 !important;  
  
background: #f0f0f0 !important;
}

Where [SkinName] stands for the skin of the menu.



By the way - it happens this to be my post #100! ;). Hope I helped someone with all my posts :).

Mar 23, 2009

Read various elements from the connection string.

I saw a question in ASP.NET forums. There was a guy asking how to extract the Username and Password from a connection string, stored in the web.config.

I recalled doing something like this but was not able to recall which class I used.

After about a day another guy posted an answer on this question - the class was SqlConnectionStringBuilder. You can use this class to easilly manage SqlConnection string properties such as DataSource, Username, Password etc.

Here is my post on how to get a connection string from the web.config:
Read connection string from web.config

Here is some more info about SqlConnectionStringBuilder from MSDN:
SqlConnectionStringBuilder class

Combining both resources will help you manage your connection strings easilly.

Mar 18, 2009

Read the connection string from the web.config file

Here is this code, it is replicated bilions of time in Internet, yet I fill obliged to paste it here...

This is the first way, which I took from Microsoft.
It checks if there is a connection strings section, then it checks if the count of connection strings is more than zero:

        System.Configuration.
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
        System.Configuration.
ConnectionStringSettings connString;
        
if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
        {
           connString =
             rootWebConfig.ConnectionStrings.ConnectionStrings[
"MyConnectionString"];
          
if (null != connString)
           {
            
// Do something with the string, for example - create SqlConnection object:
             SqlConnection con = new SqlConnection(rootWebConfig.ConnectionStrings.ConnectionStrings["MyConnectionString"].ConnectionString);
           }
        }


This one is the short line (no checks if anything fails, after all if you don't have a connection string in 99% of the scenarios you will want to have exception rised).

string cString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["mine"].ConnectionString;

Mar 16, 2009

Fixing sup - sub for radEditor example

I made few posts on telerik radEdit. There was something I considered a small issue. Which actually may appear not to be issue, but to me it was.
So i decided to get a bit more familiar with the telerik radEdit client side scripting API (thanks to Tervel for his valuable comments).
So the problem for me was that if you type normal text, then click on the sub icon to make index and then click on the sup to raise to the power of something, the result was a text on the same level as the normal text.

Digging a bit in the client API of radEdit I found that you can obtain the editor undo manager. You can also fire commands so the problem should be easy to fix (I should mention here that I am really happy with the architecture of radEditor, it has everything a developer may need in order to extend the control to fit his / her needs.

Ok, now to the problem. I thought all I need to do is to make radEdit check if a sup is selected when you click sub and switch it off if so. Same thing should happen for sub. Luckily radEdit has client side event handler
OnClientCommandExecuting which is rised prior command execution. So you will need an event handler like this:

OnClientCommandExecuting="cmdPreExec"

Having the eventhandler attached, you need to write a function to check if the user clicks either sup or sub. Then to check if the other command was recently fired, if so - it will fire it again to switch it off. Here are the functions:

    
function cmdPreExec(editor, args) {
        
var strCommand = getLastCommandReal(editor);
        
if (strCommand) {
           cmd = args.get_commandName();
          
if (cmd == "Superscript") {
            
if (strCommand == "Subscript") {
                editor.fire(
"Subscript");
             }
           }
          
if (cmd == "Subscript") {
            
if (strCommand == "Superscript") {
                editor.fire(
"Superscript");
             }
           }
        }
     }

    
function getLastCommandReal(editor) {
        
var manager = editor.get_commandsManager();
        
var commands = manager.get_commands();
        
var lastCommand = null;
        
        
if (!commands) {
          
return null;
        }
        
else {
          
for (i = commands.length - 1; i > -1; i--) {
            
if (!commands[i]) {
                
return null;
             }
            
if (commands[i]._title != "Typing...") {
                
return commands[i]._title;
             }
           }
        }
     }

The second function is to get the last command name from the undo manager, excluding the "Typing..." which is also registered there.
Please note that I see some potential problems which I haven't considered yet, you may have some side effects.
This post is more to show you how to work with some of the client side objects / events and methods than to use in real life.

Actually I am 99.99999 % sure there will be a problem with this code ;). This code was written in abouth 15 - 20 minutes so there should be a bug for sure. I can think of at least two bugs ;).

Here is a video on how this code performs for me:



Mar 12, 2009

tinyMCE has the sup - sub issue too

Just to inform you that tinyMCE cannot handle the sup / sub correctly also.

Here is a video:

Mar 11, 2009

Telerik radEditor, it is not a bug... but wait ...

Okay, yesterday I wrote a small post showing a small malfunction in telerik radEditor.

The problem was using Sub - Sup...

I got a comment from Tervel - a guy who works on the editor.

As the comment is in Bulgarian I will add a free translation in english (I will ommit hi, pavel and so on and will translate only the things that have relation to this post).

"The way you are changing the commands, it seems to me that the problem is in the browser RichText edit engine.
Sup and Sub commands are sent from telerik radEditor to the browser for further processing
." (I think there was something like execCommand("commandName") in JavaScript, this is what he is talking about.

"You can check other editors to verify this behaviour. Strictly, I don't think this is a bug, IE does include sup / sub tags in the context of the current tag, not as a parrent element of the current tag. The result is logical and correct. Whether this is intuitive behavior is another question offcourse. By the way, I think it is."

So here is what I think:
I think that Tervel is right - this is the behavior of IE. And the behavior of FireFox. I checked it too. And this is not a bug.
Yes it is not very intuitive.
Yes it takes another click.

But to me this behavior can be fixed in Telerik making their editor even more intuitive and easy to use.
I don't see any situation in which one would like to have both : sup and sub tags selected. Why would we do that?

Here is what I think can be done in the editor, if someday the guys have some spare time:

Click on sup scnario:
1. Check if the sub command is added (probably it will be but just check for sure).
2. If yes - unselect it.

Same can happen for sub.

Here is a video in which I am trying to input formula with two variables:



And last but not least - this is not an issue for the editor. I just wanted to share my opinion as Tervel left comment.

And once again - we love radEdit ;).

Mar 10, 2009

Small bug in telerik radEditor

This one I found while I was playing with the telerik radEditor:



I don't think it is a big deal. You can live with it. Still I consider telerik radEditor one of the best web editors available.

Feb 20, 2009

Microsoft SQL Management Studio - Saving changes is not permitted error message.

If you are using Microsoft SQL Management Studio 2008 you may have across this message while trying to edit a table in database:

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.



It is so self exlpanatory still a lot of people have problems to solve it.



You can follow the steps bellow to fix this:

Select "Options" from the Tools menu:



Then Uncheck the "Prevent saving changes that require table re-creation" option and click OK:

Jan 19, 2009

MCTS : Windows applications achieved today!

I got this badge officially today:



I am already entitled as a MCPD: Web Applicaionts but I wanted to achieve the MCPD : Enterprise Developer also so I needed to pass the windows thing.
In order to get there I only need to pass one more exam - the Distributed Applications exam.
Wish me luck!

Jan 11, 2009

Test images


Few pictures ...


Jan 9, 2009

Your site suddenly stops to save cookies?

I am currently developing an application. One of the requirements is the user to be able to change the language. I added a dropdown to hold the languages. Upon change a cookie is sent to the client with the language selected so when the user visits the site next time his / her language can be auto adjusted. It worked as a charm until today.

It suddenly stopped. I was wondering who to blame, when I saw a small baloon tooltip on the taskbar. It said I am running out of disk space ;).
I deleted my cookies in IE and everything started working correctly again.

(I just wonder if the disk space was the reason why under Firefox worked fine?)

Dec 18, 2008

Telerik RadSkinManager doesn't persist the Skin.


If you programatically change the Telerik RadSkinManager Skin property it won't get persisted in the key you added.
This is because probably in telerik asumed if there is no skin chooser the skins won't change and will be loaded from the markup. It is not a bad decision.
However, you may find yourself in need to programatically change the skin and want it persisted.
To do the things tidy I did a small code to persist the skin where it should be persisted.
Here is the code:
        
switch (rsMgr.PersistenceMode)
        {
          
case RadSkinManagerPersistenceMode.Cookie:
            
// Create a cookie to persist the skin selection for the session only:
             HttpCookie cookieSkin = new HttpCookie(rsMgr.PersistenceKey, rsMgr.Skin);
             Response.Cookies.Add(cookieSkin);
            
break;
          
case RadSkinManagerPersistenceMode.Session:
            
// Create a session variable with the same name:
             Session[rsMgr.PersistenceKey] = rsMgr.Skin;
            
break;
          
case RadSkinManagerPersistenceMode.ViewState:
            
// View state variable:
             ViewState[rsMgr.PersistenceKey] = rsMgr.Skin;
            
break;
        }

where rsMgr is RadSkinManager.
Now you may paste this code in a method and call this method after you programatically assign skin to the manager. I needed this because I wanted to allow the user to change from some of the skins (not all of them) I couldn't find a way to only hide few skins and display others so I can use the standard functionality of the SkinChooser proerty so I added my own RadCombobox with the skins I want displayed.

Hope this helps someone out there...

Dec 14, 2008

Nice little tool to help me with twitter.

I created a small twitter software what it does is to check each hour if I am listening to Winamp, get the song if possible and write it in twitter for me and the people who are eventually interested in what I am listening.
Here is the deal:



You can download it from here:
TWamp - Nice little twitter software

You can follow me on twitter from the following url:
My twitter profile

Please note: TWamp isn't very user friendly. You need to get along with it in order to use it ;).

Dec 2, 2008

Understanding the recursion.

Here is the golden rule to understand the recursion:
"In order to understand recursion one must first understand recursion."

Dec 1, 2008

Microsoft Office Word automation in C# - How to add table to the document?

The following C# code will create a new document, add a table to it and ask the user to save it. Document will look like this:



The following code will add a table in word and then ask the user to provide a filename to save the document:
        Microsoft.Office.Interop.Word.
Application app = new Microsoft.Office.Interop.Word.ApplicationClass();
        app.Visible =
false;

        
object start = 0;
        
object end = 0;
        
object oNull = System.Reflection.Missing.Value;

        
Document doc = new DocumentClass();
        doc = app.Documents.Add(
ref oNull, ref oNull, ref oNull, ref oNull);

        
Table tbl = doc.Tables.Add(doc.Range(ref start, ref end), 10, 2, ref oNull, ref oNull);
        
Random rnd = new Random();
        
for (int i = 0; i < 10; i++)
        {
           tbl.Rows[i + 1].Cells[1].Range.Text =
"Run# :" + ((int)i + 1).ToString();
           tbl.Rows[i + 1].Cells[2].Range.Text =
"Value :" + rnd.Next(0, 2000).ToString();
        }

        
object oFalse = false;
        app.Visible =
true;
        
try
        {
           doc.Save();
        }
        
catch (Exception ex)
        {
          
if (ex.Message.ToLower().IndexOf("command failed") == -1)
           {
            
throw ex;
           }
        }
        app.Quit(
ref oFalse, ref oFalse, ref oFalse);

What we done is to create a new document, a new table, and fill the table with random values.
Seems very easy but not quite sure how well document :).

Nov 25, 2008

ASP.NET ProgressBar to show percentage

I did this today during my lunch time break:




(sorry about the bad quality but couldn't figure out how to ask YouTube not to resize
it :).

It is ugly and unoptimized yet but I hope I will be able to refactor it soon and make it as a user control.

Another post to follow when this happens.

Nov 20, 2008

Cannot have multiple items selected in a DropDownList. Why is this ASP.NET / C# exception rised?

This is a common exception. It happens when you do something like:

        
ListItem li1 = new ListItem();
        li1.Text =
"Item 1";
        li1.Value =
"id1";
        li1.Selected =
true;
        
ListItem li2 = new ListItem();
        li2.Text =
"Item 2";
        li2.Value =
"id2";
        li2.Selected =
true;
        ddTest.Items.Add(li1);
        ddTest.Items.Add(li2);

Let's explain what is going on.
We created a ListItem, set its name and value and make it to be selected.
Then we created another ListItem, again set its value and name and set it to be selected.


When we add both ListItems the DropDownList confuses about which one should be selected and throws an exception. But why?
Because there is another control - ListBox, which allows multiple selection. If we create a ListBox on the form and add the following code in the code behind:


        
ListItem li1 = new ListItem();
        li1.Text =
"Item 1";
        li1.Value =
"id1";
        li1.Selected =
true;

        
ListItem li2 = new ListItem();
        li2.Text =
"Item 2";
        li2.Value =
"id2";
        li2.Selected =
true;

        lb1.SelectionMode =
ListSelectionMode.Multiple;
        lb1.Items.Add(li1);
        lb1.Items.Add(li2);

We will run with no errors and both items will be selected. The problem with the DropDownList control is that shares almost the same functionality with the ListBox and for that reason they both inherit the same base objects.

But the DropDownList doesn't have the ability to display multiple items so ASP.NET team decided to throw an exception when such situation occurs.




This can be confusing in more complicated code, but it is definatelly better than selecting the last item which was marked as "selected" or the first one or something like that.
Luckily there are safer ways to select an item without having to worry if there is already selected item or not.

You can use DropdownList.SelectedIndex or DropdownList.SelectedValue properties to mark selected item in a safe manner. So if in the firs example we wanted to select the item with id2 we can use the following code:

        
ListItem li1 = new ListItem();
        li1.Text =
"Item 1";
        li1.Value =
"id1";

        
ListItem li2 = new ListItem();
        li2.Text =
"Item 2";
        li2.Value =
"id2";

        ddTest.Items.Add(li1);
        ddTest.Items.Add(li2);

        ddTest.SelectedValue =
"id2";

I commonly use this as in most cases I know which value should I select but don't know which index it has.
Now, there is a situation in which you may want to select by index and this in my imagination is the following situation:
Imagine you have the above DropDownList but you want it to be optional. This means that you need to have an item with empty value or value that means "null" to you. Imagine that this value is already inserted in the DropDownList. You know it will always be the first item. Here is the snippet:

        
ListItem liNull = new ListItem();
        liNull.Text =
"-- Please Select an Item --";
        liNull.Value =
"";

        
ListItem li1 = new ListItem();
        li1.Text =
"Item 1";
        li1.Value =
"id1";

        
ListItem li2 = new ListItem();
        li2.Text =
"Item 2";
        li2.Value =
"id2";

        
// Someone selected item in the code:
        ddTest.SelectedValue = "id1";

        ddTest.Items.Add(liNull);
        ddTest.Items.Add(li1);
        ddTest.Items.Add(li2);

        
// We will select the first one which is "-- Please Select an Item --"
        ddTest.SelectedIndex = 0;

But in such cases we can take advantage of the default DropDownList behaviour (the DropDownList will select the first item if there are no items selected explicitly). So if you need the first item selected you can simply clear the selection and ASP.NET will select it for you. But how?
By using the ClearSelection() method. It does what it says - it clears the selected item.
Here is the last snippet:

        
ListItem liNull = new ListItem();
        liNull.Text =
"-- Please Select an Item --";
        liNull.Value =
"";

        
ListItem li1 = new ListItem();
        li1.Text =
"Item 1";
        li1.Value =
"id1";

        
ListItem li2 = new ListItem();
        li2.Text =
"Item 2";
        li2.Value =
"id2";

        
// Someone selected item in the code:
        ddTest.SelectedValue = "id1";

        ddTest.Items.Add(liNull);
        ddTest.Items.Add(li1);
        ddTest.Items.Add(li2);

        
// We will be sure that everything is clean
        // and will expect ASP.NET to select the first item
        // by default:
        ddTest.ClearSelection();