ASP.NET (RSS)

My talk about ASP.NET

Object to DataTable

Hi all, Did you ever had the problem that u just wanted your object in a datatable and didn't wane hardcode the datatable if so this may help:

#region ObjectArrayToDataTable
        internal static DataTable ObjectArrayToDataTable(object[] obj, Type type)
        {
            return ObjectArrayToDataTable(obj, type, null);
        }
        internal static DataTable ObjectArrayToDataTable(object[] obj, Type type, DataColumn[] extra)
        {
            DataTable dt = new DataTable();

            foreach (PropertyInfo pi in type.GetProperties())
            {
                if (pi.PropertyType.IsPrimitive || pi.PropertyType == typeof(string) || pi.PropertyType == typeof(DateTime))
                {
                    dt.Columns.Add(pi.Name, pi.PropertyType);
                }
            }

            if (extra != null)
            {
                foreach (DataColumn c in extra)
                {
                    if (dt.Columns.Contains(c.ColumnName))
                        dt.Columns.Remove(c.ColumnName);
                    dt.Columns.Add(c);
                }
            }

            foreach (object k in obj)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in type.GetProperties())
                {
                    if (pi.PropertyType.IsPrimitive || pi.PropertyType == typeof(string) || pi.PropertyType == typeof(DateTime))
                    {
                        dr[pi.Name] = pi.GetValue(k, null);
                    }
                }
                dt.Rows.Add(dr);
            }

            return dt;
        }
        #endregion

I wish you all happy netting!

Make IE and Mozzilla look the same (2 tips)

Hi all,

So i was building my cms system and finally i found out what was wrong and why a site looked so mutch differend in IE then in Mozzila.
The problem is the Box model used by IE the official box model by W3C is with of the content but IE uses the width of the border.
To fix this is pritty easy just dump IE! No just kidding there is a very nice think make by Erik Arvidsson witch will make the images with borders look the same in IE and Mozzilla. The site where you can read about this is: http://webfx.eae.net/dhtml/boxsizing/boxsizing.html

Also what really f*c*s sites up is the user of the css properties 'font-size' used with one of the following values:

  • xx-small
  • x-small
  • small
  • medium
  • large
  • x-large
  • xx-large

Just use number as values like '12px' or '16px'.

These 2 tricks really helped me create a system that makes the sites look almost the same.

Happy netting,
Warnar Boekkooi

Password encoding

Here is the way i encode my passwords for the database:
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
byte[] buff = new byte[16];
rng.GetBytes(buff);
string salt = Convert.ToBase64String(buff);
string encodeType = "SHA1"; //You can also use "MD5"
string pass = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (salt + txtPass.Text, encodeType);

As you can see i use a new salt for every password but you can also just set a static salt :)

Happy netting,
Warnar

C# password generator function

Here is a password generator:
public static string CreateRandomPassword(int PasswordLength)
  {
   string _allowedChars = "
abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?";
   Byte[] randomBytes = new Byte[PasswordLength];
   char[] chars = new char[PasswordLength];
   int allowedCharCount = _allowedChars.Length;

   for(int i = 0;i<PasswordLength;i++)
   {
    chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
   }

   return new string(chars);
  }

Happy netting,
warnar

Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.

Hey all,

I got the following error when working with access
Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.

My query was ok but i seems i used a reserved word in my query the way to get the query to work is using [ ] before and after that word.

Got the solution form  http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21023377.html

Happy netting,
warnar

Moving a Row up in a Datatable

Hey all,

I was bizzy with a little project and it needed to move row's up and down in a Datarow.
Problem was i couldn't move the datarows so i needed to move the info.
The way i moved a row up was like this (this happend in ItemCommand with a command named Up):

object[] up = DataTableFields.Rows[e.Item.ItemIndex].ItemArray;
object[] down = DataTableFields.Rows[e.Item.ItemIndex-1].ItemArray;
DataTableFields.Rows[e.Item.ItemIndex].ItemArray = down;
DataTableFields.Rows[e.Item.ItemIndex-1].ItemArray = up;

