CoderBlog.NET
Tengiz Tutisani's blog.

 
Useful Links:
 
LanguageBox 
 
Language

 
SearchBox 
 
 
ArchiveBox 
 
Archive
<February 2012>
SuMoTuWeThFrSa
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
 
CategoriesBox 
 
Categories
  ASP.NET (5)
  Ajax (1)
  C# (7)
  Common (1)
  HTML (3)
  JavaScript (5)
  Products (1)
  SEO (1)
  SQL (1)
  Visual Studio (1)
  Windows (1)
 
FriendSitesBox 
 
Friend Sites
  AdMoney Project
  Cайт о гитаре и музыке!
  Design Studio IMAGINE
 
CustomContentBox [1] 
 



 
 
ExecuteScalar() result cannot be converted as expected
Strange results
Posted By:   tengo
At:   4/30/2009 9:55:00 AM
 

Colleague wrote a little method in C# code, where he created SqlCommand object and assigned to it's CommandText property as shown:

command1.CommandText = "select dbo.fn_GetValue(‘parameters')";

As you understood he tried to select a result of the database function. The function returns value of type bit. After invoking ExecuteScalar, command returned an object, which could not be converted to the bool type as expected. Strange!
As I saw execution returned value as a string with the exception that added an empty spaces in the end. So, I advise you to avoid using such kind of commands, use execution of stored procedures instead. In that case the result will be as expected.

BTW, I found some not very good solution of this problem also. Just change a command text as followed:

command1.CommandText = "select cast(dbo.fn_GetValue(‘parameters') as bit)";

Everything will work, but again, I would use stored procedure instead, and of course, in case of stored procedures, you must specify the correct CommandType property value of the SqlCommand object. The property value must be System.Data.CommandType.StoredProcedure instead of System.Data.CommandType.Text.

I recommend visiting MSDN library article which explains details of working with the SqlCommand object shipped with Microsoft .NET framework, in particular on how to Set and Get Parameters for Command Objects.

That's all for today.

Don't forget, to have a rest is as important as to make a good job.


Filed Under:   C# | SQL |
Post Tags:   csharp | execute | function | object | procedure | result | scalar | sql |
  Comments [0]



 
 
How to get username in domain
ASP.NET How-To Series continue
Posted By:   tengo
At:   4/29/2009 6:00:00 PM
 

I was asked how to get username in domain using ASP.NET.
My answer was:

string user = Page.User.Identity.Name;

As it didn't work, I tried to change it to the second version:

string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

The second version did not work as well. Then I continued seeking for the problem. Finally I found a checkbox in the property pages of the web site that was the project published under. Check box was saying that anonymous access is allowed. Turning off the checkbox made both versions work correctly.
Also have in mind, your web configuration file must contain the following:

<system.web>
<configuration>
<identity impersonate="true" />
</configuration>
</system.web>

That's all.


Filed Under:   ASP.NET | C# |
Post Tags:   aspnet | csharp | domain | identity | page | user | username | windows |
  Comments [3]



 
 
Error "The path is not of a legal form." - Solution
Make your life easy
Posted By:   tengo
At:   3/17/2009 12:45:00 PM
 

I am working in the software company. We are developing a solution of a size larger than average. Solution includes more than 30 projects; each project contains a lot of C# forms. When opening the designer this error was shown almost always:

"The path is not of a legal form."

Today I decided to solve the problem globally, searched for the answer through internet, and found posts from Microsoft employees.
Here is the solution:

Go ahead and check your solution for dead references. You can see it in the solution explorer of visual studio; references are listed in the References folder under the project root. Dead reference is marked using yellow exclamation mark in the solution explorer. Just select the dead reference and press delete. Rebuild the project for any case and that's all.

Now any of the form's designers is opening with a first try.


Filed Under:   C# |
Post Tags:   csharp | design | designer | form | project | solution | studio |
  Comments [1]



 
 
DataGridView adds extra columns after specified columns
How to solve the issue
Posted By:   tengo
At:   2/24/2009 10:50:00 AM
 

In Visual Studio 2005, there can be found a lot of useful components on the toolbox. One of them is DataGidView.
When placing it on the form, you can define the columns collection for displaying your data. This can be done through the Columns collection from the property grid, using your C# code, that accesses this property programmatically, or using a smart tag of the DataGridView. Smart tag can be accessed pressing a little triangle button on the top right corner of the component in design view. After opening the smart tags panel, click on the link button with text ‘Edit Columns...'
Each column has several properties, such as DataPropertyName - the name of the property from datasource object's current item, value of which will be displayed on the column; HeaderText - text that will be displayed as the header text of the column; ColumnType - the type of column. This property can have one of the several values. It indicates if your column is a simple text column, checkbox column or something else. For example you could use the checkbox type of column for displaying the Boolean value; also you can find the column property ‘DefaultCellStyle', where you can define several properties that the cells of a given column will share, between them, a very useful property ‘Format' - the format string that will be applied to the values before displaying them in the column cells. For example you could use the format ‘d' for displaying the DateTime values using the short date format.

