San Diego Website design home Contact Us Client Login


Thursday, June 19, 2008

An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.

An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.

 

For some Reason I needed to add this to my connection string in the web.config file.

<remove name="LocalSqlServer"/>
        <add name="LocalSqlServer" connectionString="Server=servername Database=dbname; User ID=user; Password=something; Trusted_Connection=False" providerName="System.Data.SqlClient"/>
               

so the whole entry looks like this:

<connectionStrings>
        <add name="ClubSiteDB" connectionString="Server=servername; Database=dbname; User ID=user; Password=password123; Trusted_Connection=False" providerName="System.Data.SqlClient"/>
 <remove name="LocalSqlServer"/>
        <add name="LocalSqlServer" connectionString="Server=servername Database=dbname; User ID=user; Password=something; Trusted_Connection=False" providerName="System.Data.SqlClient"/>
               
    </connectionStrings>

 

Please support this blog by clicking on the advertisments to the right.

Invalid object name 'SiteSettings'.

I got this error when I was installing the ClubSite starter Kit on Godaddy's servers.

The Table is not created in the Database when the .sql script is run.

 

Run this in your query analyzer.

 

CREATE TABLE [dbo].[SiteSettings](
    [SiteID] [int] IDENTITY(1,1) NOT NULL,
    [SiteName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Theme] [int] NULL,
 CONSTRAINT [PK_SiteSettings] PRIMARY KEY CLUSTERED
(
    [SiteID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

 

 

You'll probable need this one also

CREATE TABLE [dbo].[SiteThemes](
    [Theme] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ThemeID] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_SiteThemes] PRIMARY KEY CLUSTERED
(
    [ThemeID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

 

 

Please support this blog by click on the advertisements to the right.

Thursday, May 22, 2008

System.Deployment. Application. Deployment Download Exception (Unknown subtype)


1). All you have to do is to add the 

.manifest = application/manifest 

and

.deploy=application/octet-stream 

in the IIS root directory's -> Properties -> HTTP Headers -> MIME Types.

RightClick the Default Web Site of your IIS , then Select Properties, then go the HTTP Header tab. Near the bottom of the tab there is a command button called MIME Types 

Click the MIME Types button. A New dialog pops. This dialog show you the MIME Types that are registered with your server. Click the New button 

on this dialog.  Another dialog pops that has two text boxes.

That asks you the Extension and MIME Type
---------------------------------------------------------------------

Like:        Extension
               MIME Type

---------------------------------------------------------------------

First  add the Extension to .manifest and add MIME Type to 

application/manifest 
Then add the Extension to .deploy   and  add MIME Type to 

application/octet-stream

Saturday, May 17, 2008

An expression of non-boolean type specified in a context where a condition is expected, near ')'

This is an syntax error in SQL when the 'if' statement is not correctly formatted.

In SQL an 'if' statement in a stored procedure can look like this:

 

IF  'condition'

BEGIN

'statement'

END

 

When the conditional statement is not formattted correctly you'll get the error for example I had:

IF  @variable = 'ALL' OR ' '

BEGIN

set @variable = NULL

END

 

I am checking the value of the incoming parameter and changing it to NULL. I do this to avoid dynamic SQL in my where clause.  But this is another topic.

SO

Change the if statement to this and avoid my mistake:

IF  @variable = 'ALL' OR @variable = ' '

BEGIN

set @variable = NULL

END

 

Please support this blog by clicking on my sponsors to the right.

 

Good Luck!

Operator '&&' cannot be applied to operands of type 'bool' and 'string'

I ran into this error when I was creating some validation logic with an 'if' statement.  It went something like this:

if (txtfield1.Text = "" || (txtfield2.Text = "" || txtfield3.Text = ""))

{

// display error message

}

You need to use double equal signs in this case.

it should be:

if (txtfield1.Text == "" || (txtfield2.Text == "" || txtfield3.Text == ""))

{

// display error message

}

 

Please support this blog by clicking on the sponsors to the right.

 

Good luck

Culture 'en' is a neutral culture. It cannot be used in formatting and parsing and therefore cannot be set as the thread's current culture.

Culture 'en' is a neutral culture. It cannot be used in formatting and parsing and therefore cannot be set as the thread's current culture.

 

I ran into this problem when I was using  a method to check for a numeric string.  I'll post this method in another blog.

Try changing the 'en' to 'en-US'

Here is the table for all possible cultures fo rthe System.Globalization class:

Culture/Language Name

Culture Identifier

Culture

"" (empty string)

0x007F

Invariant culture

af

0x0036

Afrikaans

af-ZA

0x0436

Afrikaans (South Africa)

sq

0x001C

Albanian

sq-AL

0x041C

Albanian (Albania)

ar

0x0001

Arabic

ar-DZ

0x1401

Arabic (Algeria)

ar-BH

0x3C01

Arabic (Bahrain)

ar-EG

0x0C01

Arabic (Egypt)

ar-IQ

0x0801

Arabic (Iraq)

ar-JO

0x2C01

Arabic (Jordan)

ar-KW

0x3401

Arabic (Kuwait)

ar-LB

0x3001

Arabic (Lebanon)

ar-LY

0x1001

Arabic (Libya)

ar-MA

0x1801

Arabic (Morocco)

ar-OM

0x2001

Arabic (Oman)

ar-QA

0x4001

Arabic (Qatar)

ar-SA

0x0401

Arabic (Saudi Arabia)

ar-SY

0x2801

Arabic (Syria)

ar-TN

0x1C01

Arabic (Tunisia)

ar-AE

0x3801

Arabic (U.A.E.)

ar-YE

0x2401

Arabic (Yemen)

hy

0x002B

Armenian

hy-AM

0x042B

Armenian (Armenia)

az

0x002C

Azeri

az-Cyrl-AZ

0x082C

Azeri (Azerbaijan, Cyrillic)

az-Latn-AZ

0x042C

Azeri (Azerbaijan, Latin)

eu

0x002D

Basque

eu-ES

0x042D

Basque (Basque)

be

0x0023

Belarusian

be-BY

0x0423

Belarusian (Belarus)

bg

0x0002

Bulgarian

bg-BG

0x0402

Bulgarian (Bulgaria)

ca

0x0003

Catalan

ca-ES

0x0403

Catalan (Catalan)

zh-HK

0x0C04

Chinese (Hong Kong SAR, PRC)

zh-MO

0x1404

Chinese (Macao SAR)

zh-CN

0x0804

Chinese (PRC)

zh-Hans

0x0004

Chinese (Simplified)

zh-SG

0x1004

Chinese (Singapore)

zh-TW

0x0404

Chinese (Taiwan)

zh-Hant

0x7C04

Chinese (Traditional)

hr

0x001A

Croatian

hr-HR

0x041A

Croatian (Croatia)

cs

0x0005

Czech

cs-CZ

0x0405

Czech (Czech Republic)

da

0x0006

Danish

da-DK

0x0406

Danish (Denmark)

dv

0x0065

Divehi

dv-MV

0x0465

Divehi (Maldives)

nl

0x0013

Dutch

nl-BE

0x0813

Dutch (Belgium)

nl-NL

0x0413

Dutch (Netherlands)

en

0x0009

English

en-AU

0x0C09

English (Australia)

en-BZ

0x2809

English (Belize)

en-CA

0x1009

English (Canada)

en-029

0x2409

English (Caribbean)

en-IE

0x1809

English (Ireland)

en-JM

0x2009

English (Jamaica)

en-NZ

0x1409

English (New Zealand)

en-PH

0x3409

English (Philippines)

en-ZA

0x1C09

English (South Africa

en-TT

0x2C09

English (Trinidad and Tobago)

en-GB

0x0809

English (United Kingdom)

en-US

0x0409

English (United States)

en-ZW

0x3009

English (Zimbabwe)

et

0x0025

Estonian

et-EE

0x0425

Estonian (Estonia)

fo

0x0038

Faroese

fo-FO

0x0438

Faroese (Faroe Islands)

fa

0x0029

Farsi

fa-IR

0x0429

Farsi (Iran)

fi

0x000B

Finnish

fi-FI

0x040B

Finnish (Finland)

fr

0x000C

French

fr-BE

0x080C

French (Belgium)

fr-CA

0x0C0C

French (Canada)

fr-FR

0x040C

French (France)

fr-LU

0x140C

French (Luxembourg)

fr-MC

0x180C

French (Monaco)

fr-CH

0x100C

French (Switzerland)

gl

0x0056

Galician

gl-ES

0x0456

Galician (Spain)

ka

0x0037

Georgian

ka-GE

0x0437

Georgian (Georgia)

de

0x0007

German

de-AT

0x0C07

German (Austria)

de-DE

0x0407

German (Germany)

de-LI

0x1407

German (Liechtenstein)

de-LU

0x1007

German (Luxembourg)

de-CH

0x0807

German (Switzerland)

el

0x0008

Greek

el-GR

0x0408

Greek (Greece)

gu

0x0047

Gujarati

gu-IN

0x0447

Gujarati (India)

he

0x000D

Hebrew

he-IL

0x040D

Hebrew (Israel)

hi

0x0039

Hindi

hi-IN

0x0439

Hindi (India)

hu

0x000E

Hungarian

hu-HU

0x040E

Hungarian (Hungary)

is

0x000F

Icelandic

is-IS

0x040F

Icelandic (Iceland)

id

0x0021

Indonesian

id-ID

0x0421

Indonesian (Indonesia)

it

0x0010

Italian

it-IT

0x0410

Italian (Italy)

it-CH

0x0810

Italian (Switzerland)

ja

0x0011

Japanese

ja-JP

0x0411

Japanese (Japan)

kn

0x004B

Kannada

kn-IN

0x044B

Kannada (India)

kk

0x003F

Kazakh

kk-KZ

0x043F

Kazakh (Kazakhstan)

kok

0x0057

Konkani

kok-IN

0x0457

Konkani (India)

ko

0x0012

Korean

ko-KR

0x0412

Korean (Korea)

ky

0x0040

Kyrgyz

ky-KG

0x0440

Kyrgyz (Kyrgyzstan)

lv

0x0026

Latvian

lv-LV

0x0426

Latvian (Latvia)

lt

0x0027

Lithuanian

lt-LT

0x0427

Lithuanian (Lithuania)

mk

0x002F

Macedonian

mk-MK

0x042F

Macedonian (Macedonia, FYROM)

ms

0x003E

Malay

ms-BN

0x083E

Malay (Brunei Darussalam)

ms-MY

0x043E

Malay (Malaysia)

mr

0x004E

Marathi

mr-IN

0x044E

Marathi (India)

mn

0x0050

Mongolian

mn-MN

0x0450

Mongolian (Mongolia)

no

0x0014

Norwegian

nb-NO

0x0414

Norwegian (Bokmål, Norway)

nn-NO

0x0814

Norwegian (Nynorsk, Norway)

pl

0x0015

Polish

pl-PL

0x0415

Polish (Poland)

pt

0x0016

Portuguese

pt-BR

0x0416

Portuguese (Brazil)

pt-PT

0x0816

Portuguese (Portugal)

pa

0x0046

Punjabi

pa-IN

0x0446

Punjabi (India)

ro

0x0018

Romanian

ro-RO

0x0418

Romanian (Romania)

ru

0x0019

Russian

ru-RU

0x0419

Russian (Russia)

sa

0x004F

Sanskrit

sa-IN

0x044F

Sanskrit (India)

sr-Cyrl-CS

0x0C1A

Serbian (Serbia, Cyrillic)

sr-Latn-CS

0x081A

Serbian (Serbia, Latin)

sk

0x001B

Slovak

sk-SK

0x041B

Slovak (Slovakia)

sl

0x0024

Slovenian

sl-SI

0x0424

Slovenian (Slovenia)

es

0x000A

Spanish

es-AR

0x2C0A

Spanish (Argentina)

es-BO

0x400A

Spanish (Bolivia)

es-CL

0x340A

Spanish (Chile)

es-CO

0x240A

Spanish (Colombia)

es-CR

0x140A

Spanish (Costa Rica)

es-DO

0x1C0A

Spanish (Dominican Republic)

es-EC

0x300A

Spanish (Ecuador)

es-SV

0x440A

Spanish (El Salvador)

es-GT

0x100A

Spanish (Guatemala)

es-HN

0x480A

Spanish (Honduras)

es-MX

0x080A

Spanish (Mexico)

es-NI

0x4C0A

Spanish (Nicaragua)

es-PA

0x180A

Spanish (Panama)

es-PY

0x3C0A

Spanish (Paraguay)

es-PE

0x280A

Spanish (Peru)

es-PR

0x500A

Spanish (Puerto Rico)

es-ES

0x0C0A

Spanish (Spain)

es-ES_tradnl

0x040A

Spanish (Spain, Traditional Sort)

es-UY

0x380A

Spanish (Uruguay)

es-VE

0x200A

Spanish (Venezuela)

sw

0x0041

Swahili

sw-KE

0x0441

Swahili (Kenya)

sv

0x001D

Swedish

sv-FI

0x081D

Swedish (Finland)

sv-SE

0x041D

Swedish (Sweden)

syr

0x005A

Syriac

syr-SY

0x045A

Syriac (Syria)

ta

0x0049

Tamil

ta-IN

0x0449

Tamil (India)

tt

0x0044

Tatar

tt-RU

0x0444

Tatar (Russia)

te

0x004A

Telugu

te-IN

0x044A

Telugu (India)

th

0x001E

Thai

th-TH

0x041E

Thai (Thailand)

tr

0x001F

Turkish

tr-TR

0x041F

Turkish (Turkey)

uk

0x0022

Ukrainian

uk-UA

0x0422

Ukrainian (Ukraine)

ur

0x0020

Urdu

ur-PK

0x0420

Urdu (Pakistan)

uz

0x0043

Uzbek

uz-Cyrl-UZ

0x0843

Uzbek (Uzbekistan, Cyrillic)

uz-Latn-UZ

0x0443

Uzbek (Uzbekistan, Latin)

vi

0x002A

Vietnamese

vi-VN

0x042A

Vietnamese (Vietnam)

Please support my blog by clicking on the sponsors to the right.

 

Good Luck

Tuesday, March 04, 2008

Export DataGridView to Excel

 private void ExportGridView()
        {

           Excel.Application m_objExcel = new Excel.Application();
           Excel.Workbooks m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
           Excel._Workbook m_objBook = (Excel._Workbook)(m_objBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet));
           Excel.Sheets m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
           Excel._Worksheet m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));     

            try
            {
                int x;
                int y;
                int c;
                int cc = this.dataGridView1.ColumnCount;
                int rc = this.dataGridView1.RowCount;
                for (c = 0; c < cc; c++)
                {
                    m_objSheet.Cells[1, c + 1] = this.dataGridView1.Columns[c].HeaderText;
                }
                for (x = 0; x < (rc - 1); x++)
                {
                    for (y = 0; y < cc; y++)
                    {
                        m_objSheet.Cells[x + 2, y + 1] = this.dataGridView1.Rows[x].Cells[y].Value.ToString();
                    }
                }
                m_objExcel.Visible = true;
                m_objExcel.UserControl = true;
               
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            MessageBox.Show("Data Exported");
          

        }

Friday, February 29, 2008

A first chance exception of type 'System ArgumentNullException' occurred in mscorlib.dll

I got this error during some win form development.  Check all of you reference paths, naviation links, etc.

I tried to call a dll in my navigation that was misspelled.

Please support this blog by clicking my my sponsors to the right.

 

good luck

Friday, November 09, 2007

Export CSS with GridView

This took me a while to figure this out but if you use CSS to govern the styles of a gridview in .net then you may know that the styles will not export into excel without a little help.

If you want to export a gridview into excel your function may look something like this:

  private void ExportGridView(GridView gv)

    {

        string xlsfilename = "Name.xls";

        string attachment = "attachment; filename=" + xlsfilename;

        Response.ClearContent();

        Response.AddHeader("content-disposition", attachment);

        Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

 

 

        bool allowSorting = gv.AllowSorting; // save the current AllowSorting setting

        gv.AllowSorting = false;

        gv.RenderControl(htw);

        gv.AllowSorting = allowSorting; // restore the current AllowSorting setting

    

        Response.Write(sw.ToString());

        Response.End();

       

    }

You can call on this function by executing a button cmd like this:

protected void Btn_Click(object sender, ImageClickEventArgs e)

    {

        //Export the GridView to Excel

        PrepareGridViewForExport(GridView1);

        ExportGridView(GridView1);

    }

The PrepareGridViewForExport(GridView1); line is a function to handle objects in the gridveiw, but I’ll leave that out of this post. Now back to the main topic.  The styles of this grid will not show up in excel because the office application takes the html written from the webpage and places it into a worksheet.  If that page makes calls to styles in another file then office does not have the details of those styles in the string it is passed.  To add those detail we just need to pass excel the styles in a string.

 

Here’s how it works:

Add the stylesheet to a streamreader object:

StreamReader sr = new StreamReader(Server.MapPath("Name.css"));

        string s = sr.ReadToEnd();

 

don’t forget to close the object:

sr.Close();

 

That’s it! Just add the opening and closing Head tags and Style tags to export script and Office will be able to read the details of the styles in the html string and apply them to the worksheet.

So your new function will look something like this:

 

private void ExportGridView(GridView gv)

    {

        string xlsfilename = "StatusFunds.xls";

        string attachment = "attachment; filename=" + xlsfilename;

        Response.ClearContent();

        Response.AddHeader("content-disposition", attachment);

        Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

 

 

        bool allowSorting = gv.AllowSorting; // save the current AllowSorting setting

        gv.AllowSorting = false;

        gv.RenderControl(htw);

        gv.AllowSorting = allowSorting; // restore the current AllowSorting setting

 

        //read the stylesheet to include the format with the export

        StreamReader sr = new StreamReader(Server.MapPath("Name.css"));

        string s = sr.ReadToEnd();

       

        Response.Write("<HEAD><STYLE>");

        Response.Write(s.ToString());

        Response.Write("</STYLE></HEAD>");

        Response.Write(sw.ToString());

        Response.End();

        sr.Close();

    }

 

Good luck!

Wednesday, October 10, 2007

Validation Expressions

These are so often hard to find so I am posting them here:

 

Metacharacter Match
\ the escape character - used to find an instance of a metacharacter like a period, brackets, etc.
. (period) match any character except newline
x match any instance of x
^x match any character except x
[x] match any instance of x in the bracketed range - [abxyz] will match any instance of a, b, x, y, or z
| (pipe) an OR operator - [x|y] will match an instance of x or y
() used to group sequences of characters or matches
{} used to define numeric quantifiers
{x} match must occur exactly x times
{x,} match must occur at least x times
{x,y} match must occur at least x times, but no more than y times
? preceding match is optional or one only, same as {0,1}
* find 0 or more of preceding match, same as {0,}
+ find 1 or more of preceding match, same as {1,}
^ match the beginning of the line
$ match the end of a line

POSIX Class Match
[:alnum:] alphabetic and numeric characters
[:alpha:] alphabetic characters
[:blank:] space and tab
[:cntrl:] control characters
[:digit:] digits
[:graph:] non-blank (not spaces and control characters)
[:lower:] lowercase alphabetic characters
[:print:] any printable characters
[:punct:] punctuation characters
[:space:] all whitespace characters (includes [:blank:], newline, carriage return)
[:upper:] uppercase alphabetic characters
[:xdigit:] digits allowed in a hexadecimal number (i.e. 0-9, a-f, A-F)

 

Character class Match
\d matches a digit, same as [0-9]
\D matches a non-digit, same as [^0-9]
\s matches a whitespace character (space, tab, newline, etc.)
\S matches a non-whitespace character
\w matches a word character
\W matches a non-word character
\b matches a word-boundary (NOTE: within a class, matches a backspace)
\B matches a non-wordboundary

 

  • \
    The backslash escapes any character and can therefore be used to force characters to be matched as literals instead of being treated as characters with special meaning. For example, '\[' matches '[' and '\\' matches '\'.
  • .
    A dot matches any character. For example, 'go.d' matches 'gold' and 'good'.
  • { }
    {n} ... Match exactly n times
    {n,} ... Match at least n times
    {n,m} ... Match at least n but not more than m times
  • [ ]
    A string enclosed in square brackets matches any character in that string, but no others. For example, '[xyz]' matches only 'x', 'y', or 'z', a range of characters may be specified by two characters separated by '-'. Note that '[a-z]' matches alphabetic characters, while '[z-a]' never matches.
  • [-]
    A hyphen within the brackets signifies a range of characters. For example, [b-o] matches any character from b through o.
  • |
    A vertical bar matches either expression on either side of the vertical bar. For example, bar|car will match either bar or car.
  • *
    An asterisk after a string matches any number of occurrences of that string, including zero characters. For example, bo* matches: bo, boo and booo but not b.
  • +
    A plus sign after a string matches any number of occurrences of that string, except zero characters. For example, bo+ matches: boo, and booo, but not bo or be.
  • \d+
    matches all numbers with one or more digits
  • \d*
    matches all numbers with zero or more digits
  • \w+
    matches all words with one or more characters containing a-z, A-Z and 0-9. \w+ will find title, border, width etc. Please note that \w matches only numbers and characters (a-z, A-Z, 0-9) lower than ordinal value 128.
  • [a-zA-Z\xA1-\xFF]+
    matches all words with one or more characters containing a-z, A-Z and characters larger than ordinal value 161 (eg. ä or Ü). If you want to find words with numbers, then add 0-9 to the expression: [0-9a-zA-Z\xA1-\xFF]+



Typical examples

  • (bo*)
    will find "bo", "boo", "bot", but not "b"
  • (bx+)
    will find "bxxxxxxxx", "bxx", but not "bx" or "be"
  • (\d+)
    will find all numbers
  • (\d+ visitors)
    will find "3 visitors" or "243234 visitors" or "2763816 visitors"
  • (\d+ of \d+ messages)
    will find "2 of 1200 messages" or "1 of 10 messages"
  • (\d+ of \d+ messages)
    will filter everything from the last occurrence of "2 of 1200 messages" or "1 of 10 messages" to the end of the page
  • (MyText.{0,20})
    will find "MyText" and the next 20 characters after "MyText"
  • (\d\d.\d\d.\d\d\d\d)
    will find date-strings with format 99.99.9999 or 99-99-9999 (the dot in the regex matches any character)
  • (\d\d\.\d\d\.\d\d\d\d)
    will find date-strings with format 99.99.9999
  • (([_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+))
    will find all e-mail addresses

thanks

Wednesday, September 26, 2007

Cannot implicitly convert type 'int' to 'string'

Say you have a variable x and you need to pass it as a parameter in a SQL query and it has to be an INT data type. Just convert the variable to an INT using this syntax:

Convert.ToInt32(x.Value);

 

over and out

For columns not defined as System.String, the only valid value is (Throw exception)

For handeling NULLS in a typed DataSet there are several solutions which are all combersome if the datatype is anything other than a string. 

In Visual Studio once you define the typed dataset you can adjust the properties of the column values by clicking on the column in the .xsd GUI.  This allows you to set the datatype and how to handle NullValue.  If the datatype is System.String then you can change the NullValue to empty(""), null(DBNull) or throw exception.  The exception displays an ugly error message in the browser and provides little information on how to correct the issue. (The value for column '*' in table '*' is DBNull) or (System.InvalidCastException: Specified cast is not valid.)

If your datatype is INT, Decimal, etc.. you have to use error handeling in the script to workaround this issue.  Ideally you would expect MS VS2005 to allow you to set the null value to (0), (0m), etc... but that bug is still not fixed. 

Some blogs suggest to change the .cs file to set the value using an if statement.  That will work but it will also get overwritten wehn you uspdate the file with another dataset. 

http://forums.microsoft.com/MSDN/ShowPost.aspx?
PostID=174108&SiteID=1

Fortunately when the Typed Dataset was created it generated a method to return a boolean value if the column data was Null.  So here is how you use it.

 

 define your table adapter:

xTableAdapter ds = new xtableAdapter;

Fill a datatable with the adapters resulting data:

databasename.xDataTable dt = ds.GetData();

Run throught the data and grab the values you need and change the Nulls into values you want.

foreach(databasename.xRow dr in dt)

{  decimal y;

//error check the column value first

    if (dr.Iscolumn1Null())

       { y = 0m;} else { y = dr.column1;}

}

 

That's it!  What sucks is that you have to use error checking in your script everytime you want to grab a column value in a typed dataset.  It should be handeled in the .xsd file.

 

 

Sunday, September 16, 2007

Handle null Values in DataSet, DataTable

When working with datasets and datatables we will run into issues where the resulting column values are null in the database.  These issues can cause your code to fail when you are using the values to make calculations or validations with the data.  The easiest way to handle this is to zero the null value using a custom method call.  The logic will also work with string values and here is how it works:

 object ZeroNull(object i, object defaultvalue)
    {
        if (i.Equals(DBNull.Value))
        {
            return defaultvalue;
        }
        else
        {
            return i;
        }
    }

add data to the dataset (see other blog for instructions)

DataSet ds = new DataSet
adapter.Fill(ds);

choose a row in the dataset to work with.

DataRow dr = ds.Rows[0];

Insert the column value into our new method to zero the null value if it is null otherwise it will return its actual value and cast it as a decimal.

(decimal)x = (decimal)ZeroNull(dr["columnName"], 0m);

 Good Luck

Sunday, August 19, 2007

Add Parameters to SQl Query using StoredProcedure C#, .Net

Here is how you will execute a stored procedure in the code behind script in .Net.  The parameter you pass to the procedure can come from controls, forms, defined variable, etc... In this example I will use the profile class to grab my values.

 

First step is to define the connection string.  Mine happens to be stored in the web.config file.

 

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["localconnstring"].
ConnectionString);

Define the command that used your stored procedure.


        SqlCommand cmd = new SqlCommand("stroredprocedure", conn);
        cmd.CommandType = CommandType.StoredProcedure;


Define the parameters.


        SqlParameter pr1 = new SqlParameter("@p1", SqlDbType.NVarChar, 50);
        pr1.Value = Profile.p1;//this is where you will set the value of the parameter passed to the query.  I happened to be calling on the profile for this value.
        cmd.Parameters.Add(pr1);

        SqlParameter pr2 = new SqlParameter("@p2", SqlDbType.NVarChar, 10);
        pr2.Value = Profile.p2;
        cmd.Parameters.Add(pr2);

And open the connection.

        conn.Open();

Thats it!  Now you can fill the resulting data into a dataset and bind it to a gridview.


        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = cmd;

        DataSet ds = new DataSet();
        adapter.Fill(ds);

      //  DataRow drow = ds.Tables[0].Rows[0]; use this to get after the column values.

         GridView1.DataSource = ds;
         GridView1.DataBind();

 

Tuesday, August 14, 2007

Fill Dataset with SqlDataAdapter and SQL query

First step to fill a dataset is to define the sql connection.  The method below uses the definition in the web.config fie which looks like this:

<connectionStrings>
      <clear />
  <add name="LocalSqlServer" connectionString="Server=192.169.1.1;Initial Catalog=DatabaseName;User ID=username;Password=password;"
   providerName="System.Data.SqlClient" />
</connectionStrings>

Once you have this defined in the config file then call on it by setting a string variable equal to the connectionstring.

String strCon1 = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].
ConnectionString;


Define a container for this connection string.

SqlConnection conn1 = new SqlConnection(strCon1);

Open the connection.


conn1.Open();

Next we set the select statement and put it into a string variable.


string sql1 = "SELECT [ApplicationId],[UserId],[UserName],[LoweredUserName],[MobileAlias],
[IsAnonymous],[LastActivityDate]
FROM [DatabaseName].[dbo].[table]
where [IsAnonymous] = '0' order by [LastActivityDate] desc";

Ok and now the magical adapter which will allow us to grab all of the data in the query and place it into an object that we can do some cool things with. Just set the adapter variable and execute a select command on it using the two string we just defined.


SqlDataAdapter dadapter = new SqlDataAdapter();
dadapter.SelectCommand = new SqlCommand(sql1, conn1);

Now we fill the dataset with all of the returned data from the select command.  A great feature with this method is that the table structure(schema) is retained in the new dataset.


DataSet dset = new DataSet();
dadapter.Fill(dset);

Now you can call on the values in the dataset by using the following syntax.
                     
DataRow dr = dset.Tables[0].Rows[i] ;
dr["userid"].tostring();

Another usefull method is to add the data to a Datatable.  I find it easier to work with datatables when you need to adjust the table values and bind them to a gridview.

Datatable dt = new Datatable
dadapter.Fill(dt);
           

 Good luck

San Diego Website Design
San Diego Flash Design
Testimonials
Contact Us
Support
Privacy Policy
Site Map