Don't really like this way but hey it works.

Happy netting,
warnar

Please Submit when i press enter button :D

Hey all,

Got the following way from one of the old(er) blogs around here but forgot witch.
So here we go i have a Button i want to submit when someone presses Enter :D
This is the way to do it add the following code to your code behind:

Page.RegisterHiddenField("__EVENTTARGET", "The_Name_Of_The_Button");

Just replace The_Name_Of_The_Button with the name of the button :P

Edit:
One of the things also possible is that if your in a textbox and you want that someone presses enter and it will submit you can use:

TextBox1.Attributes.Add("OnKeyUp","if(event.keyCode==13) window.location.href='/gotoUrl.aspx'");

Happy netting,
Warnar

Server Error in '/' Application. Parser Error (Don't you love this :p)

Hey all,

I got a small job from www.proctrl.nl for one of there sites.
When in plementing the ASP.NET app i got the following error:

Server Error in '/' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'ExcelPriceList.price'.

Source Error:

Line 1:  <%@ Page language="c#" Codebehind="price.aspx.cs" AutoEventWireup="false" Inherits="ExcelPriceList.price" %>
Line 2:  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
Line 3:  <HTML>

Source File: d:\internet\root\www\burgerhout\www\prijzen\price.aspx    Line: 1

Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573

The way to make sure not to get this error is make the dir your putting the app in a virtual one :D

Happy netting,
Warnar

Get info from a Excel file using ASP.NET

Hey all,

I got a small job that has a XML file that should be displayed and i'm not in the mood of typing how i did it so here are the links i used:

http://www.c-sharpcorner.com/Code/2004/June/AccessExcelDb.asp (Mostly used the screenshot from the Excel file)
http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B306572 (What to say it's the microsoft way and it works)

Hope that this may help :D

Happy Netting,

Warnar

N00B Mistake with a Component used for a Database (To mutch Database connections)

Hey all here is yet a again one of my blog about what i'm doing wrong :D

I have been bizzy with www.kapperkapper.nl as you may know. The problem is that i got error's that where like all connections to the database are open and stuff like that and i was Like WHAT!

I have a Component with all the dataset's adapters and code to use for the db on it i had my constructor witch opens the database and i had my dispose witch closes it.

A well it seemed to me that that should do the job but hey stupid me the Dispose is only called then ASP.NET thinks it is needed or what ever but not when i think it is needed.

So to fix this not i do:

using(ClientDB.Database db = new ClientDB.Database())
{
//Some stuff todo with the DB
}

Now the class is opend and disposed when the using stop's and Bug fixed :D

Happy Netting

Warnar

b.t.w. If you have any Tips for using MSSQL or related stuff me Please post them here :)

Can Send mail (503 This mail server requires authentication)

Hey all,

I'm finaly in the completing fase of my school project YAY :D
I wrote a blog Sending Mail using C# a while ago and a well now i'm having the problem on my server that i can't send mail this is because i need to send some login info for the mail server the way to do this is following (MMessage is the Mail message):

MMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
MMessage.Fields.Add("
http://schemas.microsoft.com/cdo/configuration/sendusername", "my_username_here"); //set your username here
MMessage.Fields.Add("
http://schemas.microsoft.com/cdo/configuration/sendpassword", "super_secret"); //set your password here

I got this solution on http://systemwebmail.com/faq/3.8.aspx so if you need some more info get it there :)

Happy Netting

There is already an open DataReader associated with this Connection which must be closed first. (Try reader.Close(); )

Ok so I wanted to get just 3 little thing from my DB and i used this code in the costructor of my Component:

PosterCommand = new System.Data.SqlClient.SqlCommand();
PosterCommand.CommandText = @"SELECT firstName, name, tussenVoegsel, costumerID FROM customerInfo WHERE (costumerID = @id)";
PosterCommand.Connection =
this.sqlConnection2;
PosterCommand.Parameters.Add(
new System.Data.SqlClient.SqlParameter("@id", System.Data.SqlDbType.Float, 8, "id"));

After this i used the function to get the info:

public string Poster(double ID)
{
PosterCommand.Parameters["@id"].Value = ID;
reader = PosterCommand.ExecuteReader();
reader.Read();
string Poster = string.Format("{0}{1}{2}",reader[0].ToString(),reader[2].ToString(),reader[1].ToString());
return Poster;
}

But when i was running the function for the second time i go the error There is already an open DataReader associated with this Connection which must be closed first. And then i found the blody problem i needed to CLOSE THE DATAREADER !!! so now the function is like this:

public string Poster(double ID)
{
PosterCommand.Parameters["@id"].Value = ID;
reader = PosterCommand.ExecuteReader();
reader.Read();
string Poster = string.Format("{0}{1}{2}",reader[0].ToString(),reader[2].ToString(),reader[1].ToString());

reader.Close();
return Poster;
}

Have fun and Good Netting

ItemDataBound stupid mistake between e.Item.ItemIndex and e.Item.DataSetIndex

Hi there :)

Ok yet again a small problem :(
I had a very nice datagrid with info in it a ItemDataBound to show the pricture the right way and it was great :D
But then there came the evil paging *i was scared* and when i went to page to the images wheren't right anymore!!
There was no darn reson i could find.......
The code with the error:
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemIndex >= 0)
{
string ID = dataSetProduct1.product[e.Item.ItemIndex].productID.ToString();
HyperLink picture = e.Item.FindControl("img_product") as HyperLink;
picture.ImageUrl = string.Format("/Picture/Product/Tumb/{0}.jpg",ID);
}
}

And then i found the problem it was e.Item.ItemIndex dam wat was i stupid the problem was that i looked at the row of the datalist and not to the row of the dataset witch can be gotten by using e.Item.DataSetIndex and now i works like a speed ass again :p
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemIndex >= 0)
{
string ID = dataSetProduct1.product[e.Item.DataSetIndex].productID.ToString();
HyperLink picture = e.Item.FindControl("img_product") as HyperLink;
picture.ImageUrl = string.Format("/Picture/Product/Tumb/{0}.jpg",ID);
}
}

