.NET (RSS)

My thoughts related to .NET Programming

Beware at AJAX beta 2 migration

Since beta 2 is here, I decided yesterday to update beta 1 version of my project. I always tell my self not to touch things still they work, but as usual the new things are attractive. I already hed expirience of migrating from "Atlas" to "Ajax" - thats was real hurt. But I did not think that so meny diffrence will be from one beta to another and shame on me :). After updating ajax extention library my project totaly failed to run, Jscrpit failure something with 'Sys' object was wrong. Not likable error at 01:00AM. Well googling did not bring the desired results. Then I created new ajax enabled project and copied all related web.config settings to my project. Fourtunately project is working. Must stop this 'try a new staff' things...

Showing progress in console application

Sometimes It helps us to see progress of our console application. But if It will print each line it will be a little confusing. So here is code that will print status in one line:

for(Int i=0;i<1024;i++)
{
   Console.Write(“Showing {0}\r“, i);
}

Enjoy :)   

How to create template control in ASP.NET

I wrote an article about creating template controls in ASP.NET. This is my first article. Hope it will help someone... Apreciate your feedbacks

Catch enter press event

To catch windows form's keyboard press event Form.KeyPreview property must be enabled.
Next step is to add a delegate to this form:

this
.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.FormSearch_KeyPress);

Enter has ascii code of 13 so

private
void FormSearch_KeyPress(object sender, KeyPressEventArgs e)
{
  byte[] key = System.Text.Encoding.ASCII.GetBytes(e.KeyChar.ToString());
  if(key[0].ToString()=="13")
  {
     // do something
  }
}

That's it...

Search a heap algorithm

I took a cource “Data structures” as part of my university studies, it is a real torture comparing to all previous cources , not to mention .NET courses ;-). But it is always good to know the basics. Now we are studing a heap and heapsort. A "heap" is a binary tree which has the property that each child is "smaller" (for an appropriate definition of "smaller"; this generally requires that the data type be totally ordered) than the parent. Another property is that left child of parent(i) is located index 2i, right child on 2i+1. The problem was to find efficient algorithm for searching the heap. I didn't find such one in the net. So I tryed to write it by my self, I am not sure if it is most efficient way so I am waiting for your feedbacks.

// pre: array must be a heap
private
static int search(int[] array, int i, int num)
{
if((i)>(array.Length))
   return -1;
if((num>array[i-1]))
   return -1;
if(array[i-1] == num)
   return i;
return max(search(array,(2*i),num),search(array,(2*i)+1,num));
}

I couldn't make by iterative way, is it possible?

WSE Deployment

Yesterday I spend whole evening on deployment WSE application. I have webservice and client with WSE implemented. Both of them worked fine on local machine while developing but they refuse to work on remote hosting.
After searching over net the only solution I found is to install WSE on both server and client. Well, I could speak to my hosting guys to install WSE, but I think that end users, to them client application will be distributed ,would be little confused while installing it. End users do not like complicated installetions so WSE not good for me. Now I am looking for another security solution that makes less touble in deployment.

Get default web browser from registry

Microsoft.Win32.RegistryKey keyBrowser = Microsoft.Win32.Registry.ClassesRoot;
Microsoft.Win32.RegistryKey keyDefaulBrowser = keyBrowser.OpenSubKey("HTTP\\shell\\open\\ddeexec\\Application");
string defaultBrowser = (string)keyDefaulBrowser.GetValue("");

StreamReader do not reads whole file???

I just wanted to check what do I read from text file using StreamReader class and
I found that It doesn't read a whole file data. Look at this bits:

