Showing posts with label time. Show all posts
Showing posts with label time. Show all posts

Saturday, March 31, 2012

String to DateTime?

If i have this in my Database in a column of VARCHAR

2006/12/28 18:35:10

can i convert it to date time in C# ? I attempted this?

int

result =DateTime.Compare((DateTime)ds2.Tables[0].Rows[0].ItemArray[1], (DateTime)ds2.Tables[0].Rows[1].ItemArray[1]);

which basically is taking two values in that format and comparing them but i get a invalid cast exception. And importing them into SQL As datetime is not possible.

do i have to convert it to an int first? or strip out the "/" and the ":" ? is it even possible?

thanks in advance,

mcm

UseDateTime.TryParse.

Yeah Man,

worked like a charm.

mcm


you can use

Convert.ToDateTime(string)


Convert.ToDateTime produced the same cast error as my other attempt. by TryParse worked.

yay

String validation in C#?

I'm a 30 year codingveteran using mostly S370 Assembler and Pascal on the PC's. I'm gettingmy feet wet in C#, and having a dickens of a time figuring out trivialthings. The crisis de jour is determining if a string is "valid" beforeletting XML barf all over it for containing a Hex 06 or some such.
In Pascal, I'd define a constant, ValidChars:
ValidChars = ['0'..'9', 'A'..'Z', 'a'..'z', #5, #10, #13];

andsimply iterate over the string (The lightbulb is [ i ] - How do you escape emoticon stringsin this editor?):
for i := 1 to length(arg) do
if argIdea [I] not in ValidChars
then begin
<bad string stuff>
break;
end;

I can't find anything about sets in the C# doc, so maybe theINpredicate isn't going to fly. So, maybe a CASE statement on theordinals of the various characters. Nope, no case statement. There's aswitch, but it appears not to like case definitions of> " ". Maybe it's there but I can't figure out (other than 255 cases!) how to use it.
Note, I'm looking for "the C# way", for anelegantsolution. I went to find the ord (ordinal) function, and see I didn'teven have a list of string functions, char functions, or functions ingeneral (that I could find). It must be in there somewhere.Obviously, the "language" is just the bnf of the symbols and justa few rules about operators, etc.. But the "reality" is that functions,methods, properties, etc. are built into what MS distributes, and theremust be doc on these things somewhere. I can WRITE an ordfunction, but I'm certain I'd be duplicating some efforts built intothe distribution.
TheInElegant solution I have running is pretty ugly.

private string CheckData(string arg, bool debug)
{ int loop1;
bool valid = true;
for (loop1=0; loop1 < arg.Length; loop1++)
if ((arg[loop1] != "\t"[0])
&(arg[loop1] != "\r"[0])
&(arg[loop1] != "\n"[0])
&(arg[loop1] < " "[0]))
{ valid = false;
break;
}
if (valid)
return arg;
else if (debug)
return "|Invalid String|";
else
return "";
}

Maybethis is the best C# can do, but I sincerely doubt it. It's 35 yearsPascal's junior, it should have some elegance built-in!
Possiblythere is a web reference or even a book someone might suggest to getover the odd organization of the language doc in .Net.
tiaUse regular expressions...

EDIT
You use Regular Expression to do validations. To your other questions Predicates are in standard Arrays and all the Math functions are under System.Math but I think the class is Sealed. Try the links below for the FCL(framework class library) 2.0 and a free book that covered all the math functions in C#. A good book try Programming .NET by Jeff Prosise. I did not cover the string functions, they are under strings and formatting, run a search on MSDN because it takes a book chapter to cover. Hope this helps.
http://beta.asp.net/QuickStartv20/util/classbrowser.aspx

http://www.brpreiss.com/books/opus6/html/page10.html

Wednesday, March 28, 2012

String was not recognized as a valid DateTime in another server

Hi guys,

I am currently facing this problem for quite some time now.

This is my codes below :

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

Dim dateBetweenAsString = txtDateBetween.Text.ToString.Trim

Dim dateToAsString = txtDateTo.Text.ToString.Trim

'stored procedure is done here<blah><blah>

.Parameters.AddWithValue("@dotnet.itags.org.DateBetween", DateTime.Parse(dateBetween))

.Parameters.AddWithValue("@dotnet.itags.org.DateTo", DateTime.Parse(dateTo))

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

Everything was working perfectly on my comptuer but when I tried on another server, it prompts me "String was not recognized as a valid DateTime"

I've tried conversion on both sql and asp.net but to no avail. Can someone please help?

Ryan.

Hi Ryan,

Based on my understanding, your asp.net application works fine on your local. But you get the error message above on another server when the application tries to convert the string to DateTime. If I have misunderstood you, please feel free to let me know.

Firstly, please make sure that the DateTime format matchs the DateTime format on the server.

If the formats are different, please try to use CurrentCulture's DateTimeFormat property. For example:
DateTime dt = DateTime.Parse(dateBetween, System.Threading.Tread.CurrentThread.CurrentCulture.DateTimeFormat);

Besides, you can get more information from theStandard DateTime Format Strings.

I hope this helps.


hi Hyde,
why are u usingDim dateBetweenAsString = txtDateBetween.Text.ToString.Trim

Dim dateToAsString = txtDateTo.Text.ToString.Trim, string to declare and pass as datatime,

I think you should declare both variables as datatime, and use datatimefunction to add, subtract, format or less than or greater than function provided by Thomas.

Cheers>
Dinesh.

Saturday, March 24, 2012

Stripping the time portion from date field

Hi all
I've got a textbox on the web page that captures a date.
When an insert is done, the information captured into the database is of the format dd/mm/yyyy hh:mm:ss.
How do I strip the time portion and save only the date part into the database ?
I'm using a formview, sqldatasource controls for this web page.
I tried the following in formview iteminserting event:
Dim culture_2 As System.Globalization.CultureInfo = New CultureInfo("en-GB", True)
Dim wAcceptanceD As TextBox = CType(FormView1.Row.FindControl("dtAcceptDTextBox"), TextBox)
e.Values.Add("dtAcceptD", DateTime.Parse(wAcceptanceD.Text, culture_2, DateTimeStyles.NoCurrentDateDefault))

When I run the web page, I get the following error:

System.ArgumentException was unhandled by user code
Message="Item has already been added. Key in dictionary: 'dtAcceptD' Key being added: 'dtAcceptD'"
Source="mscorlib"
StackTrace:
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)