Now let's talk about the problem that occurs if your datasource object has more properties than you want to display in your DataGridView and thus you haven't defined special columns for them. There is no way to tell the DataGridView not to display those additional columns from the design view. Though they are not visible in the design view, they will be displayed at runtime.
To solve this problem you need a property ‘AutoGenerateColumns' to be set to false. By default its value is true. This property is not accessible from the design view.
For this purpose you can assign the false property in the constructor of your form like this:

public Form1()
{
InitializeComponent();

dataGridView1.AutoGenerateColumns = false;
}

That's all. Hope this post about DataGridView will be useful.


Filed Under:   C# |
Post Tags:   columns | csharp | datagridview | datasource | form | format |
  Comments [5]



 
 
How to assign navigate URL to the ASP.NET calendar Day clicks
Tricks with ASP.NET calendar control
Posted By:   tengo
At:   2/16/2009 3:50:00 PM
 

I decided to make a next step in researching the ASP.NET calendar control. I've used it several times, but never could find the way how I could change the navigate URLs that is navigated when the user clicks a day on the calendar control.

One decision that I have seen, is to create a user control for calendar, and then hard code all the logic in it. It's the same as to create a bicycle when it already exists. No, thanks.

And this time I just started searching through Google. Found something. One guy wrote on his blog, how to change background colors of the cells of calendar control. Really good work. The only thing you have to remember is a DayRender event of calendar control.
But one moment, the author of that blog shows us how to handle that event and write our logic. But it all's done outside of the control. When should we do so and when should we inherit from the control? Let's think.
Few weeks ago I have created a user control, which contains a calendar control, in this case sure, I really prefer to write the logic of the event handling outside the calendar control, because, anyway, this logic is placed inside the user control. I think it's a good manner to have all the logic inside the object that can be used repeatedly on your site and anywhere in the project, or other projects.
But if you don't need a user control, then I advice you to create a class, inherited from System.Web.UI.Calendar control class, and write all the logic inside that class. In other words you will need to override a method called OnDayRender. Then, in your page you will need to add a <%@ Register%> directive. And then, the most pleasant thing: change <asp.Calendar> tag with your one. I mean, "Register" directive requires you to register some TagPrefix that is associated with a namespace containing your calendar control. For example, if you created a class MyCalendar and it's contained in the namespace MyControls, then you will explicitly register that namespace with some TagPrefix. Let's say that tag prefix is "mc", then you will have to change <asp:Calendar> tags with this one "<mc:MyCalendar>". Of course you need to change only those calendar controls, which you want to extend with your logic, written in your code.

One interesting note: it doesn't break a design mode of your pages.
That means, All's OK!

... And let's return from the off-topic. I hope it was at least interesting.
We already understand where to handle the DayRender event.

DayRender (or OnDayRender) method has very useful parameters. I will consider an overridden method here; the same can be said about an event handler that can be implemented outside the class inherited from the Calendar control class.

protected override void OnDayRender(TableCell cell, CalendarDay day)

This will be the title of your method. You would think that our solution is under using variable day. I would think so also. But no. A day variable just contains information about a day that is to be rendered. You can change its properties, such as day.IsSelectable etc. But nothing to overwrite the navigate URL of the day. It's possible to do using cell variable. In this case, cell is a simple table cell. A calendar in general, is a table, which contains cells of course. cell variable is empty on this step. But one interesting thing is, if you assign something to the cell.Text property, it will remain it's value, and will not become something like just clickable number.
Let's take a look on my code fragment:

protected override void OnDayRender(TableCell cell, CalendarDay day)
{
if (day.IsSelectable)
{
cell.Text = string.Format("<a href=\"{0}.aspx\">{1}</a>", day.Date.ToString("dd-MM-yyyy"), day.DayNumberText);
}
}

It's clear, I just want to have a clickable numbers, but not with the navigate URLs like "_doPostBack..." etc etc. I want it to contain clear URLs, those are combinations of date and extension ".aspx". Why I needed it? Just to make a calendar control for viewing archive for some date.
That's almost all.

