Wednesday, March 28, 2012

Utterly strange performance in the Entity Framework

Hello!

I'm trying the new Entity framework and I must say that I observe an utterly strange performance result. Is there a way to submit my solution for investigation at Microsoft?

Best regards,

Henrik Dahl

Hi Henrik,

Please briefly describe your scenario and the expected result and send me the solution for investigation to nvalluri at microsoft dot com.

regards,


Naveen Valluri,

I've now submitted the stuff to you.

Do you think you have a chance to look at it in short time - I'm really looking forward hearing from you?

Best regards,

Henrik Dahl


Naveen Valluri,

Have you managed to observe the same amazing consumption of computational resources when running the solution?

Best regards,

Henrik Dahl


Sorry for the delay in response. Naveen is actually out sick today. We'll try to connect with him and get back to you as soon as we can. Given that I don't have the details of your situation, I can't speak to it, but I will say that one of the things we are working on during this development milestone is a significant push for performance improvements... The difference in beta 3 should be really noticeable for some scenarios.

- Danny


Hello Danny!

OK.

I imagine Naveen will be sick for only a few days. I may easily wait for that and let him to recover in peace!

It sounds good with significant performance improvements. In the current case it took multiple hours to insert a singular row in a singular table so I think that here there's really room for multiple orders of magnitude of performance improvements.

Despite it's not really the subject of this thread, do you know of a rough estimation of availability of beta 3, is it for instance assumed to be released during the year of 2007?

Best regards,

Henrik Dahl


The intention is to line up beta 3 of the EF with Orcas RTM. So, yes, we intend that it will ship sometime before the end of this calendar year, but of course there are lots of things that could change between now and then.

- Danny


Daniel,

Yes, it's obvious, but thank you for sharing this.

I look forward hearing from Naveen as he'll be back again.

Best regards,

Henrik Dahl


Hi Henrik,

Thanks for your patience. We did observe the delay in inserting the record for the first time and this is in part because the framework compiles the model files. Any queries, inserts or updates after that is in sub-second range. In the current milestone, we have been working on improving the performance in this area. We tried your scenarios against our latest bits, which you will see delivered as part of Beta 3 in late November and the performance has significantly improved. The time to compile the model files is reduced to 20 seconds. Again, to reiterate, this is only the first time that CRUD operation goes to the server . Even for this, we are working towards making this happen during design time, so that the cost isn’t there at runtime.

Thanks,

Naveen


Given that view compilation is the source of the problem, you can also pre-compile your views even in beta 2, and then you will have a big hit during this initial step, but at runtime that hit will go away. I've been meaning to write a blog post on how to do that, but haven't gotten to it yet. Suddenly I feel motivated--now if only I could get the time to do it... The clue I'll give you now is to look at the commandline options on edmgen where there's a generateviews or something like that. This will output code that is a compiled version of the views which the EF uses for queries and updates. You can compile that into your assembly, and then things should get much faster at runtime.

- Danny

Utterly strange performance in the Entity Framework

Hello!

I'm trying the new Entity framework and I must say that I observe an utterly strange performance result. Is there a way to submit my solution for investigation at Microsoft?

Best regards,

Henrik Dahl

Hi Henrik,

Please briefly describe your scenario and the expected result and send me the solution for investigation to nvalluri at microsoft dot com.

regards,


Naveen Valluri,

I've now submitted the stuff to you.

Do you think you have a chance to look at it in short time - I'm really looking forward hearing from you?

Best regards,

Henrik Dahl


Naveen Valluri,

Have you managed to observe the same amazing consumption of computational resources when running the solution?

Best regards,

Henrik Dahl


Sorry for the delay in response. Naveen is actually out sick today. We'll try to connect with him and get back to you as soon as we can. Given that I don't have the details of your situation, I can't speak to it, but I will say that one of the things we are working on during this development milestone is a significant push for performance improvements... The difference in beta 3 should be really noticeable for some scenarios.

- Danny


Hello Danny!

OK.

I imagine Naveen will be sick for only a few days. I may easily wait for that and let him to recover in peace!

It sounds good with significant performance improvements. In the current case it took multiple hours to insert a singular row in a singular table so I think that here there's really room for multiple orders of magnitude of performance improvements.

Despite it's not really the subject of this thread, do you know of a rough estimation of availability of beta 3, is it for instance assumed to be released during the year of 2007?

Best regards,

Henrik Dahl


The intention is to line up beta 3 of the EF with Orcas RTM. So, yes, we intend that it will ship sometime before the end of this calendar year, but of course there are lots of things that could change between now and then.

- Danny


Daniel,

Yes, it's obvious, but thank you for sharing this.

I look forward hearing from Naveen as he'll be back again.

Best regards,

Henrik Dahl


Hi Henrik,

Thanks for your patience. We did observe the delay in inserting the record for the first time and this is in part because the framework compiles the model files. Any queries, inserts or updates after that is in sub-second range. In the current milestone, we have been working on improving the performance in this area. We tried your scenarios against our latest bits, which you will see delivered as part of Beta 3 in late November and the performance has significantly improved. The time to compile the model files is reduced to 20 seconds. Again, to reiterate, this is only the first time that CRUD operation goes to the server . Even for this, we are working towards making this happen during design time, so that the cost isn’t there at runtime.

Thanks,

Naveen


Given that view compilation is the source of the problem, you can also pre-compile your views even in beta 2, and then you will have a big hit during this initial step, but at runtime that hit will go away. I've been meaning to write a blog post on how to do that, but haven't gotten to it yet. Suddenly I feel motivated--now if only I could get the time to do it... The clue I'll give you now is to look at the commandline options on edmgen where there's a generateviews or something like that. This will output code that is a compiled version of the views which the EF uses for queries and updates. You can compile that into your assembly, and then things should get much faster at runtime.

- Danny

Utterly strange performance in the Entity Framework

Hello!

I'm trying the new Entity framework and I must say that I observe an utterly strange performance result. Is there a way to submit my solution for investigation at Microsoft?

Best regards,

Henrik Dahl

Hi Henrik,

Please briefly describe your scenario and the expected result and send me the solution for investigation to nvalluri at microsoft dot com.

regards,


Naveen Valluri,

I've now submitted the stuff to you.

Do you think you have a chance to look at it in short time - I'm really looking forward hearing from you?

Best regards,

Henrik Dahl


Naveen Valluri,

Have you managed to observe the same amazing consumption of computational resources when running the solution?

Best regards,

Henrik Dahl


Sorry for the delay in response. Naveen is actually out sick today. We'll try to connect with him and get back to you as soon as we can. Given that I don't have the details of your situation, I can't speak to it, but I will say that one of the things we are working on during this development milestone is a significant push for performance improvements... The difference in beta 3 should be really noticeable for some scenarios.

- Danny


Hello Danny!

OK.

I imagine Naveen will be sick for only a few days. I may easily wait for that and let him to recover in peace!

It sounds good with significant performance improvements. In the current case it took multiple hours to insert a singular row in a singular table so I think that here there's really room for multiple orders of magnitude of performance improvements.

Despite it's not really the subject of this thread, do you know of a rough estimation of availability of beta 3, is it for instance assumed to be released during the year of 2007?

Best regards,

Henrik Dahl


The intention is to line up beta 3 of the EF with Orcas RTM. So, yes, we intend that it will ship sometime before the end of this calendar year, but of course there are lots of things that could change between now and then.

- Danny


Daniel,

Yes, it's obvious, but thank you for sharing this.

I look forward hearing from Naveen as he'll be back again.

Best regards,

Henrik Dahl


Hi Henrik,

Thanks for your patience. We did observe the delay in inserting the record for the first time and this is in part because the framework compiles the model files. Any queries, inserts or updates after that is in sub-second range. In the current milestone, we have been working on improving the performance in this area. We tried your scenarios against our latest bits, which you will see delivered as part of Beta 3 in late November and the performance has significantly improved. The time to compile the model files is reduced to 20 seconds. Again, to reiterate, this is only the first time that CRUD operation goes to the server . Even for this, we are working towards making this happen during design time, so that the cost isn’t there at runtime.

Thanks,

Naveen


Given that view compilation is the source of the problem, you can also pre-compile your views even in beta 2, and then you will have a big hit during this initial step, but at runtime that hit will go away. I've been meaning to write a blog post on how to do that, but haven't gotten to it yet. Suddenly I feel motivated--now if only I could get the time to do it... The clue I'll give you now is to look at the commandline options on edmgen where there's a generateviews or something like that. This will output code that is a compiled version of the views which the EF uses for queries and updates. You can compile that into your assembly, and then things should get much faster at runtime.

- Danny

V$session : Session not Closed

I connect to Oracle DB thru JDBC. I used CLIENT_INFO field in V$SESSION to store my intranet Application's User Name along with Username.
I controlled the user access thru checking that field. I assumed even if user goes out of that page, session will be closed automatically. But one of client went to other page by mistaken. He restarted the IE as well his own machine. But still the session is not closed. I can see the session in V$session.
Any idea whether such problems are preventable. i cannot even close that session from my machine. How to close that session.
Thank you in advance..Note that you probably want to address JDBC questions to the JDBC forum rather than the ODBC forum-- different protocols, different products.
Justin

v1.1 - datagrid - naming headers

hi,

I have had to create a bunch of field names in my table as (i.e) "20071225" (for 25-dec-2007).

But in my datagrid I want "25-dec-2007" as my column headers.

How would i achieve this?

Thanks,

John

I've answered my own question in case anyone else was interested.

I wanted to change my "col" (foreach(DataColumn colin dt.Columns) )

- where col.ColumnName.ToString() = "20071225"

I ended up changing the DataTable column names and then the bind to the Datagrid simply picked them up correctly.

-------

string stopval = col.ColumnName.ToString();

string year = stopval.Substring(0, 4);

string month = stopval.Substring(4, 2);

string day = stopval.Substring(6, 2);

// extra faffing to get MON

dtme = Convert.ToDateTime(day + "-" + month + "-" + year);

string strMonth = dtme.ToString("MMM");

col.ColumnName = day + "-" + strMonth + "-" + year;

--------

- now col.ColumnName.ToString() = "25-Dec-2007"

V8.16 returns error message upon opening database.

When opening a database using V8.16 support files and drivers the following error message is returned. "ODBC - Tunnel Error ORA-01456: may not perform insert/delete/update operation inside a READ ONLY transaction.
This error does not occur using V8.15.
What is the cause of this problem?You don't by any chance have the 'connect in read-only mode' option checked on your DSN do you?
Justin Cave

Vague error on data source - hard to debug

I have this error:

Server Error in '/247 Website' Application.

A field or property with the name 'armAreaName' was not found on the selected data source.

I have several data sources, any ideas if I can find outwhichdata source is at error here?

Look at your code. It will be the one that tries to reference a field called armAreaName.


Ok fair enough, I found it in my code eventually. I find its difficult to find the error working in design mode so I switched to code mode. However it would be nice if the error specified at least the datasource which was falling over.

Thanks anyway.


Design Mode has very few practical uses. Drag and drop and double click for event handlers is about it. It's definitely not the place to be when trying to debug runtime errors.

Valid Access Query Creates Empty Table using OleDbCommand?

I have a very simple query which runs through the Northwind customers table and extracts all CustomerIDs who live in a city starting with 'P'. It works great if I double-click on it in Access, but when I run it through my VB code, an empty table is created. Any idea what is going on?

Here is the very simple query text, which works well in MS Access, called 'MyQuery':

SELECT DISTINCT Customers.CustomerID, Customers.City INTO pCityCustomerIDs
FROM Customers
WHERE (((Customers.City) Like "P*"));

Here is my very simple VB Code:

Public Function ExecuteProcedure(ByVal sFileLocation As String) As Integer

Dim dcMSAccessConnection As OleDb.OleDbConnection = New OleDb.OleDbConnection( _

"Provider= Microsoft.Jet.OLEDB.4.0;Data Source=" & sFileLocation)

Dim myCmd As New OleDb.OleDbCommand

myCmd.CommandText = "MyQuery"

myCmd.CommandType = CommandType.StoredProcedure

myCmd.Connection = dcMSAccessConnection

Dim rowsAffected As Integer

' Open Connection, run the query, then close the connection

dcMSAccessConnection.Open()

rowsAffected = myCmd.ExecuteNonQuery

dcMSAccessConnection.Close()

Return rowsAffected

End Function


Under ADO (Jet OLEDB) the wildcard character is a percent sign. The asterisk is specific to DAO and Microsoft Access.

SELECT DISTINCT Customers.CustomerID, Customers.City INTO pCityCustomerIDs
FROM Customers
WHERE (((Customers.City) Like "P%"));


try with:

myCmd.ExecuteReader


Thanks Paul,

The devil is in the details.

Validaiton Control

Anyone knows how to add validation controls to the GridView fields when one click on edit?Add the validators within the EditItemTemplates, as in this demo:http://www.webswapp.com/codesamples/aspnet20/dropdownlist_gridview/default.aspx
Care to explain? Thks

Valida an XML file

I'd like to validate an xml file against an Schema and 3 tables (As lookups)
online from my database. I am thinkning to return an structure like a
dataset from a webserivce and then try to load the xml into the dataset
offline and show the user the errors? Dose this appraoch work?
Thanks a lotThe XmlValidatingReader can be used for this purpose, provided you have an
XSD to run against. Another validation option is running the XML through and
XSL doc.
--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
***************************
Think Outside the Box!
***************************
"J-T" wrote:
> I'd like to validate an xml file against an Schema and 3 tables (As lookups)
> online from my database. I am thinkning to return an structure like a
> dataset from a webserivce and then try to load the xml into the dataset
> offline and show the user the errors? Dose this appraoch work?
>
> Thanks a lot
>
>
But where should I keep the data of my lookup tables? That's why I was
thinking of a container like dataset.
Thanks
"Cowboy (Gregory A. Beamer) - MVP" <NoSpamMgbworld@.comcast.netNoSpamM> wrote
in message news:286533D1-EF64-4A20-8F55-FA5709DF92B4@.microsoft.com...
> The XmlValidatingReader can be used for this purpose, provided you have an
> XSD to run against. Another validation option is running the XML through
> and
> XSL doc.
> --
> Gregory A. Beamer
> MVP; MCP: +I, SE, SD, DBA
> ***************************
> Think Outside the Box!
> ***************************
>
> "J-T" wrote:
>> I'd like to validate an xml file against an Schema and 3 tables (As
>> lookups)
>> online from my database. I am thinkning to return an structure like a
>> dataset from a webserivce and then try to load the xml into the dataset
>> offline and show the user the errors? Dose this appraoch work?
>>
>> Thanks a lot
>>
JT.
At first sight, "Why not?, however don't forget to write the schema.
\\\
ds.WriteXml("path",XmlWriteMode.WriteSchema)
///
I hope this helps.
Cor
So you mean that I can get whatever I want from the webserivce and dump it
into the client machines(Schema + Data) and from then onwrads the client can
work offline and also to be able to connect from while to while and get the
latest schema and data,right?
Thanks
"Cor Ligthert [MVP]" <notmyfirstname@.planet.nl> wrote in message
news:esXfEN9nFHA.764@.TK2MSFTNGP14.phx.gbl...
> JT.
> At first sight, "Why not?, however don't forget to write the schema.
> \\\
> ds.WriteXml("path",XmlWriteMode.WriteSchema)
> ///
> I hope this helps.
> Cor
>

Validate a CSV file

I have a CSV file which contains comma seperated data that I need to
validate against our database.I was thinking about loading that CSV file
into a Typed-Dataset which has our database schema in it and then try to
load the CSV file into that Typed-Dataset and automatically get all the
errors and constarint violations.
1) Is it doable?
2) Because I need to check the foriegn keys as well,Can I loaded the data of
those refferecing tables into my dataset as well?
3)If number 2 is doable ,how should I update my dataset if a key has been
added to the existing refferncing tables?
Thanks a lot for taking your time answering this post in advance.
J-TI suggest using BCP to upload it to a work table and doing the INSERTs from
a SP into a clone of the target table (just schema). When the INSERT
completes, the data is validated and can safely be inserted into the working
table. Then all you have to worry about is the RI issues.
--
____________________________________
William (Bill) Vaughn
Author, Mentor, Consultant
Microsoft MVP
www.betav.com/blog/billva
www.betav.com
Please reply only to the newsgroup so that others can benefit.
This posting is provided "AS IS" with no warranties, and confers no rights.
__________________________________
"J-T" <J-T@.nospam.com> wrote in message
news:uEyAI7ukFHA.3756@.TK2MSFTNGP15.phx.gbl...
>I have a CSV file which contains comma seperated data that I need to
>validate against our database.I was thinking about loading that CSV file
>into a Typed-Dataset which has our database schema in it and then try to
>load the CSV file into that Typed-Dataset and automatically get all the
>errors and constarint violations.
> 1) Is it doable?
> 2) Because I need to check the foriegn keys as well,Can I loaded the data
> of those refferecing tables into my dataset as well?
> 3)If number 2 is doable ,how should I update my dataset if a key has been
> added to the existing refferncing tables?
>
> Thanks a lot for taking your time answering this post in advance.
> J-T
>
I'm exactly doing this using a DTS package ,but I'd like to give my user the
ability to validate his file using our web application.Now they upload their
files to our system through web application and then using DTS packages we
process them and report them back all the errors in their file ,ofcourse in
DTS we have buiness rules and stuff like that but here I'd like to give my
user the ability to make sure that his file is not malformed,has the
appropriate number of columns,and just validate the CSV file rather than
validation and applying business rules.
Thanks
"William (Bill) Vaughn" <billvaRemoveThis@.nwlink.com> wrote in message
news:OHpXZZvkFHA.3580@.TK2MSFTNGP09.phx.gbl...
>I suggest using BCP to upload it to a work table and doing the INSERTs from
>a SP into a clone of the target table (just schema). When the INSERT
>completes, the data is validated and can safely be inserted into the
>working table. Then all you have to worry about is the RI issues.
> --
> ____________________________________
> William (Bill) Vaughn
> Author, Mentor, Consultant
> Microsoft MVP
> www.betav.com/blog/billva
> www.betav.com
> Please reply only to the newsgroup so that others can benefit.
> This posting is provided "AS IS" with no warranties, and confers no
> rights.
> __________________________________
> "J-T" <J-T@.nospam.com> wrote in message
> news:uEyAI7ukFHA.3756@.TK2MSFTNGP15.phx.gbl...
>>I have a CSV file which contains comma seperated data that I need to
>>validate against our database.I was thinking about loading that CSV file
>>into a Typed-Dataset which has our database schema in it and then try to
>>load the CSV file into that Typed-Dataset and automatically get all the
>>errors and constarint violations.
>> 1) Is it doable?
>> 2) Because I need to check the foriegn keys as well,Can I loaded the data
>> of those refferecing tables into my dataset as well?
>> 3)If number 2 is doable ,how should I update my dataset if a key has been
>> added to the existing refferncing tables?
>>
>> Thanks a lot for taking your time answering this post in advance.
>> J-T
>
This validation step is where I normally use a csv parser like the one
I happen to sell, http://www.csvreader.com . This way on a row by row
basis, I can run all kinds of validation code, even possibly save the
good results out to another csv file to upload using the DTS package.
That's what I would recommend. I've also in this process mapped
multiple input column names with the same meaning, ie. Qty, Count,
Quantity, etc, to one resulting output column that matched my database
table's column name. You could load the data into a typed dataset if
that will work, but if you're only dealing with one fk constraint, I'd
be more likely to select out just the list of pk's, and then on a row
by row basis, do like a hash lookup to see if it's defined as one of
the pk's. This should give you better performance than loading all the
csv data up into the dataset, and then letting the dataset constraints
give you the errors, which from my experience isn't actually that nice
performancewise.
J-T wrote:
> I'm exactly doing this using a DTS package ,but I'd like to give my user the
> ability to validate his file using our web application.Now they upload their
> files to our system through web application and then using DTS packages we
> process them and report them back all the errors in their file ,ofcourse in
> DTS we have buiness rules and stuff like that but here I'd like to give my
> user the ability to make sure that his file is not malformed,has the
> appropriate number of columns,and just validate the CSV file rather than
> validation and applying business rules.
> Thanks
> "William (Bill) Vaughn" <billvaRemoveThis@.nwlink.com> wrote in message
> news:OHpXZZvkFHA.3580@.TK2MSFTNGP09.phx.gbl...
> >I suggest using BCP to upload it to a work table and doing the INSERTs from
> >a SP into a clone of the target table (just schema). When the INSERT
> >completes, the data is validated and can safely be inserted into the
> >working table. Then all you have to worry about is the RI issues.
> >
> > --
> > ____________________________________
> > William (Bill) Vaughn
> > Author, Mentor, Consultant
> > Microsoft MVP
> > www.betav.com/blog/billva
> > www.betav.com
> > Please reply only to the newsgroup so that others can benefit.
> > This posting is provided "AS IS" with no warranties, and confers no
> > rights.
> > __________________________________
> >
> > "J-T" <J-T@.nospam.com> wrote in message
> > news:uEyAI7ukFHA.3756@.TK2MSFTNGP15.phx.gbl...
> >>I have a CSV file which contains comma seperated data that I need to
> >>validate against our database.I was thinking about loading that CSV file
> >>into a Typed-Dataset which has our database schema in it and then try to
> >>load the CSV file into that Typed-Dataset and automatically get all the
> >>errors and constarint violations.
> >>
> >> 1) Is it doable?
> >>
> >> 2) Because I need to check the foriegn keys as well,Can I loaded the data
> >> of those refferecing tables into my dataset as well?
> >>
> >> 3)If number 2 is doable ,how should I update my dataset if a key has been
> >> added to the existing refferncing tables?
> >>
> >>
> >> Thanks a lot for taking your time answering this post in advance.
> >>
> >> J-T
> >>
> >
> >
Thanks for your reply,
>> but if you're only dealing with one fk constraint
No In my CSV file there are 33 columns which 20 of it would be foriegn key
lookups.
I cannot afford buyinh that product ,is there something free around?
Thanks again
"shriop" <shriop@.hotmail.com> wrote in message
news:1122522664.804866.161650@.f14g2000cwb.googlegroups.com...
> This validation step is where I normally use a csv parser like the one
> I happen to sell, http://www.csvreader.com . This way on a row by row
> basis, I can run all kinds of validation code, even possibly save the
> good results out to another csv file to upload using the DTS package.
> That's what I would recommend. I've also in this process mapped
> multiple input column names with the same meaning, ie. Qty, Count,
> Quantity, etc, to one resulting output column that matched my database
> table's column name. You could load the data into a typed dataset if
> that will work, but if you're only dealing with one fk constraint, I'd
> be more likely to select out just the list of pk's, and then on a row
> by row basis, do like a hash lookup to see if it's defined as one of
> the pk's. This should give you better performance than loading all the
> csv data up into the dataset, and then letting the dataset constraints
> give you the errors, which from my experience isn't actually that nice
> performancewise.
> J-T wrote:
>> I'm exactly doing this using a DTS package ,but I'd like to give my user
>> the
>> ability to validate his file using our web application.Now they upload
>> their
>> files to our system through web application and then using DTS packages
>> we
>> process them and report them back all the errors in their file ,ofcourse
>> in
>> DTS we have buiness rules and stuff like that but here I'd like to give
>> my
>> user the ability to make sure that his file is not malformed,has the
>> appropriate number of columns,and just validate the CSV file rather than
>> validation and applying business rules.
>> Thanks
>> "William (Bill) Vaughn" <billvaRemoveThis@.nwlink.com> wrote in message
>> news:OHpXZZvkFHA.3580@.TK2MSFTNGP09.phx.gbl...
>> >I suggest using BCP to upload it to a work table and doing the INSERTs
>> >from
>> >a SP into a clone of the target table (just schema). When the INSERT
>> >completes, the data is validated and can safely be inserted into the
>> >working table. Then all you have to worry about is the RI issues.
>> >
>> > --
>> > ____________________________________
>> > William (Bill) Vaughn
>> > Author, Mentor, Consultant
>> > Microsoft MVP
>> > www.betav.com/blog/billva
>> > www.betav.com
>> > Please reply only to the newsgroup so that others can benefit.
>> > This posting is provided "AS IS" with no warranties, and confers no
>> > rights.
>> > __________________________________
>> >
>> > "J-T" <J-T@.nospam.com> wrote in message
>> > news:uEyAI7ukFHA.3756@.TK2MSFTNGP15.phx.gbl...
>> >>I have a CSV file which contains comma seperated data that I need to
>> >>validate against our database.I was thinking about loading that CSV
>> >>file
>> >>into a Typed-Dataset which has our database schema in it and then try
>> >>to
>> >>load the CSV file into that Typed-Dataset and automatically get all the
>> >>errors and constarint violations.
>> >>
>> >> 1) Is it doable?
>> >>
>> >> 2) Because I need to check the foriegn keys as well,Can I loaded the
>> >> data
>> >> of those refferecing tables into my dataset as well?
>> >>
>> >> 3)If number 2 is doable ,how should I update my dataset if a key has
>> >> been
>> >> added to the existing refferncing tables?
>> >>
>> >>
>> >> Thanks a lot for taking your time answering this post in advance.
>> >>
>> >> J-T
>> >>
>> >
>> >
>