at System.Collections.Hashtable.Add(Object key, Object value)

at System.Collections.Specialized.OrderedDictionary.Add(Object key, Object value)

at Default3.FormView1_ItemInserting(Object sender, FormViewInsertEventArgs e) in C:\SRS\Default3.aspx.vb:line 12

at System.Web.UI.WebControls.FormView.OnItemInserting(FormViewInsertEventArgs e)

at System.Web.UI.WebControls.FormView.HandleInsert(String commandArg, Boolean causesValidation)

at System.Web.UI.WebControls.FormView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)

at System.Web.UI.WebControls.FormView.OnBubbleEvent(Object source, EventArgs e)

at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)

at System.Web.UI.WebControls.FormViewRow.OnBubbleEvent(Object source, EventArgs e)

at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)

at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)

at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)

at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)

at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)

at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Can someone pleaseeeeeeeeeeeeeeeee tell me what's wrong ?
TIA.

The problem here is not the date parsing. Well, it is a problem too but not the one you're seeing.
You're using always the same key in your dictionary: "dtAcceptD". The first time it's ok, the second time, it crashes with the error you're seeing. A dictionary can have only one entry with a given key.
As for date parsing, you should specify the date format you're expecting explicitly. There is an overload of ParseExact that takes a format string.
Once you've gotten a DateTime object, it's easy to strip the time part (but why are you asking for it if you're going to throw it away? ) by constructing a new date object from the parts of the old one, something like:
new DateTime(myDate.Year, myDate.Month, myDate.Day)

Hi
Thanks for your reply.
Realised the following:
1) SQL saves the information for a datetime field with date and time information.
2) Viewing the information from the following sources have different results:
From SQL Enterprise Manager, information displayed as dd/mm/yyy.
From SQL Query Analyzer, information displayed as yyyy-mm-dd 00:00:00.
From VS (via the Database Explorer), its displayed as dd/mm/yyyy 12:00:00.
I probably dont need to do any conversion in the ItemInserting event of the formview.
Thanks for the tip on stripping the time portion of a datetime object. I'm sure it will come in handy.