Happy Netting

Url Rewriting using ASP.NET ! :D:D

Hey all,

So i needed to make myself a search engine and then i started reading

about how to build/make one i came to the conclusion that my nice litte site with view.aspx?id=10&view=True really would work because search engine's only would read the view.aspx and not the ?id=10&view=True .
This mend i had to make or get my self a url rewriter first i found some stupid ISAPI dll's that could do it for me and then i can accross this little article URL Rewriting in ASP.NET.
Men that's alot of ready here is the short version just to get it to work.

First make sure you have a project where you wane use it in :D
Now download the source code of the Url Rewriting in ASP.NET article (Click here) and install the blody thing then get you self the URLRewriter.dll and put it into the bin dir from your project.

Now for the little harder part :D!
Open your project and open the Web.Config file.
Now add the following after <configuration> and before <system.web> :
<configSections>
<
section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
<
/configSections>
Cool men now we included some config but you not done yet add the following after <system.web>:
<httpModules>
<add type="URLRewriter.ModuleRewriter, URLRewriter"
name="ModuleRewriter" />
</httpModules>
Now we included the httpmodule :D:D.
Now for the rules! this will also be done in the web.config and it will go like this just a example.
My self the problem was i had a file called view.aspx witch needed a id and view to work and displayed a product.
I needed to make the url look like this http://localhost/product/1/True/.aspx or http://localhost/product/2/False/.aspx a way to do this is add after </configSections> and before <system.web> the following code:
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/product/(\d*)/(\d*)/\.aspx</LookFor>
<SendTo>~/view.aspx?id=$1&view=$2<