Validate a field

I have a very simple question.

I want to validate a textbox field by using the requiredfieldvalidator.

but that should only happen when i click on a particular button and not all the buttons.

i have a textbox for search and i don't want any blank values in that box so using validator, but i want to use the other buttons on the page.

pls help

Easily remedied :)

First set the validator's 'ValidationGroup' property to something that describes your validation. Eg. 'Search'

Then set the button's 'ValidationGroup' property to the same thing as the validator's so that it will fire only the validator you have defined.


Thanks a lot.....

validate a value from a textbox column in dataGrid

I have a datagrid which has three columns and one is a textBox templateColumn Quantity. I want to validate the value entered by the user in this column... ...is there a way I can validate the value. the other two columns get their value from the Xml file..so the textbox column is the only one where a user enter the value.

Thanks for your help
Neelayu can use validator control. if i need to do that, i just open the page in HTML format and type the necessary code with ControlToValidate property set to the control for which the validator is to be used.

validate boundfield before inserting into database

Hi,

i am trying to validate that the user has entered "http://" in a textbox boundfield control before saving to the database.

this is what i have:

TextBox txt = (TextBox)FormView1.FindControl("additionalInformationTextBox");
if (txt.Text.IndexOf("http://") == -1)
{
txt.Text = txt.Text.Insert(0, "http://");
}

now i want this new version to be saved in the database. I tried the
FormView1_ItemInserting and AccessDataSourceAddNewWord_Inserting events but they are not adding the updated version of the link into the database.

thanks for the help
john

This works for Updating and inserting event handler..

protectedvoid ObjectDataSource1_Updating(object sender,ObjectDataSourceMethodEventArgs e)

{

//change things before the pipe returns the object to the update method.

//grab my object

DbTableEntity d = (DbTableEntity)e.InputParameters[0];

if (!((TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("tbRetDate")).Text.Length.Equals(0))

{

d.RetireDate =DateTime.Parse(((TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("tbRetDate")).Text);

}

}

Validate Datagrid inputs?

I'm trying to validate data when updating a datagrid.

I'm using a RegularExpressionValidator and a Validiationsummary.
In this case I fist tried to create the Validator in code at runtime but I couldn't get it to work!

Then I took a RegularExpressionValidator control from the toolbox and set the errorMessage and ControlToValidate properties in the code, and tried to get the control to validate from the update code:


TextBox tbtel;
tbtel = (TextBox)(e.Item.Cells[3].Controls[0]);

RegularExpressionValidator2.ControlToValidate="tbtel"; //error!!
RegularExpressionValidator2.ErrorMessage="Wrong format!";
RegularExpressionValidator2.Validate();

This didn't work!

How do I validate a control like this, that is created "in code" at runtime?
I think that it has something to do with the ID of the control!?
How do I get the ID?

It works when I have a default Textbox and validates it !
But then the validiationSummaryControl.messagebox won't get executed until I press update twise or presses a button with no code behind!?
I think it has something to do with updating the page...

Code:


TextBox tbtel;
tbtel = (TextBox)(e.Item.Cells[3].Controls[0]);
TextBox1.Text=tbtel.Text;

RegularExpressionValidator2.ControlToValidate="TextBox1";
RegularExpressionValidator2.ErrorMessage="Wrong format!";
RegularExpressionValidator2.Validate();

Is there an easy way to do this??

/Regards
AndersAs far as I know, you cannot validate datagrid inputs.

Validate Data in SQL table

I have a form that the user enters values on it. One of the fields I need to
validate what is being entered against records in a SQL table.
Something like doing a findfirst in Access and then doing a nomatch.
How do I go about doing this?
Thanks In Advance,
LouU¿ytkownik "Lou Civitella" <lou@.webersystems.com> napisa³ w wiadomo¶ci
news:ewjBafHuEHA.2300@.TK2MSFTNGP09.phx.gbl...
>I have a form that the user enters values on it. One of the fields I need
>to
> validate what is being entered against records in a SQL table.
> Something like doing a findfirst in Access and then doing a nomatch.
> How do I go about doing this?
Create command (text or stored proc) that will check data in SQL Table.
Regards,
Grzegorz
Hi Lou,
Change the textbox to a combobox; then load the data from the table into the
combobox and the user can only pick valid data, by definition.
HTH,
Bernie Yaeger
"Lou Civitella" <lou@.webersystems.com> wrote in message
news:ewjBafHuEHA.2300@.TK2MSFTNGP09.phx.gbl...
>I have a form that the user enters values on it. One of the fields I need
>to
> validate what is being entered against records in a SQL table.
> Something like doing a findfirst in Access and then doing a nomatch.
> How do I go about doing this?
> Thanks In Advance,
> Lou
>

Validate data in GridView cell (while editing)

Hi,

Have someone any suggestions how to validate data that user write in GridView cell while editing it,
or even allow him to write only proper characters.

In my gridview user in some cells should only write numbers {1,3,9} in other {1,2,3,4,5}. How to check if he write numbers correctly?

Add the validators to the template field which will control the validatation of the input. For examle,

<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ProductName") %>' Visible = false></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate = "TextBox1" ErrorMessage="RequiredFieldValidator">
</asp:RequiredFieldValidator>
</EditItemTemplate>


For custom validator:http://www.asp.net/QuickStart/aspnet/doc/validation/default.aspx


Thanks

Validate Details View

Is it possible to validate text fields with in a Details View. Do I need to to it in the Template editor? if so how?

Hi nhaas:

<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ValidationGroup="InitiateJobEdit"
ControlToValidate="DropDownList1"
InitialValue="0" Text="(select one)" Runat="Server" /
in the EditItemTemplate source

And call Page.Validator in your update event.


Thanks I will try it in the morning!

Validate ddl selection on page load event?

User's previos ddl selection is saved and then attempting to select it for them on page load. What to do if selection no longer exists - msgbox in page load seems like something that should not be done. How can I notify user that their selection no longer exists so the ddl selection is being reset to default?What about using a label to display the error message? Set the Label Visible property to False in the designer, then if the selection no longer exists in Page_Load, set the Label Visible property to True. If you are wanting to present an error message in a popup dialog similar to MsgBox, that requires client-side code.

Validate FCKeditor input for maximum characters

I need to validate input for maximum characters into a FCKeditor textbox. I've seen this question, and variations on it, posted all over the place but haven't come across any clean solutions. Off the top of my head I can think of only two approaches:

1. Do some server side validation for maximum characters and return an error message if entered > max OR

2. Truncate the entry so as not to exceed the SQL Server column size and just caption the text box.

#2 is fine with me though I don't know how to go about doing it. I would much rather do the #1 method. Can anyone suggest how I may get this done?

Thanks

OnSubmit or whenever you want to do your check:

if ( FCKEditor.value.length > maxLength){ e.Cancel =true; lblError.Text ="Your value input is too long, please edit it by removing " + FCKEditor.value.length - maxlength +" characters from your input."; lblError.Visible =true; }

Validate for 1 text box only

Hello i have 4 textboxes, but the user must enter data in atleast 1 of the 4. How do you do this with the validation controls?

Best,
AsafTake a look at this post

Please, don't post the same kind of question that you already posted. If any one can answer your question I promise they will. If you need to clarity or make the question more detailed, please add a new post as a reply to your question instead of adding a new post.

Thanks for the understanding.

Validate inside details view or formview?

I havent tried but how can I validate for inserting and updating inside this control?. Do I have to convert to template and then edit manually and insert the validators?I dont know how that will work for a DetailsView or FormView, but when I use a normal datagrid, then I used EditItemTemplates and added the validators manually as you described.

Validate item on insert in DetailsView

Hi. Is there a way to validate a value that's being inserted from a DetailsView? We've got the event handler for the "on inserting", but not sure how to grab the column value and validate it. How do you display an error on that item to let the user know to change it? Thank you.

Option 1) You could turn item into a template field and add validation controls.

Option 2) In your Item_Inserting Function you can capture bound fields as follows. This code would stop a blank field in row 1 from being inserted.

ProtectedSub DetailsView1_ItemInserting(ByVal senderAsObject,ByVal eAs System.Web.UI.WebControls.DetailsViewInsertEventArgs)Handles DetailsView1.ItemInserting If e.Values(0).ToString =NothingThen 'Change the 0 to the row you want to capture 'Display Error Message

e.Cancel =

True'This cancels the insert EndIfEndSub
Thanks, getdotnethelp. That worked like a charmBig Smile

Validate Model

Apparently the 'Validate Model' item of Entity designer context menu, doesn't work (do nothing)

I thought that 'Validate Model' served to check database schema and eventually update mapped entity: so I try to add a new field to a mapped table and tried it, but it doesn't work.

Am I bad thinking ?

Isn't there a similar function ? If not, how can I bring up to date my entities ? I need to recreate the entire model (losing entity modifications) ?

Luca

Hi! Luca,

The "Validate Model" functionality in the designer verifies that that the model and mappings are consistent. For example, it verifies that entities in the conceptual model are correct (e.g. entities have a key, etc) and validates that entities are mapped correctly to the storage model and reports errors in Visual Studio. It does not update the model and mappings to reflect the current state of the database.

We are looking to add some sort of "refresh model from database" functionality in a subsequent release. For this CTP, you can recreate the model & mappings by running the wizard again in a new .edmx file.

Regards,

Sanjay


We are looking to add some sort of "refresh model from database" functionality in a subsequent release. For this CTP, you can recreate the model & mappings by running the wizard again in a new .edmx file.