Thursday, March 22, 2012

Strongly-typed Datasets in ASP.NET 2.0

Hello,

In ASP.NET 1.1, I followed this data access methodology:

At design time
- Create a strongly typed dataset
- Add this dataset to a form and bind controls to the dataset using
the designer

At run time
- Fill dataset with data on the first load of the page
- Handle all Add/Edit/Delete operations against the in-memory copy
of my dataset
- Persist the dataset between postbacks in session
- Give users the ability to Save or Cancel changes, which either
persists the changes to the database or discards them.

It worked like a charm -- there were only two trips to the database --
in the very beginning and at the very end. In memory manipulations were
very fast. And, more importantly, my productivity was high because I
was able to use design features of the Visual Studio.

It seems that in 2005, if I were to pursue the same methodology, things
would be harder, not easier.

- It appears that the only way to bind a dataset to a gridview is
through the ObjectDataSource. This binds to table adapters, not the
actual dataset, so, the database gets hit on each update.

- DataSource property is gone from the design view, so I no longer can
use the design features of Visual Studio, if I were to directly bind to
a dataset.

- There is no out of the box feature to persist a dataset between
postbacks. So, like in 1.1, if I were to go this route, I would have to
persist it in session.

I was wondering if there is anybody out there who used the 1.1 data
access in a similar fashion, and how you adapted to 2.0.

Thank you for your comments.

Evgueni

Hi Evgueni,

You can create a strongly typed DS without table adapters also. Simplest way is to just open the DS in the designer and delete the adapter part. You can then use this DS to bind to a gridView (like in 1.1) but you need to manually write code to add rows to it. Alternatively, you can use an ObjectDatasource and let it handle the DB code itself.

HTH,

Vivek


Wouldn't that be great, if there was a data source object that would out of the box:

- bind directly to a dataset, not table adapters
- know how to persist the dataset between postbacks (maybe different persistence models such as session or cache)
- have the load and update methods to interact with the database

Basically, Windows Forms pattern -- but in a stateless environment. This would greatly assist us with creating cancellable forms such as wizard and complex master/child forms.

Am I talking non-sense, or is it something that people could use in ASP.NET?


Data source controls controls can either directly connect to a data store such as a DB or XML files, or to a business object (such as a strongly typed dataset). They act like a "broker" dealing with the manipulation of data so that the developer is spared of writing too much standard data access code. So an object data source can bind directly to a dataset (and you need to create a strongly typed dataset for it, or a custom business object) and also support caching. When using typed datasets, the VS 2005 designer creates TableAdapters for the Datasets, which is an advanced and quite useful feature considering the fact that TableAdapters extend DataAdpaters.

Now when we talk about binding directly to a dataset, this we can easily do, but tableAdapeters help us to avoid writing CRUD code (with the help of VS designer) and save time. You can very easily attach Load and Update methods using TableAdapter to bind to a particular table in the DB. So my point is that TableAdapters are just some "nitro boosted" form of DataAdapters, and while using them you are infact binding with the typed Datasets only.

Summarising, all your requirements can be easily met with the new ADO.NET and VS 2005 designer features in .NET 2.0.

Let me know if you need more details.

Vivek


Vivek, thank you for your response.

I understand that what I am asking for can be done in .NET 2.0. My point is that you actually have to write code if you want to bind directly to a dataset, and I don't want to do thatSmile. For example, I want to bind directly to the dataset, and maintain a full design-time experience like I had in 2003. I can't do that now because the Data Source property is not available in the designer. Am I missing something here?

Evgueni


Evgueni,

You can use the DataSource property for the GridView in the code behind, but the reason it is not there in the Properties window is due to the fact that if we bind a gridview to a non-datasourcecontrol object, we need to provide custom paging. So it is advisable to use an ObjectDataSource which is connected to a strongly typed dataset with a gridview. All relevant designer properties would be supported.

Let me know if you still face issues with this approach.

Vivek