One moment that you would be interested in:
If you want to add some dynamic, JavaScript content to the cell, you can use it's Attributes collection. For example to make a background color yellow on mouseover, you would write something like this:
cell.Attributes["onmouseover"] = "this.style.backgroundColor='yellow'";
etc.

Have a good day!


Filed Under:   ASP.NET | C# | JavaScript |
Post Tags:   aspnet | calendar | csharp | javascript | render | url |
  Comments [0]



 
 
Converting from string to int
Why not working (int)stringVariable?
Posted By:   tengo
At:   2/15/2009 11:15:00 AM
 

Converting from string to int
Why not working (int)stringVariable?


I was asked with this question. Well, I think there are a lot of professionals who will not even think about it, but my suggestion is, if there's a person who can ask such a question, there must be a person, who will find a time and answer it.

OK, I always love to answer using my own words, not the copy-paste magic from MSDN library (by the way, it can be found at http://msdn.microsoft.com).

In C#, the type can be explicitly converted to the type of the same type - a little complicated sentence, right? But the truth!
In this case, type int is a value-type, and type string is a reference-type. To convert from one to another, you must use static method int.Parse(string).

But be careful, it may throw an exception. If you want to handle the exception, you must use try-catch statement, or, a method that is more informational about parsing results, and as I think, more useful: int.TryParse(string, out int).
Let's consider next code:

string s = "123";
int number = int.Parse(s); //all's ok

s = "123a";
number = int.Parse(s); //exception is thrown!!!

//solution is:
//1)
try
{
number = int.Parse(s);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message); //or some other code to handle the exception
}

//2)
if (int.TryParse(s, out number);
{
//all's ok
}
else
{
MessageBox.Show("error converting from string to int"); //or some other code to handle the exception
}

That's all. I hope you cought the idea.

 


Filed Under:   C# |
Post Tags:   convert | csharp | exception | int | parse | reference | string | value |
  Comments [0]



 
 
How to create ASP.NET form without action
Standard solution breaks the designer, I prefer the other way
Posted By:   tengo
At:   2/11/2009 3:05:00 PM
 

 How to create ASP.NET form without action
Standard solution breaks the designer, I prefer the other way

Ok, first what I did is just opened site http://asp.net/learn, entered the ASP.NET section and found the video from "How Do I" series, which describes how to make URL rewriting.
Great video, my advice to you is to find a little free time and have a look at this too.
There is said that, if you want to make URL rewriting in your ASP.NET project, you just have to create a class, inherited from System.Web.IHttpModule, and implement it's methods. In the Init() method you have to assign event handler to the application event called BeginRequest. It's fired every time when the request is sent to the server.
If you didn't yet understand the logic, I want to explain: According to the request you can find the URL to which it's pointing, and then, if it's your wish, you can change that particular URL with something else. But don't think about it as it sounds from the start. Changing URL means that URL in the address bar remains unchanged, but request is sent to another URL, the one you provided for changing the old one. Great trick, yeah?
For example: consider you have a web site, and you have user profiles stored in your SQL DataBase or some other kind of source. Let's consider your site's domain name is http://mysite.com. Your task is to show the profiles of users. Of course you would not create so many ASP.NET pages as many users you have. Am I right? Then what would you do?
One of the ways is to create a page which will display user's information according to the provided parameters. Let's say you created a page UserProfile.aspx which expects user's login name written in the query string, like this: UserProfile.aspx?Login=someLogin. Easy logic.
In the code of the page you just check the value of Request.Querystring["Login"], which is of type string, and then you make a simple select statements from the data source.
Considering this, you can understand, that, if needed to display the profile of user with login "tengo", then you must enter the following URL in the address bar of your web browser:
http://mysite.com/UserProfile.aspx?Login=tengo
not a bad job.
But!
Why not to make it possible to access the profile of user with login "tengo" using the following URL:
http://mysite.com/Users/tengo.aspx
(just like my blog does).
It looks like you have to create a page named tengo.aspx but, using the feature of URL rewriting you can solve the problem very easy. In terms of URL rewriting, the request URL in this case is http://mysite.com/Users/tengo.aspx. and the second URL, using which you must change the requested URL, is the real, working URL, that is: UserProfile.aspx?Login=tengo.
And that means, that address in the address bar of the browser will be the first, and the request will be processed in the second one.

Ok, next step.

If you watched the video that I mentioned about, you would already know, that this approach has some not very comfortable results. One of them is: if you have any button or anything that makes the page submitting, that means, after clicking on that, user will see the URL that you so much tried to hide from the eyes of the user.
The same video, teaches us how to avoid this problem. You can just create your own class, inherited from System.Web.UI.HtmlControls.HtmlForm, and override it's RenderAttributes() method. Why you need that?
The reason that just opens you secret URL to the user is the "action" attribute of the form tag, that is contained on each ASP.NET page. If that attribute would not be there, everything would be just fine! I hope now you understood. After overriding the RenderAttributes() method you can just render all the attributes of the form except the one with a name "action". Great approach, I did try it on my own project, created the class of Form, registered that class in my ASP.NET page using <%@Register %> directive of ASP.NET, and then, just simply changed the tag <form> with my own tag name (the name of the class I had created).
Everything's fine, and you would think: that's all, the problem is solved.

Not so fast, please...

Yes, I changed the tag in my ASP.NET page, ran the project, saw the result. I was happy. Then, I just continued writing some other codes in the project and...
I was very surprised when I switched to the design view of the page and, what there happened is, there was nothing visible in the design view of the page. Everything disappeared, page was empty and a rectangle positioned in the left upper corner of the page was saying:

Error Creating Control - form1
Unable to cast object of type ‘System.Web.UI.Design.HTMLIntrinsicControlDesigner' to type ‘System.Web.UI.Design.ControlDesigner'

Now what? Designer is broken.
The first think I just thought, I would change the form tags back as it was from the beginning, continue the development, and then, before releasing it, I would change the tags as needed.
Not very comfortable solution (as for me).

Second solution:

Create a class inherited from System.Web.UI.HtmlTextWriter, override it's WriteAttribute methods, in the beginning of the method check if the name of attribute is "action", and if so just exit the method.
Then, create a class inherited from System.Web.UI.Page class. Override it's Render method, and make a rendering to your htmltextwriter class.
It was in a little amount of words, explained the solution. Now I'll explain all in details:

Every page in you project is a class inherited from the System.Web.UI.Page class. And of course, when rendering it to the browser as HTML, the rules contained in the Page class are used.
Now you understand, that if you'll have you own Page class, and write there the rendering rules, and then change your pages so as they inherit from your Page class, then every page will play with your rules.

Let's look at the code of my HTMLTextWriter class:

public class HTMLTextWriter : System.Web.UI.HtmlTextWriter
{
public HTMLTextWriter(System.Web.UI.HtmlTextWriter baseWriter) : base(baseWriter)
{
this.InnerWriter = baseWriter;
}

public override void WriteAttribute(string name, string value)
{
if (name.ToLower() == "action")
{
return;
}
base.WriteAttribute(name, value);
}

public override void WriteAttribute(string name, string value, bool fEncode)
{
if (name.ToLower() == "action")
{
return;
}
base.WriteAttribute(name, value, fEncode);
}
}


and here's the code of my Page class:

public class MyPage : System.Web.UI.Page
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(new HTMLTextWriter(writer));
}
}