Therefore abandoning all work accomplished in the designer? For such a highly anticipated release, it is frustrating to me that its still not usable. Doesnt really lend itself to a TDD\Agile environment. Guess its back to hacking the xml files.... sigh.

(I know its a CTP, just dissapointed)

Validate Model

Apparently the 'Validate Model' item of Entity designer context menu, doesn't work (do nothing)

I thought that 'Validate Model' served to check database schema and eventually update mapped entity: so I try to add a new field to a mapped table and tried it, but it doesn't work.

Am I bad thinking ?

Isn't there a similar function ? If not, how can I bring up to date my entities ? I need to recreate the entire model (losing entity modifications) ?

Luca

Hi! Luca,

The "Validate Model" functionality in the designer verifies that that the model and mappings are consistent. For example, it verifies that entities in the conceptual model are correct (e.g. entities have a key, etc) and validates that entities are mapped correctly to the storage model and reports errors in Visual Studio. It does not update the model and mappings to reflect the current state of the database.

We are looking to add some sort of "refresh model from database" functionality in a subsequent release. For this CTP, you can recreate the model & mappings by running the wizard again in a new .edmx file.

Regards,

Sanjay


We are looking to add some sort of "refresh model from database" functionality in a subsequent release. For this CTP, you can recreate the model & mappings by running the wizard again in a new .edmx file.

Therefore abandoning all work accomplished in the designer? For such a highly anticipated release, it is frustrating to me that its still not usable. Doesnt really lend itself to a TDD\Agile environment. Guess its back to hacking the xml files.... sigh.

(I know its a CTP, just dissapointed)

Validate multiple text boxes together...

Hopefully I can explain this clearly...

I have a form which accepts inputs. I have 10 fields, a few do individual validation (check for date value, etc.)

Specifically, there are 3 fields (textbox1, textbox2, textbox3) and I want to validate that the user either:
- Enter values for all 3 fields, or
- Leave all three blank.

How can I do that?? I've looked into the current .NET validation and I can't figure out how to do it.

Thanks.

You can use javascript..


jodybannon:

Hopefully I can explain this clearly...

I have a form which accepts inputs. I have 10 fields, a few do individual validation (check for date value, etc.)

Specifically, there are 3 fields (textbox1, textbox2, textbox3) and I want to validate that the user either:
- Enter values for all 3 fields, or
- Leave all three blank.

How can I do that?? I've looked into the current .NET validation and I can't figure out how to do it.

Thanks.

You can either use a validation Summary or a Javascript.

Suppose you have a form

<form onSubmit="return Validate">textbox code...goes here..</form>

Now

<script type="text/javascript">

function Validate()

{

//get textboxes

textbox1=document.getElementById(<%=textbox.clientId%>) and so on..

if (textbox1=="")||(textbox2=="")||(textbox3=="")

{

return false;

}

else

return true;

}

</script>

Validate Only Certain GridView Row

We've got a GridView control which displays various information and has one column with a TextBox and another with a Button that adds a new record to the database. This works fine, it gets the value from the TextBox and the other controls perfectly and there is no problems inserting them into the database. The problem is, however, trying to validate the TextBox input, as it has to be an integer.

Using a RequiredFieldValidator (to make sure it's not null) and a RegularExpressionValidator (to make sure it's an integer) also works perfectly, but only when there's one record in the GridView. When there's more than one, every TextBox is validated, but we only want the one on the same row as the button that was clicked to be validated.

In other words, if the button on row #1 is clicked, only the TextBox on row #1 should be validated, if the button on row #2 is clicked, only the TextBox on row #2 should be validated and so on.

The index of the row can be found by sender.Parent.Parent.RowIndex (sender being the button) but we're unsure of how to make only that row be validated.

Can anybody help?

Thanks.

Why do you use a CustomValidator control?
Why don't you use a CustomValidator control?

Could you give me a bit of a clue as to how to write one for this situation?

This being my first real project, the concepts are relatively easy to figure out but putting them into practice is alot harder.


Use this link. Basically you create a customvalidator control in place of your requiredfieldvalidator and regularexpressionvalidator.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwebuiwebcontrolscustomvalidatormemberstopic.asp


The validation part itself is fine, it now works exactly the same as the RequiredFieldValidator and the RegularExpressionValidator, but the problem still remains, it validates every TextBox, not just the one from the specific row.
please post your code.

Just took out the expression part for the sake of simplicity, but it makes no difference to whether it validates the right control or not.

The "sender.Parent.Parent.RowIndex" bit is supposed to select only the correct row, but obviously that doesn't work, cause it does every one.

Protected Sub Quantity(ByVal senderAs Object,ByVal argsAs ServerValidateEventArgs)Dim QuantityAs TextBox = ProductsGrid.Rows(sender.Parent.Parent.RowIndex).FindControl("Quantity")If Quantity.Text =""Then args.IsValid =False Else args.IsValid =True End IfEnd Sub

Hi,b00f;

You may use client side validationg with Javascript in your page.

Here is the sample of a client side validationg of RadioButton Wish it helps;

http://www.codeproject.com/aspnet/ClientsideValidationRB.asp


rexlin:

Hi,b00f;

You may use client side validationg with Javascript in your page.

Here is the sample of a client side validationg of RadioButton Wish it helps;

http://www.codeproject.com/aspnet/ClientsideValidationRB.asp


Hi,b00f;

You may use client side validationg with Javascript in your page.

Here is the sample of a client side validationg of RadioButton Wish it helps;

http://www.codeproject.com/aspnet/ClientsideValidationRB.asp

Cheers for the suggestion, but we just managed to figure it out in an easier way (perhaps not the best way, good enough though).

Simply, when the button is clicked, it goes through each row in the GridView and sets the validators as being true (irrespective of what is in the TextBox). Then, it calls the validate method on only the controls on the same row from which the button was clicked (using sender.Parent.Parent.RowIndex). The code is below, it's probably easier to understand then my explanation.

Dim RowAs GridViewRowFor Each RowIn ProductsGrid.RowsDim RequiredQuantityTrueAs RequiredFieldValidator = ProductsGrid.Rows(Row.RowIndex).FindControl("RequiredQuantity")Dim QuantityExpressionTrueAs RegularExpressionValidator = ProductsGrid.Rows(Row.RowIndex).FindControl("QuantityExpression") RequiredQuantityTrue.IsValid =True QuantityExpressionTrue.IsValid =TrueNext RowDim RequiredQuantityAs RequiredFieldValidator = ProductsGrid.Rows(sender.Parent.Parent.RowIndex).FindControl("RequiredQuantity")Dim QuantityExpressionAs RegularExpressionValidator = ProductsGrid.Rows(sender.Parent.Parent.RowIndex).FindControl("QuantityExpression")RequiredQuantity.Validate()QuantityExpression.Validate()If RequiredQuantity.IsValidAnd QuantityExpression.IsValidThen
...

Validate one datagrid edit field off another edit field

ok I have a dropdownlist if the user selects Item 3 then I want to show a requiredfieldvalidator for the datefield.

see your previous post. I can provide you with some sample code doingnot exactly that but using one control validation based on the value ofthe other one. Give me a shout if you are interested
Cheers

i did not think the first one went through, thanks I will look

validate textbox in gridview?

In gridview i am using checkbox and textbox in itemtemplate . Now i want

to validate the textbox (Required field validator)when the checkbox is checked .

give some sample codes in asp.net not in javascript...

add requierd field validator like this..

<EditItemTemplate>

<asp:TextBoxID="TextBox2"runat="server"Text='<%# Bind("sal") %>'></asp:TextBox>

<asp:RequiredFieldValidatorControlToValidate="TextBox2"ID="RequiredFieldValidator1"runat="server"ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

</EditItemTemplate>

hope this will help u..


I am using Textbox&checkbox in Itemtemplate and i have try the above code in itemtemplate also

but its not working please check and send the code.............


see this code now

<ItemTemplate>

<asp:PlaceHolderID="placeholder1"runat="server">

</asp:PlaceHolder>

<asp:CheckBoxID="CheckBox1"Text='<%# Bind("id") %>'runat="server"AutoPostBack="true"OnCheckedChanged="CheckBox2_CheckedChanged"/>

<asp:TextBoxID="TextBox3"runat="server"Text='<%# Bind("sal") %>'></asp:TextBox>

</ItemTemplate>

and i added the requierd filed validator on the chk box chk event as

protectedvoid CheckBox2_CheckedChanged(object sender,EventArgs e)

{

CheckBox chk = (CheckBox)sender;if (chk.Checked)

{

int i=Convert.ToInt32(chk.Text);

TextBox tt = (TextBox)GridView1.Rows[i].FindControl("TextBox3");

PlaceHolder pp = (PlaceHolder)GridView1.Rows[i].FindControl("placeholder1");RequiredFieldValidator re =newRequiredFieldValidator();

re.ControlToValidate = tt.ID.ToString();

re.Text ="*";

pp.Controls.Add(re);

}

}

'>'>

'>'>try this and let me know if any problem..


I am using checkbox and textbox in seperate itemtemplates.

The above code is not working..................


<asp:CheckBox ID="CHK_T_SET_CONTROL_PERMISSION" runat="server" AutoPostBack="True"
OnCheckedChanged="CHK_T_SET_CONTROL_PERMISSION_CheckedChanged" />
</ItemTemplate>
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="Select"></asp:Label>
</HeaderTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ControlName" HeaderText="Control Name" SortExpression="ControlName">
<ItemStyle Font-Size="Small" />
</asp:BoundField>
<asp:TemplateField HeaderText="Display Control Name">
<ItemTemplate>
<asp:TextBox ID="TXT_T_SET_CTRL_SCR_DISPLAY_SCREEN_NAME" runat="server" Enabled="False"></asp:TextBox>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Control Description">
<ItemTemplate>
<asp:TextBox ID="TXT_T_SET_CTRL_SCR_SCREEN_DESCRIPTION" runat="server" Enabled="False"></asp:TextBox>

</ItemTemplate>

this is my aspx code.........


This is my code..

HTML

<asp:GridViewID="GridView1"runat="server"AutoGenerateColumns="False">

<Columns>

<asp:TemplateFieldHeaderText="Isvalidate">

<ItemTemplate>

<asp:CheckBoxID="CheckBox1"Text='<%# Bind("id") %>'runat="server"AutoPostBack="true"OnCheckedChanged="CheckBox2_CheckedChanged"/>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateFieldHeaderText="sal">

<EditItemTemplate>

<asp:TextBoxID="TextBox2"runat="server"Text='<%# Bind("sal") %>'></asp:TextBox>

<asp:RequiredFieldValidatorControlToValidate="TextBox2"ID="RequiredFieldValidator1"runat="server"ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

</EditItemTemplate>

<ItemTemplate>

<asp:PlaceHolderID="placeholder1"runat="server">

</asp:PlaceHolder>

<asp:TextBoxID="TextBox3"runat="server"Text='<%# Bind("sal") %>'></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

and code behind page is

protectedvoid Page_Load(object sender,EventArgs e)

{

if (!IsPostBack)

{

GridView1.DataSource = binddate();

GridView1.DataBind();

}

}

privateDataTable binddate()

{

DataTable dt =newDataTable();

DataColumn dc =newDataColumn("id");

DataColumn dc1 =newDataColumn("sal");

dt.Columns.Add(dc);

dt.Columns.Add(dc1);

for (int i = 0; i < 5; i++)

{

DataRow dr = dt.NewRow();

dr["id"] = i;

dr["sal"] = i * 100;

dt.Rows.Add(dr);

}

return dt;

}

protectedvoid CheckBox2_CheckedChanged(object sender,EventArgs e)