FileStream fs = new FileStream("test.txt",FileMode.Open,FileAccess.Read);
FileStream fs1 =
new FileStream("test_read.txt",FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter sw =
new StreamWriter(fs1);
using (StreamReader sr = new StreamReader(fs))
{
string strTmp;
while(sr.Peek() >= 0)
{
strTmp=sr.ReadLine();
sw.WriteLine(strTmp);
}

This code must give me two identical files, right? But It doesn't. It cuts few lines at the end.
So what is the catch?

 

Ip to county solution needed

Is where any public webservices for Ip to country mapping?   

Webservice soap message length limitation

Is there any length limitation of soap message? I mean I could sent entire DataSets over network and It could be a lot of data . And what happens if network disconnection occurs during transmition?  

How to parse HTML?

Does anybody know what is the best way to parse HTML files?

Webservice serialization

I've create class A that includes collection of another class B. I'm trying to use class A with webservice. I've created function that returns class A. When I try to invoke the function in browser it gives me status 500. When I try to use that service with my application it also fails with  “Server was unable to process request. --> There was an error generating the XML document. --> The type MyClass.StudentInfo was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.”  error. Soap serialization through System.Runtime.Serialization.Formatters.Soap worked just fine. I thought these are the same serialization proccess, if not how do I prepare my classes for webservice usage?

Weird VS2003 behavior

A friend of my asked to show him how to start with ASP.NET. He has VS.2003 installed on his PC. So I choosed project name “test” for example ASP.NET application. On project creation VS.2003 just stuck and became not responding. I tried again but this time with “test1” name for the project - the same thing. When we went to my PC (I was sure It will work on my PC because I did it a hundred times), on my PC it also stuck. When I lived the default project name it worked perfectly. Weird...

Problem with IIS intallation after framework installed

When you install IIS after you installed .NET framework you will not be able to run asp.net projects. In this case you need to run aspnet_regiis -i from command line. It locates at %WINDIR%/Microsoft.NET\Framework\v1.1.4322\

Validating URL

Here is an example of function that validates url.

public bool function ValidateUrl(string url)
{
   Uri newUri = new Uri(“Http://“+url);
   try
   {
     WebRequest httpReq = WebRequest.Create(newUri);
     WebResponse httpRes = httpReq.GetResponse();
     HttpWebResponse myRes = (HttpWebResponse)httpRes;

      if(myRes.StatusCode==“OK“)
     {
         return true;
     }
     else
        return false;
   }
   catch (WebException ex)
   {
       return false;
    }

}

Getting output from stored procedure with SqlCommand

I know for many people it is not new but I post It anyway. Creating a stored procedure 
CREATE PROCEDURE AddUser
(
      @UserName nvarchar(100),
      @NewUserId int OUTPUT
) AS
INSERT tUsers (UserName) VALUES(@UserName)
SELECT @NewUserId=@@Identity
RETURN
GO 

Creating a function:
public int AddUser(string userName)
{
      int newId;
      SqlConnection conn = new SqlConnection(connectionSting);
      SqlCommand cmd = new SqlCommand(“AddUser“,conn);
      
cmd.CommandType = CommandType.StoredProcedure;
       
cmd.Parameters.Add("@UserName",userName);
        cmd.Parameters.Add("@NewUserId",SqlDbType.Int);
        cmd.Parameters["@NewUserId"].Direction = ParameterDirection.Output;
        conn.Open();
        cmd.ExecuteNonQuery();
       
newId =
(int)cmdl.Parameters["@NewUserId"].Value;
        conn.Close();
        return newId;
      

}

Data access application block performance

I have replaced Data Access Layer of my working project with Enterprise library Data access application block.. not exactly replaces rather implemented :) just to couple small functions.  The first thing I could see that my now project  loads slower. It is about few second, It not a problem for a little data, but I'm afraid that it could affect bigger data chunks.  

String resource file

I'm studing Enterprise Library and I just don't get It... What is string resource file and where It came from?

Adding images to ListView control

this an example how to add images to listview control:

// create a new image list
ImageList ilImages = new ImageList();
// add some images
ilImages.images.add(“image.bmp“);
lvObjects.SmallImageList = ilImages;

foreach (object o in objects)
{
ListViewItem listItem =
new ListViewItem();
string sArg = "";
listItem.Text = o.Text;
// index of desired image

listItem.ImageIndex = 0;
lvObjects.Items.Add(listItem);

}

"String or binary data would be truncated" MS Sql error

This problem occurs when you trying to insert to field a string that exceeds fields length. The only solution I could find was to set a bigger field length.