as you see, in the constructor of HTMLTextWriter class I'm saving the pointer to parameter baseWriter assigning it to the propery InnerWriter. InnerWriter is the writer that writes everything. I'm not interested what it was before this assignment. The fact is, I'm invoking Page class's Render method using a writer that must have everything rendered inside. And of course, code will be writing everything to this writer, because I saved the pointer to it.

Then, everything is very simply, overriding WriteAttribute methods, I write everything to exactly that writer, except the attribute named "action".

When done with this code, now you can access the code of your pages and change the inheritance of them. Like this (for my default page):

public partial class _Default : MyPage

let's try a designer... All's working fine!

Happy coding!

 


Filed Under:   ASP.NET | C# |
Post Tags:   action | aspnet | csharp | form | html | rewrite | url |
  Comments [0]



 
CustomContentBox [2] 
 
Useful Links:
 
CategoryViewBox 
 
CoderBlog.NET
  Get your own Blog Engine
  SMS Sending Service
  What do you want to see on CoderBlog.NET?
  IMAGINE.GE created a header image for CoderBlog.NET
  CoderBlog.NET offers link exchange
  Quick language selection added
  CoderBlog.NET ‘s what is what
  Welcome to CoderBlog.NET

  Jump to Category...
 
TagsBox 
 
Popular Tags
aspnetblogcsharpdesigndivengineerrorformhtmljavascript
 
AuthorsBox 
 
Authors
  Tengiz Tutisani  (25)
 
SubscriptionsBox 
 
Subscriptions
Your Email:
 
LoginStatusBox 
 
Site Members
Login
 
Copyright © 2009 . CoderBlog.NET