{

CheckBox chk = (CheckBox)sender;if (chk.Checked)

{

int i =Convert.ToInt32(chk.Text);

TextBox tt = (TextBox)GridView1.Rows[i].FindControl("TextBox3");

PlaceHolder pp = (PlaceHolder)GridView1.Rows[i].FindControl("placeholder1");

RequiredFieldValidator re =newRequiredFieldValidator();

re.ControlToValidate = tt.ID.ToString();

re.Text ="*";

pp.Controls.Add(re);

}

}

This code will work, but not that sufficent

when you will select the chk box and clear the textbox then it will shows error,

but this is working for only one row at a time, if you are selected two chkboxes, then it is not validating both the textboxes.

but i think this will give u an idea, to validate the textbox..


<asp:CheckBoxID="CheckBox1"Text='<%# Bind("id") %>'runat="server"AutoPostBack="true"OnCheckedChanged="CheckBox2_CheckedChanged"/>

<asp:TextBoxID="TextBox2"runat="server"Text='<%# Bind("sal") %>'></asp:TextBox>

I am not binding text value to checkbox and textbox ..

I try the above code but its not working...............

Validate the dataitem in repeater,datalist control

Hi Everybody

Question is, how to validate the item that are binded in the repeater,datalist control.

For Example,
Binded five items in the repeater control,among the five item one is containing NULL value.So in that place validate the <container.dataitem("fieldname")> .

if it is NULL jump to process1 else jump to process2.

If anyone knows or across this problem just send the solution.

Any help regd in this issue is highly grateful.

Cheers
GSKInstead of directly binding to container.dataitem("fieldname") bind to a function and pass the container.dataitem("fieldname") as a parameter to it. Within the function check for null and act appropriately

validate the date type input

is there a easy way to validate a date that the user inputs ..

I mean i have a text box where the user enter a date and i am suppose to validate it..
say mm/dd/yy is the format i need to validate that date..

is there a easy way..can someone share the codeUse a compare validator


<asp:comparevalidator id="cv1" runat="server" controltovalidate="mydate" Operator="DataTypeCheck" Type = Date />

Validate user selection

I would like to display a list of items and cost from an XML data source and allow the user to select items. When the user selects items I want to calculate if the user selected item total cost(s) exceeds their allowable credit limit. Then save the selection and costs. I'm a first timer and don't know what controls to use or if they have a validation and save functions. I am currently displaying the list in a GridView control fed by and XML data file.


Dave

Hi,

Well what you can do is when the user comes on the page where he can select items to buy you get the Allowed Credit Limit from the source where you have saved it for the user and keep it with you. Now when the user adds item you calculate the total cost of the items added in the list and compare it with the Allowed Credit Limit which you have already retrieved. If the user exceeds it then prompt the user that you don't have enough credit limit or what ever message you want to display. If the item's total cost selected by the user is within the Allowed Credit Limit then call your method to save the records.

Hope it will help you out.

Thanks and best regards,

validate userid duplicate

hi, i am doing a page which requires user input an user id. on given this id, i would like the
page to query the database to see if this id is already taken. My logic is that perform an sql select query, then if the result set is empty (null value), then the id is valid (as nobody is using it yet); if not, the id is already taken by someone.

Any idea how can i evaluate the result set? I have tried:

++++++++++++

string sqlSelect = "SELECT * FROM member WHERE usrid= '"+ IDValue + "'";

SqlDataAdapter adp=new SqlDataAdapter(sqlSelect,"server=aaaa;database=db;User ID=id123;pwd=123123");

DataSet ds=new DataSet();
adp.Fill(ds,"member");
if (ds==null)
{
value.IsValid = true;
}
else
{
value.IsValid = false;
}

+++++++++++++

which does not work and tells "the id is taken" always. Obviously the dataset is never empty even though it has no records at all...

any help please? if i have done sth obviously wrong please point out and any other methods please?

Thanks very muchI don't think you should use the DataSet if you only will query the datasource to let you know if the Id is taken or not. Use the ExecuteScalar method of the SqlCommand class and also use parameters to avoid Sql-injection.
cheers for that! solved now

Validate:

I have a MS SQL database running with information about users. Password, usernames user levels etc. I have the login information working fine, UserName / UserPassword pulling the data from the database to authenticate. But I'm not sure how to incorporate the UserLevel part. Each person has a different level 0-9, and depending on their level it gives them access to a specific area. Here is the code I have thus far.

Any help would be greatly appreciated, new to the whole asp.net thing.

Windows XP Pro
Web Matrix
MS SQL Server

<--login.aspx--> (Not part of the code)

Sub LoginBtn_Click(Sender As Object, E As EventArgs)
If Page.IsValid Then
Dim userDS As New System.Data.DataSet
userDS = GetUser(UserName.Text, UserPass.Text)
If userDS.Tables(0).Rows.Count = 1 Then
FormsAuthentication.RedirectFromLoginPage(UserName.Text, false)
Else
Msg.Text = "Invalid Username or Password: Please try again"
End If
End If
End Sub

Function GetUser(ByVal userName As String, ByVal userPassword As String) As System.Data.DataSet
Dim connectionString As String = "server='RSA1'; trusted_connection=true; database='users'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "SELECT [user_table].[UserName], [user_table].[UserPassword] FROM [user_table] WHE"& _
"RE (([user_table].[UserName] = @dotnet.itags.org.UserName) AND ([user_table].[UserPassword] = @dotnet.itags.org.Us"& _
"erPassword))"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_userName As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userName.ParameterName = "@dotnet.itags.org.UserName"
dbParam_userName.Value = userName
dbParam_userName.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userName)
Dim dbParam_userPassword As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userPassword.ParameterName = "@dotnet.itags.org.UserPassword"
dbParam_userPassword.Value = userPassword
dbParam_userPassword.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userPassword)

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

Return dataSet
End Function

Function GetLevel() As System.Data.DataSet
Dim connectionString As String = "server='RSA1'; trusted_connection=true; database='users'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

Dim queryString As String = "SELECT [user_table].[UserLevel] FROM [user_table] WHERE ([user_table].[UserLevel]"& _
" = 0)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

Return dataSet
End FunctionLooks like you're on the right track...

To answer your question on how to implement the access levels, I would suggest setting a session variable to store the users level. i.e. Session("Level") = "9"

Then on subsequent pages you can use a select case statement to perform some other action based on the level. i.e.

Select Case Session("Level")
Case "0"
' Show level 0 options
Case "1"
' Show level 1 options
Case "2"
' Show level 2 options
End Select

Also, just wanted to offer another pointer about some of the code...

When declaring object where you are instancing a new object of that type you can use the New Keyword before the object type so your code would look like this:

Instead of this:
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)

It could look like this:
Dim dbConnection As New System.Data.IDbConnection(connectionString)

Same with these:
Dim dbCommand As New System.Data.IDbCommand
Dim dataSet As New System.Data.DataSet

And lastly, here's a bit more on how we can succinctly add parameters:

Here's what you have:
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_userName As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userName.ParameterName = "@.UserName"
dbParam_userName.Value = userName
dbParam_userName.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userName)
Dim dbParam_userPassword As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userPassword.ParameterName = "@.UserPassword"
dbParam_userPassword.Value = userPassword
dbParam_userPassword.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userPassword)

Here's another way to write it:
Dim dbCommand As New System.Data.IDbCommand
With dbCommand
.CommandText = queryString
.Connection = dbConnection
.Parameters.Add("@.UserName", userName)
.Parameters.Add("@.UserPassword", userPassword)
End With

I know that less lines of code doesn't mean better code... just wanted to give you another way to look at it.

HTH, intellec

Validating a field in datagrid...

i have this datagrid:
<Columns>
<asp:ButtonColumn Text=">" ButtonType="PushButton" CommandName="Select"></asp:ButtonColumn>
<asp:BoundColumn Visible="False" DataField="AddressTypeId" SortExpression="AddressTypeId" ReadOnly="True" HeaderText="AddressTypeId"></asp:BoundColumn>
<asp:BoundColumn DataField="AddressTypeDesc" SortExpression="AddressTypeDesc" HeaderText="Description"></asp:BoundColumn>
</Columns
And i need to validate the AddressTypeDesc (for not inserting two times the same description) but with the validators i can't do that (i am getting an error).

Does anybody knows how-to?

Thanks inadvance,
Mike.

(Sorry for my bad english)Please if somebody knows!!!

Thanks!
in the update datagrid function you can capture the fields' values and then do reguler if then expressions like so:


<asp:datagrid id="dg"....
<columns>
<ASP:BoundColumn
DataField="RecID"
ReadOnly=True
Visible="False" />
...
</columns>
</asp:datagrid>

in the script...

protected void Update_dg(Object sender, DataGridCommandEventArgs e) {
String RecID = e.Item.Cells[0].Text;
...

if ( RecID == '123' ) {
// do some stuff...
}


Hope this helps.
Thank you, i will try this :)

Validating a DTO (Data Transfer Object)

I am building a home groan DAL (yes I meant to write groan instead of grown). I know there are many tools out there that do the same thing. I am doing this purely for educational purposes (I am curious about how to implement a DAL). I have decided that I will transfer data between layers via a DTO. For each database table in my application I am going to create a DTO that has public properties that map directly to a database table.

For the purposes of this question I have the following:

Database Tables DTO's

Employee EmployeeDTO

Department DepartmentDTO

I also have a EmployeeCRUD class and a DepartmentCRUD class that handle all of the CRUD operations for these tables/DTO's. These CRUD classes will take a DTO object as a parameter (ie. EmployeeCRUD.Insert(employeeDTO)

Before I perform an insert or update I would like to validate the fields within the DTO.

Here are my questions:

1. Would I be better off putting the validation method in the DTO class or the CRUD class (the call to the validation method will be done in the CRUD class before the insert and update methods)?

2. One of the fields in my Employee table and my EmployeeDTO is departmentCode. I am not sure of the best method to validate the department code (which is a foreign key in the department table).

Should I validate the departmentCode like I would any field in my DTO ( i.e. if (departmentCode.IsNullOrEmpty)...) or should I create a DepartmentDTO object within my EmployeeDTO object and then call the Validate Method on the DeparmentDTO object?

Thanks.

I would definitely valid my business logic as close to my business objects as possible. I believe that the latest version of the Enterprise Library includes a Validation Block, that uses reflection and attributes on your properties to do some simple validation (Someone correct me if this is wrong, but I believe that this is what I saw in it)


validating a gridview boundfield

i've been trying to follow along with a tutorial on how to create a custom BoundField that has built-in validation functionality. (tutorial is athttp://dotnet.sys-con.com/read/217541.htm.) being more than a little unfamiliar with how classes and assemblies work, i don't think i'm following him correctly, because i've been getting a couple errors that i haven't found how to solve.

in his example code page (athttp://res.sys-con.com/story/may06/217541/source.html) he has the full aspx page code at the bottom, but i'm not quite sure what to do with the c# code. would anyone be able to tell me where to put these code pieces? i've tried putting them in the code-behind page as well as a new file under app_code, but i get the build error "unknown server tag 'Powered01Cs:PoweredBoundField'." i also have no idea what "InitializeCell" is supposed to be overriding.

the author says the full demo is available for download, but i can'tfind the download link. if anyone sees where it is, i would dearlylove to know.

thanks so much for any pointers.would anyone know of any other tutorials perhaps?

bttrflii:


..as well as a new file under app_code, but i get the build error "unknown server tag 'Powered01Cs:PoweredBoundField'."

You need to make the application aware of the namespace. In web.config:
<system.web>
...
<pages>
<controls>
<addtagPrefix="Powered01Cs"namespace="Powered01Cs" />
</controls>
</pages>
</system.web>

bttrflii:


i also have no idea what "InitializeCell" is supposed to be overriding.

From the help:

TheInitializeCell method is implemented byBoundField-derived types to add text and controls to aTableCell object of a data control that uses tables to display a user interface (UI). These data controls create the complete table structure row-by-row when the control'sCreateChildControls method is called. TheInitializeCell method is called by theInitializeRow method of data controls such asDetailsView andGridView.

Call this method when you are writing a custom data-bound control that usesTableCell objects to initialize the cells of the table structure with data or controls. Implement this method when you are writing aBoundField-derived class.

Hope this gets you a bit further.


thanks a bunch sjonnie! it seems that every time i think i'm taking a step forward, i take a dozen leaps back. now that i'm past *that* error, it appears that the code given in his "listings" isn't even all the code needed to get his example to work. being the complete dunce i am, i might have to just find that magazine's contact info and ask for the complete and working example after all. i feel like i'm trying to complete a complex puzzle armed with the knowledge that half the pieces are missing...

i sincerely appreciate the pointers. :) thank you!

Validating a XML string against a XML Schema (typed dataset)

Please
i have an webservice that receives a XML string that i convert it to a
dataset.
How can i validate this XML, against a typed dataset schema?
Tks in adv.
FabianoHello Fabiano,
Use a StringReader to contstruct an XmlValidatingReader...
--
Matt Berther
http://www.mattberther.com
> Please
> i have an webservice that receives a XML string that i convert it to a
> dataset.
> How can i validate this XML, against a typed dataset schema?
> Tks in adv.
> Fabiano
>

Validating an XML file

Hi there,
I've created a strongly-typed "DataSet" using VS. If I save the data via
"DataSet.WriteXml()" and later prompt my users for the name of the file in
order to read it back in again (using "DataSet.ReadXml()"), how do I
validate that the file they enter is valid. That is, while
"DataSet.ReadXml()" throws a "System.Xml.XmlException" if they enter a
non-XML file, a valid XML file results in no exception even though the
schema may be completely incorrect (if they enter some random XML file on
the system that is). Is there a clean way of detecting this situatiion.
Thank you.Hi
Check out the WriteXmlSchema, ReadXmlSchema and WriteXml and ReadXml
overloads of the DataSet type. I haven't actually used these before, and I
can't check that it will do exactly what you want it do (at a PC with no
.Net), but it's worth a look.
Glenn
"Jack White" <no_spam@._nospam.com> wrote in message
news:eBUJz4qNHHA.4060@.TK2MSFTNGP03.phx.gbl...
> Hi there,
> I've created a strongly-typed "DataSet" using VS. If I save the data via
> "DataSet.WriteXml()" and later prompt my users for the name of the file in
> order to read it back in again (using "DataSet.ReadXml()"), how do I
> validate that the file they enter is valid. That is, while
> "DataSet.ReadXml()" throws a "System.Xml.XmlException" if they enter a
> non-XML file, a valid XML file results in no exception even though the
> schema may be completely incorrect (if they enter some random XML file on
> the system that is). Is there a clean way of detecting this situatiion.
> Thank you.
>
Jack White wrote:
> I've created a strongly-typed "DataSet" using VS. If I save the data via
> "DataSet.WriteXml()" and later prompt my users for the name of the file in
> order to read it back in again (using "DataSet.ReadXml()"), how do I
> validate that the file they enter is valid. That is, while
> "DataSet.ReadXml()" throws a "System.Xml.XmlException" if they enter a
> non-XML file, a valid XML file results in no exception even though the
> schema may be completely incorrect (if they enter some random XML file on
> the system that is). Is there a clean way of detecting this situatiion.
Try something like:
DataSet ds = new DataSet("TestDS");
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.ValidationType = ValidationType.Schema;
xrs.Schemas.Add(XmlSchema.Read(new
StreamReader(@."C:\ds.xsd"), ValidationEventHandler));
XmlReader xr = XmlTextReader.Create(@."C:\ds.xml", xrs);
ds.ReadXml(xr);
Arne
>> I've created a strongly-typed "DataSet" using VS. If I save the data via
>> "DataSet.WriteXml()" and later prompt my users for the name of the file
>> in order to read it back in again (using "DataSet.ReadXml()"), how do I
>> validate that the file they enter is valid. That is, while
>> "DataSet.ReadXml()" throws a "System.Xml.XmlException" if they enter a
>> non-XML file, a valid XML file results in no exception even though the
>> schema may be completely incorrect (if they enter some random XML file on
>> the system that is). Is there a clean way of detecting this situatiion.
> Try something like:
> DataSet ds = new DataSet("TestDS");
> XmlReaderSettings xrs = new XmlReaderSettings();
> xrs.ValidationType = ValidationType.Schema;
> xrs.Schemas.Add(XmlSchema.Read(new StreamReader(@."C:\ds.xsd"),
> ValidationEventHandler));
> XmlReader xr = XmlTextReader.Create(@."C:\ds.xml", xrs);
> ds.ReadXml(xr);
Thanks very much. That does appear to be the correct solution but it still
doesn't trap an invalid ".xml" file for some reason. I've tried different
variations including similar solutions on the web (which all basically boil
down to your own) but it never invokes the handler. Note that my experience
with XML is very limited so I'm not sure what's wrong (I'm a very
experienced developer however). I'll have to research it further but I'm
basically doing this:
1) Create a strongly-typed (wizard-generated) dataset using VS
(wizard-generated constructor creates all tables, constraints, etc.)
2) Populate it with data and write to file using "DataSet.WriteXml("ds.xml",
XmlWriteMode.IgnoreSchema)". Note that my ".xml" file actually uses another
extension but I assume that's not an issue.
3) Read it back in using your code above, passing the wizard-generated
".xsd" file from step 1. Note however that "ds" from your example will
actually be the wizard-generated "DataSet" derivative whose constructor
creates all tables, etc. I'm assuimg this makes no difference (?).
If I now pass in an arbitrary (invalid) ".xml" file in step 3, the handler
is never called. Any idea what's wrong? Thanks again.
Jack White wrote:
>> I've created a strongly-typed "DataSet" using VS. If I save the data via
>> "DataSet.WriteXml()" and later prompt my users for the name of the file
>> in order to read it back in again (using "DataSet.ReadXml()"), how do I
>> validate that the file they enter is valid. That is, while
>> "DataSet.ReadXml()" throws a "System.Xml.XmlException" if they enter a
>> non-XML file, a valid XML file results in no exception even though the
>> schema may be completely incorrect (if they enter some random XML file on
>> the system that is). Is there a clean way of detecting this situatiion.
>> Try something like:
>> DataSet ds = new DataSet("TestDS");
>> XmlReaderSettings xrs = new XmlReaderSettings();
>> xrs.ValidationType = ValidationType.Schema;
>> xrs.Schemas.Add(XmlSchema.Read(new StreamReader(@."C:\ds.xsd"),
>> ValidationEventHandler));
>> XmlReader xr = XmlTextReader.Create(@."C:\ds.xml", xrs);
>> ds.ReadXml(xr);
> Thanks very much. That does appear to be the correct solution but it still
> doesn't trap an invalid ".xml" file for some reason.
If I add something either non well formed XML to the file or
add well formed XML that does not comply with the schema then
I get an exception.
Arne
> If I add something either non well formed XML to the file or
> add well formed XML that does not comply with the schema then
> I get an exception.
Strange. The ".xml" file I'm passing doesn't conform with the ".xsd" file.
The handler isn't called however nor is any exception thrown. After the call
to "ReadXml()", everything created in the constructor remains intact as if
nothing happened. After several hours mucking with this I'm at a loss to
explain it. Anyway, I'll just have to keep probing. Thanks again though
(appreciated).
Using ReadXmlSchema and ReadXml should throw an exception if the XML doesn't
match the schema, although it'll probably being something vague like a
constraint failure.
"Jack White" <no_spam@._nospam.com> wrote in message
news:uMHwMwBOHHA.4644@.TK2MSFTNGP03.phx.gbl...
>> If I add something either non well formed XML to the file or
>> add well formed XML that does not comply with the schema then
>> I get an exception.
> Strange. The ".xml" file I'm passing doesn't conform with the ".xsd" file.
> The handler isn't called however nor is any exception thrown. After the
> call to "ReadXml()", everything created in the constructor remains intact
> as if nothing happened. After several hours mucking with this I'm at a
> loss to explain it. Anyway, I'll just have to keep probing. Thanks again
> though (appreciated).
>
> Using ReadXmlSchema and ReadXml should throw an exception if the XML
> doesn't match the schema, although it'll probably being something vague
> like a constraint failure.
Thanks for your feedback. I was going to respond to your first post in fact
but was working on resolving the issue which I just did moments ago (with
the help of an XML MVP elsewhere though I'm still testing things). I had to
turn on the "XmlSchemaValidationFlags.ReportValidationWarnings" in
"XmlReaderSettings" and then Arne's example works (well, I changed it
slightly). Note that not even MSFT's examples touch this flag however so I
don't understand this (it makes me a little nervous in fact). Problems are
also reported as warnings and not errors which I find counter-intuitive. In
any case, perhaps one of the "ReadXml()" overloads you suggested does throw
an exception but not the version I've been using all along (it doesn't). If
one of them does however then it's not documented and therefore unreliable.
I think Arne's way is really the "official" way in 2.0 anyway (there was
another technique in 1.X that's now obsolete) so I'm probably safer relying
on it. I don't like having to send my ".xsd" file out just for validation
however (it's an internal detail) but I'm hoping it can be avoided somehow.
I'm still looking into it but I'm fairly new to XML and so it's a learning
process. Any advice you can offer (on having to ship my ".xsd" file) would
be welcome however. Thanks again.
Responses inline...
"Jack White" <no_spam@._nospam.com> wrote in message
news:ONPrJzMOHHA.2236@.TK2MSFTNGP02.phx.gbl...
>> Using ReadXmlSchema and ReadXml should throw an exception if the XML
>> doesn't match the schema, although it'll probably being something vague
>> like a constraint failure.
> Thanks for your feedback. I was going to respond to your first post in
> fact but was working on resolving the issue which I just did moments ago
> (with the help of an XML MVP elsewhere though I'm still testing things). I
> had to turn on the "XmlSchemaValidationFlags.ReportValidationWarnings" in
> "XmlReaderSettings" and then Arne's example works (well, I changed it
> slightly). Note that not even MSFT's examples touch this flag however so I
> don't understand this (it makes me a little nervous in fact).
Interesting, I can't remember ever having to do the
"XmlSchemaValidationFlags.ReportValidationWarnings" thing. The method I
use, which is almost definately slower given it doesn't use a reader, or if
it does it's internal, is XmlDocument.Validate().
>Problems are also reported as warnings and not errors which I find
>counter-intuitive.
Whenever a problem gets reported you can check ValidationEventArgs.Severity
property to determine what action to take, if any.
>In any case, perhaps one of the "ReadXml()" overloads you suggested does
throw
> an exception but not the version I've been using all along (it doesn't).
> If one of them does however then it's not documented and therefore
> unreliable.
Was the schema inlined with the XML? If not, it'll infer the schema from
the XML and won't throw an exception.
http://msdn2.microsoft.com/en-us/library/360dye2a.aspx
> I think Arne's way is really the "official" way in 2.0 anyway (there was
> another technique in 1.X that's now obsolete) so I'm probably safer
> relying on it.
That involved using XmlValidatingReader, which is indeed obselete.
>I don't like having to send my ".xsd" file out just for validation however
>(it's an internal detail) but I'm hoping it can be avoided somehow. I'm
>still looking into it but I'm fairly new to XML and so it's a learning
>process. Any advice you can offer (on having to ship my ".xsd" file) would
>be welcome however. Thanks again.
I've distributed schemas with application code before now as a plain .xsd
file, although this was to a well constrained user population. If your
worried about people tampering with it, you could store it in a .resx file
in your application.
Glenn
> Interesting, I can't remember ever having to do the
> "XmlSchemaValidationFlags.ReportValidationWarnings" thing. The method I
> use, which is almost definately slower given it doesn't use a reader, or
> if it does it's internal, is XmlDocument.Validate().
Since none of the examples I've seen turn this flag on it leads me to
believe I have a problem somewhere. I shouldn't have to turn it on IOW if
nobody else has to.
> Whenever a problem gets reported you can check
> ValidationEventArgs.Severity property to determine what action to take, if
> any.
It always reports it as a warning. I originally thought it would be reported
as an error but apparently not. The problem is that you can't distinguish
between "acceptable" warnings generated while reading a conforming ".xml"
file (warnings I can safely ignore), and those that really need to be
treated as errors (normally because you're dealing with a non-conforming
".xml" file). My testing shows that a conforming ".xml" file generates no
warnings however so I'll have to assume that any warning is really an error
and treat it that way. That may not be true however so I may actually reject
a conforming ".xml" file which will be a problem. I can't seem to resolve
the issue any other way however.
> Was the schema inlined with the XML? If not, it'll infer the schema from
> the XML and won't throw an exception.
> http://msdn2.microsoft.com/en-us/library/360dye2a.aspx
Even when I pass "XmlWriteMode.WriteSchema" to "WriteXml()" and later read
it back in, no errrors are generated.
> I've distributed schemas with application code before now as a plain .xsd
> file, although this was to a well constrained user population. If your
> worried about people tampering with it, you could store it in a .resx file
> in your application.
Tampering isn't an issue in my case but it's really an implemenation detail
so I wanted to avoid having to install it merely for this purpose. I'm not
sure what the accepted protocol is however . To validate an ".xml" file, do
you normally install its ".xsd" file for this purpose, assuming you don't
need it for anything else. In any case, my overall experience with this
situation has been very frustrating. I just want to validate an ".xml" file
but apparently I have to become an XML expert to do it. Thanks again for
your help though.
"Jack White" <no_spam@._nospam.com> wrote in message
news:OZ5FkHXOHHA.1252@.TK2MSFTNGP02.phx.gbl...
> > Interesting, I can't remember ever having to do the
> > "XmlSchemaValidationFlags.ReportValidationWarnings" thing. The method I
> > use, which is almost definately slower given it doesn't use a reader, or
> > if it does it's internal, is XmlDocument.Validate().
> Since none of the examples I've seen turn this flag on it leads me to
> believe I have a problem somewhere. I shouldn't have to turn it on IOW if
> nobody else has to.
> > Whenever a problem gets reported you can check
> > ValidationEventArgs.Severity property to determine what action to take,
if
> > any.
> It always reports it as a warning. I originally thought it would be
reported
> as an error but apparently not. The problem is that you can't distinguish
> between "acceptable" warnings generated while reading a conforming ".xml"
> file (warnings I can safely ignore), and those that really need to be
> treated as errors (normally because you're dealing with a non-conforming
> ".xml" file). My testing shows that a conforming ".xml" file generates no
> warnings however so I'll have to assume that any warning is really an
error
> and treat it that way. That may not be true however so I may actually
reject
> a conforming ".xml" file which will be a problem. I can't seem to resolve
> the issue any other way however.
> > Was the schema inlined with the XML? If not, it'll infer the schema
from
> > the XML and won't throw an exception.
> >
> > http://msdn2.microsoft.com/en-us/library/360dye2a.aspx
> Even when I pass "XmlWriteMode.WriteSchema" to "WriteXml()" and later read
> it back in, no errrors are generated.
> > I've distributed schemas with application code before now as a plain
.xsd
> > file, although this was to a well constrained user population. If your
> > worried about people tampering with it, you could store it in a .resx
file
> > in your application.
> Tampering isn't an issue in my case but it's really an implemenation
detail
> so I wanted to avoid having to install it merely for this purpose. I'm not
> sure what the accepted protocol is however . To validate an ".xml" file,
do
> you normally install its ".xsd" file for this purpose, assuming you don't
> need it for anything else. In any case, my overall experience with this
> situation has been very frustrating. I just want to validate an ".xml"
file
> but apparently I have to become an XML expert to do it. Thanks again for
> your help though.
>
Firstly, add a while (reader.Read() ); after you create the XmlReader. That
will cause the reader to walk over the document.
And, if you haven't already done so, add someway of capturing and displaying
the results of the validation from the ValidationEventArgs of the
ValidationEventHandler.
I did a test, for instance changing the data type of the Key element
InnerText which resulted in and XmlSeverity.Error and produced a message
indicating the exact problem.
HTH
Glenn
"Jack White" <no_spam@._nospam.com> wrote in message
news:OZ5FkHXOHHA.1252@.TK2MSFTNGP02.phx.gbl...
>> Interesting, I can't remember ever having to do the
>> "XmlSchemaValidationFlags.ReportValidationWarnings" thing. The method I
>> use, which is almost definately slower given it doesn't use a reader, or
>> if it does it's internal, is XmlDocument.Validate().
> Since none of the examples I've seen turn this flag on it leads me to
> believe I have a problem somewhere. I shouldn't have to turn it on IOW if
> nobody else has to.
>> Whenever a problem gets reported you can check
>> ValidationEventArgs.Severity property to determine what action to take,
>> if any.
> It always reports it as a warning. I originally thought it would be
> reported as an error but apparently not. The problem is that you can't
> distinguish between "acceptable" warnings generated while reading a
> conforming ".xml" file (warnings I can safely ignore), and those that
> really need to be treated as errors (normally because you're dealing with
> a non-conforming ".xml" file). My testing shows that a conforming ".xml"
> file generates no warnings however so I'll have to assume that any warning
> is really an error and treat it that way. That may not be true however so
> I may actually reject a conforming ".xml" file which will be a problem. I
> can't seem to resolve the issue any other way however.
>> Was the schema inlined with the XML? If not, it'll infer the schema from
>> the XML and won't throw an exception.
>> http://msdn2.microsoft.com/en-us/library/360dye2a.aspx
> Even when I pass "XmlWriteMode.WriteSchema" to "WriteXml()" and later read
> it back in, no errrors are generated.
>> I've distributed schemas with application code before now as a plain .xsd
>> file, although this was to a well constrained user population. If your
>> worried about people tampering with it, you could store it in a .resx
>> file in your application.
> Tampering isn't an issue in my case but it's really an implemenation
> detail so I wanted to avoid having to install it merely for this purpose.
> I'm not sure what the accepted protocol is however . To validate an ".xml"
> file, do you normally install its ".xsd" file for this purpose, assuming
> you don't need it for anything else. In any case, my overall experience
> with this situation has been very frustrating. I just want to validate an
> ".xml" file but apparently I have to become an XML expert to do it. Thanks
> again for your help though.
>
Don't worry about distributing an XSD with your application, it's just
another file. And it's there for the purpose of making your application
inputs more robust.
Anyway, back your the validation problem...
Before calling the myDataSet.ReadXml( reader ), you need to call while (
reader.Read() ); Doing so will cause the reader to walk over the document
and pick up any problems.
I promise you, this version works, honest ;-)
class Program
{
static void Main()
{
try
{
//WriteData();
//Mangle the data by hand...
ReadData();
}
catch ( Exception exception )
{
Console.WriteLine( exception.Message );
}
finally
{
Console.WriteLine( "\r\nFinished" );
Console.ReadLine();
}
}
static void WriteData()
{
MyDataSet testDataSet = new MyDataSet();
testDataSet.MyTable.AddMyTableRow( "Abraham Lincoln" );
testDataSet.WriteXml( "MyFile.xml", XmlWriteMode.IgnoreSchema );
}
/// <summary>
///
/// </summary>
static void ReadData()
{
MyDataSet myDataSet = new MyDataSet();
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add( null, "..\\..\\MyDataSet.xsd" );
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |=XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(
delegate( object sender, ValidationEventArgs args )
{
Console.WriteLine( "Severity : {0}\r\nMessage :{1}",
args.Severity.ToString(), args.Message );
} );
XmlReader reader = XmlReader.Create( "MyFile.xml", settings );
//this line is important!!!!
while ( reader.Read() ) ;
myDataSet.ReadXml( reader );
}
}
I appreciate your on-going assistance ...
> Don't worry about distributing an XSD with your application, it's just
> another file. And it's there for the purpose of making your application
> inputs more robust.
Ok (thanks)
> Anyway, back your the validation problem...
> Before calling the myDataSet.ReadXml( reader ), you need to call while (
> reader.Read() ); Doing so will cause the reader to walk over the document
> and pick up any problems.
Ok, I'll look into it but why is "reader.Read()" required? I assume (maybe
naively) that any action on the reader will be validated. And in fact, I've
conducted a number of tests now (not exhaustive but so far so good) and the
handler seems to be trapping everything. That is, the call to
"myDataSet.ReadXml(reader)" attempts to read the entire ".xml" file into
"myDataSet" and so validation occurs no differently than if you read it one
node at a time by calling "reader.Read()" first. Doing that would double the
processing time in fact so it doesn't seem to make any sense (on the surface
anyway). Are you sure it's really required? In any case, I do have two
related questions that maybe you know something about:
1) I noticed that if I add a new field, column, etc. to my "DataSet", VS
updates the ".xsd" file of course but I can still read previous ".xml" files
error/warning-free (i.e., older ".xml" files that don't have these new
elements). I'll experiment with your "reader.Read()" scenario to see what it
does (I'm guessing there won't be any difference) but since the schema of
the older ".xml" file isn't an exact match for the updated ".xsd" file, I'm
not sure why it passess validation (probaly because it's still a valid
subset I'm guessing).
2) The first arg to "settings.Schemas.Add" (i.e., the targetNameSpace) is
null. I'm not too familiar with this argument yet (working on it) but is
this safe. Passing null therefore causes the function to pull
"targetNamespace" from the ".xsd" file itself which I assume is typically
the correct path to go (since I'd presumably pass the same value anyway if I
were to explicitly pass the first arg).
Thanks again.
"Jack White" <no_spam@._nospam.com> wrote in message
news:e7eLLnkOHHA.324@.TK2MSFTNGP06.phx.gbl...
> I appreciate your on-going assistance ...
> > Don't worry about distributing an XSD with your application, it's just
> > another file. And it's there for the purpose of making your application
> > inputs more robust.
> Ok (thanks)
> > Anyway, back your the validation problem...
> >
> > Before calling the myDataSet.ReadXml( reader ), you need to call while (
> > reader.Read() ); Doing so will cause the reader to walk over the
document
> > and pick up any problems.
> Ok, I'll look into it but why is "reader.Read()" required? I assume (maybe
> naively) that any action on the reader will be validated. And in fact,
I've
> conducted a number of tests now (not exhaustive but so far so good) and
the
> handler seems to be trapping everything. That is, the call to
> "myDataSet.ReadXml(reader)" attempts to read the entire ".xml" file into
> "myDataSet" and so validation occurs no differently than if you read it
one
> node at a time by calling "reader.Read()" first. Doing that would double
the
> processing time in fact so it doesn't seem to make any sense (on the
surface
> anyway). Are you sure it's really required? In any case, I do have two
> related questions that maybe you know something about:
Thinking about it, you're right, why call it twice? The reader.Read()
should get called by the ReadXml(). The strange thing is, when I didn't
call reader.Read() explicitly I didn't get the validation messages. Could
ReadXml() suppress validation warnings? Could it only care that the XML can
create a "valid" DataSet and to hell with everything else?
Sorry, don't know the answer to this one. Where's an MVP when you need one?
> 1) I noticed that if I add a new field, column, etc. to my "DataSet", VS
> updates the ".xsd" file of course but I can still read previous ".xml"
files
> error/warning-free (i.e., older ".xml" files that don't have these new
> elements). I'll experiment with your "reader.Read()" scenario to see what
it
> does (I'm guessing there won't be any difference) but since the schema of
> the older ".xml" file isn't an exact match for the updated ".xsd" file,
I'm
> not sure why it passess validation (probaly because it's still a valid
> subset I'm guessing).
If your adding columns, the behaviour is absolutely correct, it's forward
compatibility, or maybe backward compatibility. One of the two.
> 2) The first arg to "settings.Schemas.Add" (i.e., the targetNameSpace) is
> null. I'm not too familiar with this argument yet (working on it) but is
> this safe. Passing null therefore causes the function to pull
> "targetNamespace" from the ".xsd" file itself which I assume is typically
> the correct path to go (since I'd presumably pass the same value anyway if
I
> were to explicitly pass the first arg).
> Thanks again.
>
In this instance it's quite safe.
Glenn
Ok, thanks for all your help (appreciated). Everything seems to working now
but I'm sure I'll be revisting it once I gain more experience.
In microsoft.public.dotnet.languages.csharp Arne Vajh?j <arne@.vajhoej.dk> wrote:
> Jack White wrote:
>> I've created a strongly-typed "DataSet" using VS. If I save the data via
>> "DataSet.WriteXml()" and later prompt my users for the name of the file in
>> order to read it back in again (using "DataSet.ReadXml()"), how do I
>> validate that the file they enter is valid. That is, while
>> "DataSet.ReadXml()" throws a "System.Xml.XmlException" if they enter a
>> non-XML file, a valid XML file results in no exception even though the
>> schema may be completely incorrect (if they enter some random XML file on
>> the system that is). Is there a clean way of detecting this situatiion.
> Try something like:
> DataSet ds = new DataSet("TestDS");
> XmlReaderSettings xrs = new XmlReaderSettings();
> xrs.ValidationType = ValidationType.Schema;
> xrs.Schemas.Add(XmlSchema.Read(new
> StreamReader(@."C:\ds.xsd"), ValidationEventHandler));
> XmlReader xr = XmlTextReader.Create(@."C:\ds.xml", xrs);
> ds.ReadXml(xr);
Also, I find that it is worth while to embedd the XSD as a resource in the
assembly. It can then be retreived and used without worry about filesystem
access or other issues [like an assembly being GAC'd or building a custom
directory structure].
--
Thomas T. Veldhouse
Key Fingerprint: D281 77A5 63EE 82C5 5E68 00E4 7868 0ADC 4EFB 39F0
I wish I could say it worked for me.
This still isn't working for me.
Here's my XML file ("details.xml"):
<?xml version="1.0" encoding="UTF-8" ?>
<details/>
Here's my XSD file ("Test.xsd")
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Test" targetNamespace="http://tempuri.org/Test.xsd"
elementFormDefault="qualified" xmlns="http://tempuri.org/Test.xsd"
xmlns:mstns="http://tempuri.org/Test.xsd"
xmlns:xs="">http://www.w3.org/2001/XMLSchema">
<xs:element name="details" type="xs:string" />
</xs:schema>
Here's my code:
System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
settings.Schemas.Add(null, "Test.xsd");
settings.Schemas.Compile();
settings.ValidationType = System.Xml.ValidationType.Schema;
settings.ValidationFlags |=System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new
System.Xml.Schema.ValidationEventHandler(delegate(object s,
System.Xml.Schema.ValidationEventArgs args)
{
Console.WriteLine("Severity : {0}\r\nMessage :{1}",
args.Severity.ToString(), args.Message);
});
System.Xml.XmlReader reader = System.Xml.XmlReader.Create("details.xml",
settings);
while (reader.Read()) ;
The XML is compliant, but it's still reporting an error:
Could not find schema information for the element 'details'. I've been
fighing with this for hours. This is ridiculous. Any ideas?
"Glenn" wrote:
> "Jack White" <no_spam@._nospam.com> wrote in message
> news:OZ5FkHXOHHA.1252@.TK2MSFTNGP02.phx.gbl...
> >> Interesting, I can't remember ever having to do the
> >> "XmlSchemaValidationFlags.ReportValidationWarnings" thing. The method I
> >> use, which is almost definately slower given it doesn't use a reader, or
> >> if it does it's internal, is XmlDocument.Validate().
> >
> > Since none of the examples I've seen turn this flag on it leads me to
> > believe I have a problem somewhere. I shouldn't have to turn it on IOW if
> > nobody else has to.
> >
> >> Whenever a problem gets reported you can check
> >> ValidationEventArgs.Severity property to determine what action to take,
> >> if any.
> >
> > It always reports it as a warning. I originally thought it would be
> > reported as an error but apparently not. The problem is that you can't
> > distinguish between "acceptable" warnings generated while reading a
> > conforming ".xml" file (warnings I can safely ignore), and those that
> > really need to be treated as errors (normally because you're dealing with
> > a non-conforming ".xml" file). My testing shows that a conforming ".xml"
> > file generates no warnings however so I'll have to assume that any warning
> > is really an error and treat it that way. That may not be true however so
> > I may actually reject a conforming ".xml" file which will be a problem. I
> > can't seem to resolve the issue any other way however.
> >
> >> Was the schema inlined with the XML? If not, it'll infer the schema from
> >> the XML and won't throw an exception.
> >>
> >> http://msdn2.microsoft.com/en-us/library/360dye2a.aspx
> >
> > Even when I pass "XmlWriteMode.WriteSchema" to "WriteXml()" and later read
> > it back in, no errrors are generated.
> >
> >> I've distributed schemas with application code before now as a plain .xsd
> >> file, although this was to a well constrained user population. If your
> >> worried about people tampering with it, you could store it in a .resx
> >> file in your application.
> >
> > Tampering isn't an issue in my case but it's really an implemenation
> > detail so I wanted to avoid having to install it merely for this purpose.
> > I'm not sure what the accepted protocol is however . To validate an ".xml"
> > file, do you normally install its ".xsd" file for this purpose, assuming
> > you don't need it for anything else. In any case, my overall experience
> > with this situation has been very frustrating. I just want to validate an
> > ".xml" file but apparently I have to become an XML expert to do it. Thanks
> > again for your help though.
> >
> Don't worry about distributing an XSD with your application, it's just
> another file. And it's there for the purpose of making your application
> inputs more robust.
> Anyway, back your the validation problem...
> Before calling the myDataSet.ReadXml( reader ), you need to call while (
> reader.Read() ); Doing so will cause the reader to walk over the document
> and pick up any problems.
> I promise you, this version works, honest ;-)
> class Program
> {
> static void Main()
> {
> try
> {
> //WriteData();
> //Mangle the data by hand...
> ReadData();
> }
> catch ( Exception exception )
> {
> Console.WriteLine( exception.Message );
> }
> finally
> {
> Console.WriteLine( "\r\nFinished" );
> Console.ReadLine();
> }
> }
> static void WriteData()
> {
> MyDataSet testDataSet = new MyDataSet();
> testDataSet.MyTable.AddMyTableRow( "Abraham Lincoln" );
> testDataSet.WriteXml( "MyFile.xml", XmlWriteMode.IgnoreSchema );
> }
> /// <summary>
> ///
> /// </summary>
> static void ReadData()
> {
> MyDataSet myDataSet = new MyDataSet();
> XmlReaderSettings settings = new XmlReaderSettings();
> settings.Schemas.Add( null, "..\\..\\MyDataSet.xsd" );
> settings.ValidationType = ValidationType.Schema;
> settings.ValidationFlags |=> XmlSchemaValidationFlags.ReportValidationWarnings;
> settings.ValidationEventHandler += new ValidationEventHandler(
> delegate( object sender, ValidationEventArgs args )
> {
> Console.WriteLine( "Severity : {0}\r\nMessage :{1}",
> args.Severity.ToString(), args.Message );
> } );
> XmlReader reader = XmlReader.Create( "MyFile.xml", settings );
> //this line is important!!!!
> while ( reader.Read() ) ;
> myDataSet.ReadXml( reader );
> }
> }
>
>
>
On 12 Feb, 21:21, Joe Monnin <JoeMon...@.discussions.microsoft.com>
wrote:
> I wish I could say it worked for me.
> This still isn't working for me.
> Here's my XML file ("details.xml"):
> <?xml version="1.0" encoding="UTF-8" ?>
> <details/>
> Here's my XSD file ("Test.xsd")
> <?xml version="1.0" encoding="utf-8"?>
> <xs:schema id="Test" targetNamespace="http://tempuri.org/Test.xsd"
> elementFormDefault="qualified" xmlns="http://tempuri.org/Test.xsd"
> xmlns:mstns="http://tempuri.org/Test.xsd"
> xmlns:xs="">http://www.w3.org/2001/XMLSchema">
> <xs:element name="details" type="xs:string" />
> </xs:schema>
I haven't checked all of this thread, so apologies if I've missed the
intended point. But your XML instance isn't valid against your
schema. Either the XML instance needs to be (i.e. add in namespace
declaration):
<?xml version="1.0" encoding="UTF-8" ?>
<details xmlns="http://tempuri.org/Test.xsd"/>
Or your schema needs to be (i.e. remove targetNamespace etc.):
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Test"
xmlns:xs="">http://www.w3.org/2001/XMLSchema">
<xs:element name="details" type="xs:string" />
</xs:schema>
HTH,
Pete.
--
=============================================Pete Cordell
Tech-Know-Ware Ltd
for XML to C++ data binding visit
http://www.tech-know-ware.com/lmx
(or http://www.xml2cpp.com)
=============================================
I was so focused on finding out what was wrong with the code that I neglected
to consider something was wrong with the schema. That, plus I'm not really a
schema guy. I used Visual Studio to visually create the schema, so I just
assumed it was right. Thanks for setting me straight. :)
"usenet@.tech-know-ware.com" wrote:
> On 12 Feb, 21:21, Joe Monnin <JoeMon...@.discussions.microsoft.com>
> wrote:
> > I wish I could say it worked for me.
> >
> > This still isn't working for me.
> >
> > Here's my XML file ("details.xml"):
> > <?xml version="1.0" encoding="UTF-8" ?>
> > <details/>
> >
> > Here's my XSD file ("Test.xsd")
> > <?xml version="1.0" encoding="utf-8"?>
> > <xs:schema id="Test" targetNamespace="http://tempuri.org/Test.xsd"
> > elementFormDefault="qualified" xmlns="http://tempuri.org/Test.xsd"
> > xmlns:mstns="http://tempuri.org/Test.xsd"
> > xmlns:xs="">http://www.w3.org/2001/XMLSchema">
> > <xs:element name="details" type="xs:string" />
> > </xs:schema>
> I haven't checked all of this thread, so apologies if I've missed the
> intended point. But your XML instance isn't valid against your
> schema. Either the XML instance needs to be (i.e. add in namespace
> declaration):
> <?xml version="1.0" encoding="UTF-8" ?>
> <details xmlns="http://tempuri.org/Test.xsd"/>
> Or your schema needs to be (i.e. remove targetNamespace etc.):
> <?xml version="1.0" encoding="utf-8"?>
> <xs:schema id="Test"
> xmlns:xs="">http://www.w3.org/2001/XMLSchema">
> <xs:element name="details" type="xs:string" />
> </xs:schema>
> HTH,
> Pete.
> --
> =============================================> Pete Cordell
> Tech-Know-Ware Ltd
> for XML to C++ data binding visit
> http://www.tech-know-ware.com/lmx
> (or http://www.xml2cpp.com)
> =============================================>