Showing posts with label following. Show all posts
Showing posts with label following. Show all posts

Saturday, March 31, 2012

String to Enumeration

Hello,

How do I convert a string an enumeration value?

I have the following Enum:

Public Enum MyEnum
Book = 1
Movie
End Enum

Basically, I have a variable of type MyEnum and I want to define a
value to it:

Dim MyString As String = "Book"
Dim MyVar As MyEnum = MyString

I am getting an error.
I then tried:
Dim MyVar As MyEnum = CType(MyString, MyEnum)

This is still not working.
Any idea of how to solve this?

Thanks,
MiguelFor outputing the string, just use MyEnum.ToString(). And to reverse the
operation, use Enum.Parse.

String to Enum

Hello,

How do I convert a string an enumeration value?

I have the following Enum:

Public Enum MyEnum
Book = 1
Movie
End Enum

Basically, I have a variable of type MyEnum and I want to define a value to it:

Dim MyString As String = "Book"
Dim MyVar As MyEnum = MyString

I am getting an error.
I then tried:
Dim MyVar As MyEnum = CType(MyString, MyEnum)

This is still not working.
Any idea of how to solve this?

Thanks,
Miguel

Here's how it's done in C# (should be similar for VB)

enum EType {AAA, BBB, CCC};protected void Button1_Click(object sender, EventArgs e) { EType Test; Test = (EType)Enum.Parse(typeof(EType),"AAA"); }

Hello,

Here is a sample for you:

Imports SystemPublicClass ParseTest <FlagsAttribute()> _Enum Colors Red = 1 Green = 2 Blue = 4 Yellow = 8EndEnumPublicSharedSub Main() Console.WriteLine("The entries of the Colors Enum are:")Dim colorNameAsStringForEach colorNameIn [Enum].GetNames(GetType(Colors)) Console.WriteLine("{0}={1}", colorName, Convert.ToInt32([Enum].Parse(GetType(Colors), colorName)))Next colorName Console.WriteLine()Dim myOrangeAs Colors = CType([Enum].Parse(GetType(Colors),"Red, Yellow"), Colors) Console.WriteLine("The myOrange value {1} has the combined entries of {0}", myOrange, Convert.ToInt64(myOrange))EndSubEndClass'This code example produces the following results:''The entries of the Colors Enum are:'Red=1'Green=2'Blue=4'Yellow=8''The myOrange value 9 has the combined entries of Red, Yellow'
More details are here:http://msdn2.microsoft.com/en-us/library/essfb559.aspx

String Trancate

Hi,

In following example I would like to Trancate first 5 digits and last 3 digits.

W04056040-PAY001

So I can get 6040-PAY

Any code behind examples?

Any help will be appriciated.

Thanks.

TekinUse the stringbuilder class (remove method):

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

Or if you want to do it old school, the intrinsic Mid function works well too.
Hi mtekin303,

There's many ways to solve this problem. Here's two ideas:


[Visual Basic]
Dim temp As String = "W04056040-PAY001"
Response.Write("Sample 1: " + temp.Substring(5,8) + "<br />")
Response.Write("Sample 2: " + temp.Remove(temp.Length-3,3).Remove(0,5))

[C#]
string temp = "W04056040-PAY001";
Response.Write("Sample 1: " + temp.Substring(5,8) + "<br />");
Response.Write("Sample 2: " + temp.Remove(temp.Length-3,3).Remove(0,5));


Hope this helps.
Thank you.

Stringbuilder resolved it.

Thanks again.
Thanks Chuck.

Stringbuilder resolved it.

String was not recognized as a valid Boolean

We're receiving the following error: "String was not recognized as a valid Boolean" whenever we click button1 then immediately click button2 before allowing the entire page to completely refresh/render. Under normal transaction (not clicking multiple buttons all at the same time), we don't encounter such error

1) Populate hidden fields with string values of "true" or "false
2) Upon post back, convert values of hidden fields into boolea

Highlevel logic of our page that triggers the error.We suspect that clicking 2 buttons almost at the same time fails to properly populate the hidden fields as described in step 1 above. Any ideas on how to gracefully handle the "clicking too fast" scenario? Would appreaciate your suggestions

Thanks
LesterOne thing that comes to mind is handling your button clicks with a client
side script. In your script, first disable the buttons which shouldn't be
pushed without a full round trip, collect and convert your data, and then
submit the form.

--
Chris Jackson
Software Engineer
Microsoft MVP - Windows Client
Windows XP Associate Expert
--
More people read the newsgroups than read my email.
Reply to the newsgroup for a faster response.
(Control-G using Outlook Express)
--

"Lester Lee" <anonymous@.discussions.microsoft.com> wrote in message
news:45A10F5F-6C2A-4C4B-810C-9F20C298B68D@.microsoft.com...
> We're receiving the following error: "String was not recognized as a valid
> Boolean" whenever we click button1 then immediately click button2 before
> allowing the entire page to completely refresh/render. Under normal
> transaction (not clicking multiple buttons all at the same time), we don't
> encounter such error.
> 1) Populate hidden fields with string values of "true" or "false"
> 2) Upon post back, convert values of hidden fields into boolean
>
> Highlevel logic of our page that triggers the error.We suspect that
> clicking 2 buttons almost at the same time fails to properly populate the
> hidden fields as described in step 1 above. Any ideas on how to gracefully
> handle the "clicking too fast" scenario? Would appreaciate your
> suggestions.
> Thanks!
> Lester
I noticed your post went unanswered. Have you resolved this issue?

--
Regards,
Alvin Bruney [ASP.NET MVP]
Got tidbits? Get it here...
http://tinyurl.com/3he3b
"Lester Lee" <anonymous@.discussions.microsoft.com> wrote in message
news:45A10F5F-6C2A-4C4B-810C-9F20C298B68D@.microsoft.com...
> We're receiving the following error: "String was not recognized as a valid
Boolean" whenever we click button1 then immediately click button2 before
allowing the entire page to completely refresh/render. Under normal
transaction (not clicking multiple buttons all at the same time), we don't
encounter such error.
> 1) Populate hidden fields with string values of "true" or "false"
> 2) Upon post back, convert values of hidden fields into boolean
>
> Highlevel logic of our page that triggers the error.We suspect that
clicking 2 buttons almost at the same time fails to properly populate the
hidden fields as described in step 1 above. Any ideas on how to gracefully
handle the "clicking too fast" scenario? Would appreaciate your suggestions.
> Thanks!
> Lester
How about a simple js on both buttons which disables the other button.

"Alvin Bruney [MVP]" <vapor at steaming post office> wrote in message
news:%23Zpqv4s6DHA.3052@.TK2MSFTNGP09.phx.gbl...
> I noticed your post went unanswered. Have you resolved this issue?
> --
> Regards,
> Alvin Bruney [ASP.NET MVP]
> Got tidbits? Get it here...
> http://tinyurl.com/3he3b
> "Lester Lee" <anonymous@.discussions.microsoft.com> wrote in message
> news:45A10F5F-6C2A-4C4B-810C-9F20C298B68D@.microsoft.com...
> > We're receiving the following error: "String was not recognized as a
valid
> Boolean" whenever we click button1 then immediately click button2 before
> allowing the entire page to completely refresh/render. Under normal
> transaction (not clicking multiple buttons all at the same time), we don't
> encounter such error.
> > 1) Populate hidden fields with string values of "true" or "false"
> > 2) Upon post back, convert values of hidden fields into boolean
> > Highlevel logic of our page that triggers the error.We suspect that
> clicking 2 buttons almost at the same time fails to properly populate the
> hidden fields as described in step 1 above. Any ideas on how to gracefully
> handle the "clicking too fast" scenario? Would appreaciate your
suggestions.
> > Thanks!
> > Lester

String was not recognized as a valid DateTime

I am getting the following error:

Server Error in '/Web' Application.

String was not recognized as a valid DateTime.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.FormatException: String was not recognized as a valid DateTime.

Source Error:

Line 103: decimal Reorderlevel = decimal.Parse(row["P_ReorderLevel"].ToString());Line 104: string Warehouseno = row["P_WareHouseNo"].ToString();Line 105: DateTime Modifieddate = DateTime.Parse(row["P_ModifiedDate"].ToString());Line 106: string Memo = row["P_Memo"].ToString();Line 107: string Desc = row["P_Desc"].ToString();


Source File:C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs Line:105

Stack Trace:

[FormatException: String was not recognized as a valid DateTime.] System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) +2271362 System.DateTime.Parse(String s) +22 WareHouse.DataLayer.DataObjects.SqlServer.SqlServerProductDao.GetProduct(Int32 ProductID) in C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs:105 WareHouse.BusinessLayer.Facade.ProductFacade.GetProduct(Int32 ProductID) in C:\IList_WareHouse_Solution\Facade\ProductFacade.cs:104[TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0 System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +72 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +358 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +17 System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +676 System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +2660 System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +84 System.Web.UI.WebControls.DataBoundControl.PerformSelect() +154 System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +99 System.Web.UI.WebControls.DetailsView.DataBind() +23 System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() +91 System.Web.UI.WebControls.DetailsView.EnsureDataBound() +196 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +101 System.Web.UI.Control.EnsureChildControls() +134 System.Web.UI.Control.PreRenderRecursiveInternal() +109 System.Web.UI.Control.PreRenderRecursiveInternal() +233 System.Web.UI.Control.PreRenderRecursiveInternal() +233 System.Web.UI.Control.PreRenderRecursiveInternal() +233 System.Web.UI.Control.PreRenderRecursiveInternal() +233 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4436

whenever I run

//get single product

publicProduct GetProduct(int ProductID)

{

StringBuilder sql =newStringBuilder();

sql.Append("usp_SelectProduct");

SqlParameter[] p =newSqlParameter[1];

p[0] =newSqlParameter("@dotnet.itags.org.P_Productid",SqlDbType.Int);

p[0].Value = ProductID;

DataRow row =Db.GetDataRow(sql.ToString(), p);

int productid =int.Parse(row["P_ProductID"].ToString());

string Productname = row["P_ProductName"].ToString();

decimal Qtyperunit =decimal.Parse(row["P_QtyPerUnit"].ToString());

decimal Unitprice =decimal.Parse(row["P_UnitPrice"].ToString());

decimal Unitsinstock =decimal.Parse(row["P_UnitsInStock"].ToString());

decimal Unitsonorder =decimal.Parse(row["P_UnitsOnOrder"].ToString());

decimal Reorderlevel =decimal.Parse(row["P_ReorderLevel"].ToString());

string Warehouseno = row["P_WareHouseNo"].ToString();

DateTime Modifieddate =DateTime.Parse(row["P_ModifiedDate"].ToString());

string Memo = row["P_Memo"].ToString();

string Desc = row["P_Desc"].ToString();

Product product;

return product =newProduct(productid, Productname, Qtyperunit, Unitprice, Unitsinstock, Unitsonorder, Reorderlevel, Warehouseno, Modifieddate, Memo, Desc);

}

Is there a problem in the way that I am converting my DateTime to string?

thanks

Nick

what is the data type of this:P_ModifiedDate
if it is a datetime, then you dont need to convert it to a string at all

try:

DateTime Modifieddate =Convert.ToDateTime(row["P_ModifiedDate"])


As the other poster said, if p_ModifiedDate is of type DateTime you don't need to user DateTime.Parse, neither convert it to string.

If it's in a string, then you don't need the .ToString method, however, the date has to be in the format appropriate to your thread's culture.

eg, if it's en-US it should be mm/dd/yyyy.


Ok, so DateTime is I guess a string type? I tried the

DateTime Modifieddate =Convert.ToDateTime(row["P_ModifiedDate"]);

and it generated another error saying:

Server Error in '/Web' Application.

Object cannot be cast from DBNull to other types.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.InvalidCastException: Object cannot be cast from DBNull to other types.

Source Error:

Line 103: decimal Reorderlevel = decimal.Parse(row["P_ReorderLevel"].ToString());Line 104: string Warehouseno = row["P_WareHouseNo"].ToString();Line 105: DateTime Modifieddate = Convert.ToDateTime(row["P_ModifiedDate"]);Line 106: string Memo = row["P_Memo"].ToString();Line 107: string Desc = row["P_Desc"].ToString();


Source File:C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs Line:105

this is what my product.cs class looks like:

namespace WareHouse.BusinessLayer.BusinessObjects

{

[Serializable]

publicclassProduct

{

/**** FIELD PRIVATE ****************************************/

privateint _ProductID;

privatestring _ProductName;

privatedecimal _QtyPerUnit;

privatedecimal _UnitPrice;

privatedecimal _UnitsInStock;

privatedecimal _UnitsOnOrder;

privatedecimal _ReOrderLevel;

privatestring _WareHouseNo;

privateDateTime _ModifiedDate;

privatestring _Memo;

privatestring _Desc;

// overload with 10 arguemtns for SqlServerProductDao

public Product(int P_ProductID,string P_ProductName,decimal P_QtyPerUnit,decimal P_UnitPrice,decimal P_UnitsInStock,decimal P_UnitsOnOrder,decimal P_ReorderLevel,string P_WareHouseNo,DateTime P_ModifiedDate,string P_Memo,string P_Desc)

{

this._ProductID = P_ProductID;

this._ProductName = P_ProductName;

this._QtyPerUnit = P_QtyPerUnit;

this._UnitPrice = P_UnitPrice;

this._UnitsInStock = P_UnitsInStock;

this._UnitsOnOrder = P_UnitsOnOrder;

this._ReOrderLevel = P_ReorderLevel;

this._WareHouseNo = P_WareHouseNo;

this._ModifiedDate = P_ModifiedDate;

this._Memo = P_Memo;

this._Desc = P_Desc;

}

...

....

publicDateTime ModifiedDate

{

get

{

return _ModifiedDate;

}

set

{

_ModifiedDate =value;

}

}


Ok, so DateTime is I guess a string type? I tried the

DateTime Modifieddate =Convert.ToDateTime(row["P_ModifiedDate"]);

and it generated another error saying:

Server Error in '/Web' Application.

Object cannot be cast from DBNull to other types.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.InvalidCastException: Object cannot be cast from DBNull to other types.

Source Error:

Line 103: decimal Reorderlevel = decimal.Parse(row["P_ReorderLevel"].ToString());Line 104: string Warehouseno = row["P_WareHouseNo"].ToString();Line 105: DateTime Modifieddate = Convert.ToDateTime(row["P_ModifiedDate"]);Line 106: string Memo = row["P_Memo"].ToString();Line 107: string Desc = row["P_Desc"].ToString();


Source File:C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs Line:105

this is what my product.cs class looks like:

namespace WareHouse.BusinessLayer.BusinessObjects

{

[Serializable]

publicclassProduct

{

/**** FIELD PRIVATE ****************************************/

privateint _ProductID;

privatestring _ProductName;

privatedecimal _QtyPerUnit;

privatedecimal _UnitPrice;

privatedecimal _UnitsInStock;

privatedecimal _UnitsOnOrder;

privatedecimal _ReOrderLevel;

privatestring _WareHouseNo;

privateDateTime _ModifiedDate;

privatestring _Memo;

privatestring _Desc;

// overload with 10 arguemtns for SqlServerProductDao

public Product(int P_ProductID,string P_ProductName,decimal P_QtyPerUnit,decimal P_UnitPrice,decimal P_UnitsInStock,decimal P_UnitsOnOrder,decimal P_ReorderLevel,string P_WareHouseNo,DateTime P_ModifiedDate,string P_Memo,string P_Desc)

{

this._ProductID = P_ProductID;

this._ProductName = P_ProductName;

this._QtyPerUnit = P_QtyPerUnit;

this._UnitPrice = P_UnitPrice;

this._UnitsInStock = P_UnitsInStock;

this._UnitsOnOrder = P_UnitsOnOrder;

this._ReOrderLevel = P_ReorderLevel;

this._WareHouseNo = P_WareHouseNo;

this._ModifiedDate = P_ModifiedDate;

this._Memo = P_Memo;

this._Desc = P_Desc;

}

...

....

publicDateTime ModifiedDate

{

get

{

return _ModifiedDate;

}

set

{

_ModifiedDate =value;

}

}


The date you fetch from DB might be null, Try this:

DateTime Modifieddate;object Modifieddate_obj = row["P_ModifiedDate"];if(Modifieddate!= System.DBNull.Value){ Modifieddate = Convert.ToDateTime();}


I tried the following:

DateTime Modifieddate;object Modifieddate_obj = row["P_ModifiedDate"];if(Modifieddate!= System.DBNull.Value){ Modifieddate = Convert.ToDateTime();}

and got errors saying:

Error 11 Operator '!=' cannot be applied to operands of type 'System.DateTime' and 'System.DBNull' C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs 107 17 DataObjects
Error 12 No overload for method 'ToDateTime' takes '0' arguments C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs 109 32 DataObjects

Next I tried:

object Modifieddate_obj = row["P_ModifiedDate"];
if (Modifieddate_obj != System.DBNull.Value)
{
Modifieddate = Convert.ToDateTime();
}

and I still got errors saying:

Error 11 No overload for method 'ToDateTime' takes '0' arguments C:\IList_WareHouse_Solution\DataObjects\SqlServer\SqlServerProductDao.cs 109 32 DataObjects

thanks

nick


Make sure you are getting some value in P_ModifiedDate and it is in the correct date format. If so, then you can convert it to your needs. And also Convert.ToDateTime takes a parameter, it should be used like this : Modifieddate = Convert.ToDateTime(Modifieddate_obj);

Thanks

Wednesday, March 28, 2012

String was not recognized as a valid DateTime

I retrive data from web service. My date is in the format 20/6/2006 0:00. When I try to format date with the following code it gives me above error.

the code is

String.Format("{0:MMMM d, yyyy}",Date.Parse(_landcorReport.vrValuationDate))

please help me

please guys can any one help me?
Hi,
Make sure you are getting valid date in _landcorReport.vrValuationDate. Try using TryParse with an out variable of DateTime type, and then try to format it.

DateTime dt;
bool result = DateTime.TryParse(_landcorReport.vrValuationDate.ToString(), out dt);

Thanks,


unless you are doing Visual J#, you should be usingDateTime.Parse instead

String.Format ( "{0:MMMM d, yyyy}",DateTime.Parse ( _landcorReport.vrValuationDate ) )

that should work assuming of course that _landcorReport.vrValuationDate returns a string that is convertible to a valid date


ReyN:

unless you are doing Visual J#, you should be usingDateTime.Parse instead

String.Format ( "{0:MMMM d, yyyy}",DateTime.Parse ( _landcorReport.vrValuationDate ) )

that should work assuming of course that _landcorReport.vrValuationDate returns a string that is convertible to a valid date

If the input string cannot be converted to DateTime, an exception will be thrown. If you are not sure whether the input string can be converted to datetime, use the TryParse, as this method tries to parse only if the input string is valid and gives you the result if succeeded into the out variable. If you are not using TryParse, you need to use a try {} catch {} block to handle the exception.

Thanks

This method is available in .Net 2.0 while I'm working in .Net 1.1
Hi
Check if the value of_landcorReport.vrValuationDate is a valid date, or use your statement in try catch block

THanks

string.equals general question

hi

there's something with the following I just can't seem to understand.

Private Function stringequals() As String

Dim str1 As String = "aaa"
Dim str2 As String = "bbb"
Dim str3 As String = "ccc"
Dim str4 As String = "aaa"

str1 &= str1.Equals(str2, str3)

Return str1

End Function

This function returns the string 'aaaFalse', as I was expecting. What I dont understadn is this;

The Equals method is overloaded so that I can compare two objects, as I'm doing here with str2 and str3. I can't see why they've done this. str2 and str3 have NOTHING to do with str1.

I'd understand if the line was;

str1 &= str1.Equals(str4)

Of course, this is a valid overload method too.

I'm only really asking my question because I'm new to vb.net and OO in general. The str1.Equals method is 'part' of str1, but compares two different obects (str2 and str3). This doesnt make sense to me.

any thoughts?

thanks

mauriceI think that two things are throwing you.

First, you have used the &= operator which means, "add to" ...

str1 &= str2 means"aaa" + "bbb" and will give you"aaabbb"
str1 &= False means"aaa" + "False" and will give you"aaaFalse"

The last example is why you are getting "aaa" in your result.

The second thing I think is throwing you is what, exactly, the.Equals is doing. It compares the thing before .Equals to the thing in the brackets.

If there is only one thing in the brackets, then it works simply:
str1.Equals("aaa") asks whether"aaa" = "aaa" and the answer isTrue
str1.Equals(str2) asks whether"aaa" = "bbb" and the answer isFalse

But, if there are two things in the brackets, it compares all three things (this is notstrictly true, but it's true enough with the example you've provided):
str1.Equals("aaa", str4) asks whether"aaa" = "aaa" = "aaa" and the answer isTrue
str1.Equals(str3, str4) asks whether"aaa" = "ccc" = "aaa" and the answer isFalse

So, your expressionstr1 &= str1.Equals(str2, str3") is working like this:

str1.Equals(str2, str3") asks whether"aaa" = "bbb" = "ccc" which isFalse.

So, your expression reduces tostr1 &= False.

Remember that the &= operator means to add the second thing to the first, so:
str1 &= False means"aaa" + "False" which becomes"aaaFalse"

Has that helped explain what, exactly, is going on?
Actually, not true.

str1.Equals(str2,str3) compares ONLY str2 and str3.

While this implementation might seem a tad confusing, this is only from the perspective you are using it here.

.Equals is implemented as a shared method, so you don't need to instantiate the string object to use it. For example:

blnStringComp = String.Equals(str2,str3)

You might use it in this fashion to compare, say, the content of two textboxes, without creating an explicit instance of the string class to do so:

blnStringCompare = String.Equals(Me.txt1.Text, Me.txt2.Text)

Is it a bit superfluous? Perhaps. I think a better question is (and I ask this seriously), is String.Equals faster than just using the "=" operator.
I said that my explanation wasn't strictly true ... but, you're right, it's not even "almost true" :)

You're also right ... simply using a set of "=" operator tests would be easier. However, I think that String.Equals is probably faster over a number of boolean tests, in the same way that the StringBuilder class is faster than "&=" for more than handful of string concatenations.
thanks for your answers, i thought something 'strange' was going on...

"Equals is implemented as a shared method, so you don't need to instantiate the string object to use it. For example:

blnStringComp = String.Equals(str2,str3)"

now it all makes sense, mostly ;)
An intresting aside

In a (good?) OO language like C# the above wont compile, and thus remove the potential misunderstsanding of what is happening.

One can't call static (shared) members on an instance of a class, only on the type.

Another gotcha, the object.equals(obj1, obj2) will only do a reference equals, ie are the objects the same (ie the same address), not a value equals, do the objects have the same value. The string.equals(string1, string2) will do a value equals. I imagine this is what is called in the above instances.

M G Walmsley
Thatwas interesting.

You mentioned that .Equals tests references, not values. You then explain that the reference test asks "are the objects the same (ie the same address)". By "the same address", do you mean the "address" as used inAddHandler btnSend.Click, AddressOf btnSend_Click? If so, it means I've misunderstood the difference between ByVal and ByRef...
By address i mean the address in memory of the object. Normally this is not available or needed in code, but can be got at if needed. This is returned by AddressOf, though strictly this is a function delegate, ie the address and signature of the function.

By Ref means that the address (as above) is passed to the function. So code inside the called function will update the object in the callee.

For Reference objects, eg, classes, this is the normal way to pass them to functions.
Value types, primitives, ints etc, and structures are normally passed By Value not By Ref.

By Value means the value of the object is passed. IF an object is passed by value, it is copied to a new object. This means the object in the callee will not be updated in the called function.
Another thing to be carefull about.

All types derive from object. Object has a Equals method that works as described (a reference equals).

So all types have a Equals method. So unless they are overridden be a derived type, the base object.Equals will be called.

String does have an override of Equals which does a value equals, but only if called with two strings.

The thing to always be aware of when one writes a statement like xxx.Equals(aaa, bbb) is what will actually be called.
Thanks, mgwalm, for your explanation.

For this cowboy (self-taught) developer, it shows how much I don't know about the very fundamentals of programming :/

string.format gridview cell

I am trying to use the following code to format specific cells in my gridview and failing. I can successfully format a column by setting htmlencode off and string.format for the field, but I need to control the formatting at the cellular level :-). I can get font, color etc, but not string.format. I can add to the string i.e. in the code below everything works, except the <code> "

Case"Sales"

For i = 1To e.Row.Cells.Count - 1

IfNot RTrim(e.Row.Cells(i).Text.ToString) =""Then

e.Row.Cells(i).Text =String.Format("{0:c}", e.Row.Cells(i).Text)

EndIf

Next

"</code>

Also if not rtrim(e.row.cells(i).text.tostring = "" does not do anything for me, what is the correct syntax so that empty cells do not recieving this formatting?

<code>

Sub gridview2_rowdatabound(ByVal senderAsObject,ByVal eAs GridViewRowEventArgs)Handles GridView2.RowDataBound

Dim iAsInteger

If e.Row.RowType = DataControlRowType.DataRowThen

e.Row.Cells(4).Font.Bold =True

e.Row.Cells(8).Font.Bold =True

e.Row.Cells(12).Font.Bold =True

e.Row.Cells(16).Font.Bold =True

e.Row.Cells(17).Font.Bold =True

e.Row.Cells(4).BackColor = Drawing.Color.LightGray

e.Row.Cells(8).BackColor = Drawing.Color.LightGray

e.Row.Cells(12).BackColor = Drawing.Color.LightGray

e.Row.Cells(16).BackColor = Drawing.Color.LightGray

e.Row.Cells(17).BackColor = Drawing.Color.LightGray

SelectCase RTrim(e.Row.Cells(0).Text)

Case"Sales"

For i = 1To e.Row.Cells.Count - 1

IfNot RTrim(e.Row.Cells(i).Text.ToString) =""Then

e.Row.Cells(i).Text =String.Format("{0:c}", e.Row.Cells(i).Text)

EndIf

Next

Case"Gross Profit"

For i = 1To e.Row.Cells.Count - 1

IfNot e.Row.Cells(i).TextIsNothingThen

e.Row.Cells(i).Text ="$" & e.Row.Cells(i).Text

EndIf

Next

EndSelect

EndIf

EndSub

</code>

Thanks

if you change your trouble code to this:

String str =String.Format("{0:c}", e.Row.Cells(i).Text);
e.Row.Cells(i).Text =String.Format("{0:c}", e.Row.Cells(i).Text)

and debugg it,

what result to you get for str?
Does it format it?
Does your code even go into the if statement above the trouble line?

foregive my ignorance, is there a way to see the value of a variable in vs.net during a debugging session besides assigning it to a label in my web app?

I do know that the code does go into the if statement as changing the code to me e.row.cells(i).text = "$" & e.row.cells(i).text gives me the expected result in the gridview cell.

Also the app compiles without error.

Thanks in advance for your assistance.


Ok, I placed a break immediately after the str1 = string.format...

and in my vs.net 2005 it shows the number with no formatting.

"Good news is I now see how to trouble shoot my code without adding extra labels etc on my application to display variables just so that I know what is being assigned to the variable" Bad news, I still don't see why string.format is not working.


Oops. Disregard this post, plz.


Try this:

IfNot RTrim(e.Row.Cells(i).Text.ToString) =""Then

e.Row.Cells(i).Text =String.Format("{0:c}", Double.Parse(e.Row.Cells(i).Text))

EndIf


that works perfectly. Thank you

String.Insert() problem

dear :
i have the following problem:
string sAttachmentBody;
int nCount = 0;
int nMaxLineLength = 77;
//sAttachmentBody.Length may reaches (560960 chars)
for(int i=0 ; i < sAttachmentBody.Length ; i++)
{
if(nCount % nMaxLineLength == 0 )
{
try
{
sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
}
catch(Exception ex)
{
wr = new System.IO.StreamWriter("C:\\stringerror.txt");
wr.WriteLine("Message = " + ex.Message );
wr.WriteLine("Stack = " + ex.StackTrace );
wr.Close();
}
nCount = 0;
}
}
the exception
Stack = at System.String.Insert(Int32 startIndex, String value)
at Utility.Email.SetAttachmentBody(String sAttachmentBody)
the exception occured ONLY if the length is to big , is there a replacement
for insert function because as I wrote the length may reaches millionsStringBuilder class might be what you are looking for.
"Raed Sawalha" wrote:

> dear :
> i have the following problem:
>
> string sAttachmentBody;
> int nCount = 0;
> int nMaxLineLength = 77;
> //sAttachmentBody.Length may reaches (560960 chars)
> for(int i=0 ; i < sAttachmentBody.Length ; i++)
> {
> if(nCount % nMaxLineLength == 0 )
> {
> try
> {
> sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
> }
> catch(Exception ex)
> {
> wr = new System.IO.StreamWriter("C:\\stringerror.txt");
> wr.WriteLine("Message = " + ex.Message );
> wr.WriteLine("Stack = " + ex.StackTrace );
> wr.Close();
> }
> nCount = 0;
> }
> }
> the exception
> Stack = at System.String.Insert(Int32 startIndex, String value)
> at Utility.Email.SetAttachmentBody(String sAttachmentBody)
> the exception occured ONLY if the length is to big , is there a replacemen
t
> for insert function because as I wrote the length may reaches millions
my problem is the index where I want to place the char all the overloaded
function is int
what should I do
"Tu-Thach" wrote:
> StringBuilder class might be what you are looking for.
> "Raed Sawalha" wrote:
>
int is sufficient for for handling millions of characters. I recommend that
you use the StringBuilder class and build up your string with "\r\n" instead
of replacing the string like you are doing now.
"Raed Sawalha" wrote:
> my problem is the index where I want to place the char all the overloaded
> function is int
> what should I do
> "Tu-Thach" wrote:
>
examnotes <RaedSawalha@.discussions.microsoft.com>
confessed in news:FA6628D8-8568-4E71-A1B9-337E43A04EC0@.microsoft.com:

> dear :
> i have the following problem:
>
> string sAttachmentBody;
> int nCount = 0;
> int nMaxLineLength = 77;
> //sAttachmentBody.Length may reaches (560960 chars)
> for(int i=0 ; i < sAttachmentBody.Length ; i++)
> {
> if(nCount % nMaxLineLength == 0 )
> {
> try
> {
> sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
> }
> catch(Exception ex)
> {
> wr = new System.IO.StreamWriter("C:\\stringerror.txt");
> wr.WriteLine("Message = " + ex.Message );
> wr.WriteLine("Stack = " + ex.StackTrace );
> wr.Close();
> }
> nCount = 0;
> }
> }
> the exception
> Stack = at System.String.Insert(Int32 startIndex, String value)
> at Utility.Email.SetAttachmentBody(String sAttachmentBody)
> the exception occured ONLY if the length is to big , is there a
replacement
> for insert function because as I wrote the length may reaches millions
Oh man, that's a killer memory operation.
Use a StringBuilder, not a String!
-- ipgrunt
use something larger. Perhaps an int64?

String.Insert() problem

dear :

i have the following problem:

string sAttachmentBody;
int nCount = 0;
int nMaxLineLength = 77;

//sAttachmentBody.Length may reaches (560960 chars)

for(int i=0 ; i < sAttachmentBody.Length ; i++)
{
if(nCount % nMaxLineLength == 0 )
{
try
{
sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
}
catch(Exception ex)
{
wr = new System.IO.StreamWriter("C:\\stringerror.txt");
wr.WriteLine("Message = " + ex.Message );
wr.WriteLine("Stack = " + ex.StackTrace );
wr.Close();
}

nCount = 0;
}
}

the exception
Stack = at System.String.Insert(Int32 startIndex, String value)
at Utility.Email.SetAttachmentBody(String sAttachmentBody)

the exception occured ONLY if the length is to big , is there a replacement
for insert function because as I wrote the length may reaches millionsStringBuilder class might be what you are looking for.

"Raed Sawalha" wrote:

> dear :
> i have the following problem:
>
> string sAttachmentBody;
> int nCount = 0;
> int nMaxLineLength = 77;
> //sAttachmentBody.Length may reaches (560960 chars)
> for(int i=0 ; i < sAttachmentBody.Length ; i++)
> {
> if(nCount % nMaxLineLength == 0 )
> {
> try
> {
> sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
> }
> catch(Exception ex)
> {
> wr = new System.IO.StreamWriter("C:\\stringerror.txt");
> wr.WriteLine("Message = " + ex.Message );
> wr.WriteLine("Stack = " + ex.StackTrace );
> wr.Close();
> }
> nCount = 0;
> }
> }
> the exception
> Stack = at System.String.Insert(Int32 startIndex, String value)
> at Utility.Email.SetAttachmentBody(String sAttachmentBody)
> the exception occured ONLY if the length is to big , is there a replacement
> for insert function because as I wrote the length may reaches millions
my problem is the index where I want to place the char all the overloaded
function is int
what should I do

"Tu-Thach" wrote:

> StringBuilder class might be what you are looking for.
> "Raed Sawalha" wrote:
> > dear :
> > i have the following problem:
> > string sAttachmentBody;
> > int nCount = 0;
> > int nMaxLineLength = 77;
> > //sAttachmentBody.Length may reaches (560960 chars)
> > for(int i=0 ; i < sAttachmentBody.Length ; i++)
> > {
> > if(nCount % nMaxLineLength == 0 )
> > {
> > try
> > {
> > sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
> > }
> > catch(Exception ex)
> > {
> > wr = new System.IO.StreamWriter("C:\\stringerror.txt");
> > wr.WriteLine("Message = " + ex.Message );
> > wr.WriteLine("Stack = " + ex.StackTrace );
> > wr.Close();
> > }
> > nCount = 0;
> > }
> > }
> > the exception
> > Stack = at System.String.Insert(Int32 startIndex, String value)
> > at Utility.Email.SetAttachmentBody(String sAttachmentBody)
> > the exception occured ONLY if the length is to big , is there a replacement
> > for insert function because as I wrote the length may reaches millions
int is sufficient for for handling millions of characters. I recommend that
you use the StringBuilder class and build up your string with "\r\n" instead
of replacing the string like you are doing now.

"Raed Sawalha" wrote:

> my problem is the index where I want to place the char all the overloaded
> function is int
> what should I do
> "Tu-Thach" wrote:
> > StringBuilder class might be what you are looking for.
> > "Raed Sawalha" wrote:
> > > dear :
> > > > i have the following problem:
> > > > > string sAttachmentBody;
> > > int nCount = 0;
> > > int nMaxLineLength = 77;
> > > > //sAttachmentBody.Length may reaches (560960 chars)
> > > > for(int i=0 ; i < sAttachmentBody.Length ; i++)
> > > {
> > > if(nCount % nMaxLineLength == 0 )
> > > {
> > > try
> > > {
> > > sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
> > > }
> > > catch(Exception ex)
> > > {
> > > wr = new System.IO.StreamWriter("C:\\stringerror.txt");
> > > wr.WriteLine("Message = " + ex.Message );
> > > wr.WriteLine("Stack = " + ex.StackTrace );
> > > wr.Close();
> > > }
> > > > nCount = 0;
> > > }
> > > }
> > > > the exception
> > > Stack = at System.String.Insert(Int32 startIndex, String value)
> > > at Utility.Email.SetAttachmentBody(String sAttachmentBody)
> > > > the exception occured ONLY if the length is to big , is there a replacement
> > > for insert function because as I wrote the length may reaches millions
=?Utf-8?B?UmFlZCBTYXdhbGhh?= <RaedSawalha@.discussions.microsoft.com>
confessed in news:FA6628D8-8568-4E71-A1B9-337E43A04EC0@.microsoft.com:

> dear :
> i have the following problem:
>
> string sAttachmentBody;
> int nCount = 0;
> int nMaxLineLength = 77;
> //sAttachmentBody.Length may reaches (560960 chars)
> for(int i=0 ; i < sAttachmentBody.Length ; i++)
> {
> if(nCount % nMaxLineLength == 0 )
> {
> try
> {
> sAttachmentBody = sAttachmentBody.Insert(i,"\n\r");
> }
> catch(Exception ex)
> {
> wr = new System.IO.StreamWriter("C:\\stringerror.txt");
> wr.WriteLine("Message = " + ex.Message );
> wr.WriteLine("Stack = " + ex.StackTrace );
> wr.Close();
> }
> nCount = 0;
> }
> }
> the exception
> Stack = at System.String.Insert(Int32 startIndex, String value)
> at Utility.Email.SetAttachmentBody(String sAttachmentBody)
> the exception occured ONLY if the length is to big , is there a
replacement
> for insert function because as I wrote the length may reaches millions

Oh man, that's a killer memory operation.

Use a StringBuilder, not a String!

-- ipgrunt
use something larger. Perhaps an int64?

string.remove and while

I have the following method that should remove html comments. But it's not reacting the way I expect. When the loop breaks and I return the string, I get the correct value - all comments are removed. But the loop will not break using neither the while conditional statement or the internal IndexOf check, therefore stuck in an infinite loop (save for the counter that breaks it).

What am I missing??

public static string RemoveComments(string page) {int i = 0;while (page.IndexOf("<!--") > 0) {int _CommentStart = page.IndexOf("<!--");int _CommentEnds = page.IndexOf("-->");if (_CommentStart > 0) {if (_CommentEnds <= _CommentStart) {break; } page.Remove(_CommentStart, (_CommentEnds - _CommentStart)); }if (page.IndexOf("<!--") < 1) { i = 100; } i++;if (i > 10)break; }return page +" " + i.ToString(); }
I'm not following that logic too well - I don't use c# either - but wouldn't this be a case for regular expressions ?
I'm not a regular expressions expert, but I'm sure there is a way to look for that string and remove it.
Do a search on using regular expressions...

Thank you, very good suggestion. I used the following:

System.Text.RegularExpressions.Regex r =new System.Text.RegularExpressions.Regex(@."\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>");return r.Replace(page,string.Empty);

String.Replace() in .net 1.1 did not work!

Hi, guys,

The following source code in Page_Load() did not work:

string pathVal = "2006\";
pathVal.Replace("\\", "/");

I still had the value "2006\", not "2006/", the one I expected.

I then tried the second line as:

pathVal.Replace('\', '/');

still no luck.

Any ideas? Thanks.Replace probably returns a new string that you need to set a variable to.

"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('\', '/');
> still no luck.
> Any ideas? Thanks.
You need to get the value value returned by Replace function. It returns
stirng variable.
"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('\', '/');
> still no luck.
> Any ideas? Thanks.
String.Replace() returns a new String value. You can always set the
returned value to the original string.

String.Replace() in .net 1.1 did not work!

Hi, guys,
The following source code in Page_Load() did not work:
string pathVal = "2006\";
pathVal.Replace("\\", "/");
I still had the value "2006\", not "2006/", the one I expected.
I then tried the second line as:
pathVal.Replace('\', '/');
still no luck.
Any ideas? Thanks.Replace probably returns a new string that you need to set a variable to.
"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('', '/');
> still no luck.
> Any ideas? Thanks.
>
You need to get the value value returned by Replace function. It returns
stirng variable.
"Andrew" <Andrew@.discussions.microsoft.com> wrote in message
news:74E97D68-79AC-47AB-B2D3-802DF9579D77@.microsoft.com...
> Hi, guys,
> The following source code in Page_Load() did not work:
> string pathVal = "2006\";
> pathVal.Replace("\\", "/");
> I still had the value "2006\", not "2006/", the one I expected.
> I then tried the second line as:
> pathVal.Replace('', '/');
> still no luck.
> Any ideas? Thanks.
>
String.Replace() returns a new String value. You can always set the
returned value to the original string.

Monday, March 26, 2012

string.Split() does not work?

The following code:

string strProductIDAndProductCategory = Convert.ToString(e.CommandArgument); // productidandproductcategory sent in the command argument
string [] strArrayProductIDAndProductCategory = strProductIDAndProductCategory.Split("/");

...gives me the following compile error:
The best overloaded method match for 'string.Split(params char[])' has some invalid arguments

What are these 'invalid arguments'?

when i change it from Split("/") to Split() it works just fine... what gives?

thanks"/" is a string and not a char[]

Try this


char[]splitOn = {'/'};
string [] strArrayProductIDAndProductCategory = strProductIDAndProductCategory.Split(splitOn);

or this

string [] strArrayProductIDAndProductCategory = strProductIDAndProductCategory.Split('/');

String/Number manip.

In the following line:
txtWage.Text = "$" & Trim(dataReader.GetValue(9).ToString)

It returns $20.0000 I only want it to return back $20.00 -- every search I've done in string manip. has shown me zilch.

Any suggestions?

txtWage.Text = Format(CDbl(Trim(dataReader.GetValue(9).ToString)), "currency")
I think you can use String.Format also to do the same thing, with the format of {0:c}

StringBuilder

can anyone tell me how to declare a stringbuilder using vb in visual studio, I am trying to use a stringbuilder in the following code, but visual studio states stringbuilder is not defined.

Imports System.Data
Imports System.Data.SqlClient
Imports System.Text.StringBuilder

Public Class datagrid2
Inherits System.Web.UI.Page

Public Sub UpdateCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)

Dim sb1 As StringBuilder = New StringBuilder("")
sb1.Append("INSERT Employees (firstname, lastname, titleofcourtesy, title, country) VALUES(")
sb1.Append("@dotnet.itags.org.sFirstName, @dotnet.itags.org.sLastName, @dotnet.itags.org.sTitle, @dotnet.itags.org.sPosition, @dotnet.itags.org.sCountry)")
cmd.CommandText = sb1.ToString()Hi,

Dim sb1 As System.Text.StringBuilder = New System.Text.StringBuilder("")

HTH
Imports System.Text.StringBuilder <-- don't do this, StringBuilder is a class, not a namespace.

use:
Imports System.Text

now you can use "StringBuilder" in your code (instead of having to write the fully qualified version of it each time)
thanks guys

Saturday, March 24, 2012

Strong Assembly Name

I have following question:

Why Strong Naming?
When I need It?

RegardsStrong naming an assembly means someone can't go into your assembly and
modify it. In other words, someone can't hack it, put a trojan in it and
make it look like it's ur doing.

In my opinion you'd do it when you are shipping a product or even more so a
component/library. If you are doing internal developement (enterprise
development) or you are shipping to a single client (contract work) it
becomes less important. Of course, it barely takes any time...

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/
http://openmymind.net/redirector.aspx?documentId=51 - Learn about AJAX!

"Raed Sawalha" <RaedSawalha@.discussions.microsoft.com> wrote in message
news:C299AF7D-A09E-4514-9036-42874803C7ED@.microsoft.com...
>I have following question:
> Why Strong Naming?
> When I need It?
> Regards
> If you are doing internal developement (enterprise development) or you
> are shipping to a single client (contract work) it becomes less important.
> Of course, it barely takes any time...

In fact, it's better to NOT use the GAC for this type of thing generally, as
it makes it a pain in the butt to make changes and update them. For example,
in our system, we make changes on a weekly (usually) basis. And since our
stuff is safely behind a firewall, and other security systems, there's no
need to go to the trouble.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
I'd rather be a hammer than a nail.

"Karl Seguin" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net>
wrote in message news:uW90zLpwFHA.2792@.tk2msftngp13.phx.gbl...
> Strong naming an assembly means someone can't go into your assembly and
> modify it. In other words, someone can't hack it, put a trojan in it and
> make it look like it's ur doing.
> In my opinion you'd do it when you are shipping a product or even more so
> a component/library. If you are doing internal developement (enterprise
> development) or you are shipping to a single client (contract work) it
> becomes less important. Of course, it barely takes any time...
> Karl
> --
> MY ASP.Net tutorials
> http://www.openmymind.net/
> http://openmymind.net/redirector.aspx?documentId=51 - Learn about AJAX!
>
> "Raed Sawalha" <RaedSawalha@.discussions.microsoft.com> wrote in message
> news:C299AF7D-A09E-4514-9036-42874803C7ED@.microsoft.com...
>>I have following question:
>>
>> Why Strong Naming?
>> When I need It?
>>
>> Regards

Strong Assembly Name

I have following question:
Why Strong Naming?
When I need It?
RegardsStrong naming an assembly means someone can't go into your assembly and
modify it. In other words, someone can't hack it, put a trojan in it and
make it look like it's ur doing.
In my opinion you'd do it when you are shipping a product or even more so a
component/library. If you are doing internal developement (enterprise
development) or you are shipping to a single client (contract work) it
becomes less important. Of course, it barely takes any time...
Karl
MY ASP.Net tutorials
http://www.openmymind.net/
http://openmymind.net/redirector.aspx?documentId=51 - Learn about AJAX!
"Raed Sawalha" <RaedSawalha@.discussions.microsoft.com> wrote in message
news:C299AF7D-A09E-4514-9036-42874803C7ED@.microsoft.com...
>I have following question:
> Why Strong Naming?
> When I need It?
> Regards
> If you are doing internal developement (enterprise development) or you
> are shipping to a single client (contract work) it becomes less important.
> Of course, it barely takes any time...
In fact, it's better to NOT use the GAC for this type of thing generally, as
it makes it a pain in the butt to make changes and update them. For example,
in our system, we make changes on a wly (usually) basis. And since our
stuff is safely behind a firewall, and other security systems, there's no
need to go to the trouble.
HTH,
Kevin Spencer
Microsoft MVP
.Net Developer
I'd rather be a hammer than a nail.
"Karl Seguin" <karl REMOVE @. REMOVE openmymind REMOVEMETOO . ANDME net>
wrote in message news:uW90zLpwFHA.2792@.tk2msftngp13.phx.gbl...
> Strong naming an assembly means someone can't go into your assembly and
> modify it. In other words, someone can't hack it, put a trojan in it and
> make it look like it's ur doing.
> In my opinion you'd do it when you are shipping a product or even more so
> a component/library. If you are doing internal developement (enterprise
> development) or you are shipping to a single client (contract work) it
> becomes less important. Of course, it barely takes any time...
> Karl
> --
> MY ASP.Net tutorials
> http://www.openmymind.net/
> http://openmymind.net/redirector.aspx?documentId=51 - Learn about AJAX!
>
> "Raed Sawalha" <RaedSawalha@.discussions.microsoft.com> wrote in message
> news:C299AF7D-A09E-4514-9036-42874803C7ED@.microsoft.com...
>

Thursday, March 22, 2012

Strongly typed datasets and XML

I am having trouble understanding strongly typed datasets and XML files. I
have the following schema:

<xs:schema id="Pages" targetNamespace="http://asdf.org/EOBEPages.xsd"
elementFormDefault="qualified"
xmlns="http://asdf.org" xmlns:mstns="http://asdf.org/EOBEPages.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="EOBEPages">
<xs:complexType>
<xs:sequence>
<xs:element name="Page">
<xs:complexType>
<xs:sequence>
<xs:element name="PageTitle" type="xs:string" />
<xs:element name="PageText" type="xs:string" />
<xs:element name="PageNumber" type="xs:integer" />
<xs:element name="NumImages" type="xs:integer" />
<xs:element name="ImagesDescription" type="xs:string" minOccurs="0"
maxOccurs="1" />
<xs:element name="ImageDefinitions">
<xs:complexType>
<xs:sequence>
<xs:element name="Description" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema
I load the xml data into the dataset no problem, and can access the "page"
info by:

myDataset.Page(index).pageTitle

, etc, but can NOT access the "ImageDefinitions", because I guess I don't
understand how. What I wanted to do is something like:

myVar = myDataset.Page(index).ImageDefinitions(index2).Des cription

but this is not part of the dataset... why? How can I get access to the
image definition descriptions based on the page index?

Thanks a bunch!

MC Ddatasets are tables with relationships. every xml complex type becomes a new
table. ImageDefinitions becomes a table which you can access.

myVar = myDataset.ImageDefinitions(index).Description

if you have a relionship setup you can access ImageDefinitions rows from
Page rows using GetChildRows

-- bruce (sqlwork.com)

"Big D" <a@.a.com> wrote in message
news:uam6WMY9DHA.1632@.TK2MSFTNGP12.phx.gbl...
> I am having trouble understanding strongly typed datasets and XML files.
I
> have the following schema:
> <xs:schema id="Pages" targetNamespace="http://asdf.org/EOBEPages.xsd"
> elementFormDefault="qualified"
> xmlns="http://asdf.org" xmlns:mstns="http://asdf.org/EOBEPages.xsd"
> xmlns:xs="http://www.w3.org/2001/XMLSchema">
> <xs:element name="EOBEPages">
> <xs:complexType>
> <xs:sequence
> <xs:element name="Page">
> <xs:complexType>
> <xs:sequence>
> <xs:element name="PageTitle" type="xs:string" />
> <xs:element name="PageText" type="xs:string" />
> <xs:element name="PageNumber" type="xs:integer" />
> <xs:element name="NumImages" type="xs:integer" />
> <xs:element name="ImagesDescription" type="xs:string" minOccurs="0"
> maxOccurs="1" /
> <xs:element name="ImageDefinitions">
> <xs:complexType>
> <xs:sequence>
> <xs:element name="Description" type="xs:string" />
> </xs:sequence>
> </xs:complexType>
> </xs:element>
> </xs:sequence>
> </xs:complexType>
> </xs:element>
> </xs:sequence>
> </xs:complexType>
> </xs:element>
> </xs:schema>
> I load the xml data into the dataset no problem, and can access the "page"
> info by:
> myDataset.Page(index).pageTitle
> , etc, but can NOT access the "ImageDefinitions", because I guess I don't
> understand how. What I wanted to do is something like:
> myVar = myDataset.Page(index).ImageDefinitions(index2).Des cription
> but this is not part of the dataset... why? How can I get access to the
> image definition descriptions based on the page index?
> Thanks a bunch!
> MC D

Tuesday, March 13, 2012

strugling with Atributed XML parsing.

I have XML in following format
<ORDER>
<HEADER> ... </HEADER>
<LINE> ... <LINE>
<LINE> ... <LINE>
<LINE> ... <LINE>
</ORDER
Can someone suggest how will i parseout such document using XmlSerializer
and attributes.
There can be different amount of lines in different documents.

I have

class clsOrder

{

clsHeader _header;

clsLine [] Lines;

}

How do i specify that <line> goes into Lines array?

Thanks.

George.Hi George,

Thanks for posting in the community!
From your description, you need some suggestions or information on how to
specify the proper XmlAttributes in certian classes so as to use
XmlSerializer to output them and the certain custom class you made contains
an array member of another custom class, yes?
If there is anything I misunderstood, please feel free to let me know.

As for this question, I suggest that you use the "XmlArray" and
XmlArrayItem" attribute to implement the control of the array member within
a certain class's serialization. For example, we can provide the class's
code as below:

public class clsLine
{
public clsLine()
{}

public string Name = "name";
public string Description = "description";
}

public class clsOrder
{
public clsOrder()
{}

[XmlElement("MyHeader")]
public string Header = "header";

[XmlArrayItem(typeof(clsLine),ElementName = "MyLine")]
[XmlArray(ElementName = "MyLines",Namespace = "", IsNullable = true)]
public clsLine[] Lines = null;

}

Notice the two attributes specified in the clsOrder class.
1. the "XmlArray" has specified what name to use for the array member when
the class's instance is serialized, here I specify it as "MyLines", and the
"XmlArrayItem" can be used to specify the array member's item's serialize
options, and when i serialzie a certain clsOrder instance via the following
code:
----------------
XmlSerializer serializer = new XmlSerializer(typeof(clsOrder));

clsOrder odr = new clsOrder();
odr.Header = "Test Order";
clsLine[] lines = new clsLine[5];

for(int i=0;i<lines.Length;i++)
{
clsLine line = new clsLine();
line.Name = "Name" + i.ToString();
line.Description = "Description" + i.ToString();
lines[i] = line;
}

odr.Lines = lines;

TextWriter writer = new StreamWriter("output.xml");
serializer.Serialize(writer,odr);
writer.Close();
------------
The output.xml is like:
----------output.xml--------
<?xml version="1.0" encoding="utf-8"?>
<clsOrder xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<MyHeader>Test Order</MyHeader>
<MyLines>
<MyLine>
<Name>Name0</Name>
<Description>Description0</Description>
</MyLine>
<MyLine>
<Name>Name1</Name>
<Description>Description1</Description>
</MyLine>
<MyLine>
<Name>Name2</Name>
<Description>Description2</Description>
</MyLine>
<MyLine>
<Name>Name3</Name>
<Description>Description3</Description>
</MyLine>
<MyLine>
<Name>Name4</Name>
<Description>Description4</Description>
</MyLine>
</MyLines>
</clsOrder>
----------------

In addition, here is some tech references in MSDN on the how to use and
control the XmlSerializer, I believe they'll be helpful to you:

#Introducing XML Serialization
http://msdn.microsoft.com/library/e...roducingxmlseri
alization.asp?frame=true

#Examples of XML Serialization
http://msdn.microsoft.com/library/e...xampleofxmlseri
alizationwithxmlserializer.asp?frame=true

#Controlling XML Serialization Using Attributes
http://msdn.microsoft.com/library/e...trollingseriali
zationbyxmlserializerwithattributes.asp?frame=true

#Attributes That Control XML Serialization
http://msdn.microsoft.com/library/e...ributesthatcont
rolserialization.asp?frame=true

Please check out my preceding suggestions, if you have any questions on
them, please feel free to let me know.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
That is the problem.
Your sample creates following XML
<clsOrder>
<MyHeader>Test Order</MyHeader>
<MyLines>
<MyLine> ..</MyLine>
<MyLine> ..</MyLine>
<MyLine> ..</MyLine>
</MyLines>
</clsOrder
Unfortunately i need following structure.

<clsOrder>
<MyHeader>Test Order</MyHeader>
<MyLine> ..</MyLine>
<MyLine> ..</MyLine>
<MyLine> ..</MyLine>
</clsOrder
Notice there is no <MyLines> tag

I do agree that your structure is more natural and i would not even ask my
question if that was a case. But i stuck with aftermarket standart which was
created by some guys with jumbo heads (joke) and need to be able to parse
that XML

Thanks.
George.

"Steven Cheng[MSFT]" <v-schang@.online.microsoft.com> wrote in message
news:DaO7nzf6DHA.3736@.cpmsftngxa07.phx.gbl...
> Hi George,
>
> Thanks for posting in the community!
> From your description, you need some suggestions or information on how to
> specify the proper XmlAttributes in certian classes so as to use
> XmlSerializer to output them and the certain custom class you made
contains
> an array member of another custom class, yes?
> If there is anything I misunderstood, please feel free to let me know.
> As for this question, I suggest that you use the "XmlArray" and
> XmlArrayItem" attribute to implement the control of the array member
within
> a certain class's serialization. For example, we can provide the class's
> code as below:
>
> public class clsLine
> {
> public clsLine()
> {}
> public string Name = "name";
> public string Description = "description";
> }
> public class clsOrder
> {
> public clsOrder()
> {}
> [XmlElement("MyHeader")]
> public string Header = "header";
> [XmlArrayItem(typeof(clsLine),ElementName = "MyLine")]
> [XmlArray(ElementName = "MyLines",Namespace = "", IsNullable = true)]
> public clsLine[] Lines = null;
> }
> Notice the two attributes specified in the clsOrder class.
> 1. the "XmlArray" has specified what name to use for the array member when
> the class's instance is serialized, here I specify it as "MyLines", and
the
> "XmlArrayItem" can be used to specify the array member's item's serialize
> options, and when i serialzie a certain clsOrder instance via the
following
> code:
> ----------------
> XmlSerializer serializer = new XmlSerializer(typeof(clsOrder));
> clsOrder odr = new clsOrder();
> odr.Header = "Test Order";
> clsLine[] lines = new clsLine[5];
> for(int i=0;i<lines.Length;i++)
> {
> clsLine line = new clsLine();
> line.Name = "Name" + i.ToString();
> line.Description = "Description" + i.ToString();
> lines[i] = line;
> }
> odr.Lines = lines;
> TextWriter writer = new StreamWriter("output.xml");
> serializer.Serialize(writer,odr);
> writer.Close();
> ------------
> The output.xml is like:
> ----------output.xml--------
> <?xml version="1.0" encoding="utf-8"?>
> <clsOrder xmlns:xsd="http://www.w3.org/2001/XMLSchema"
> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
> <MyHeader>Test Order</MyHeader>
> <MyLines>
> <MyLine>
> <Name>Name0</Name>
> <Description>Description0</Description>
> </MyLine>
> <MyLine>
> <Name>Name1</Name>
> <Description>Description1</Description>
> </MyLine>
> <MyLine>
> <Name>Name2</Name>
> <Description>Description2</Description>
> </MyLine>
> <MyLine>
> <Name>Name3</Name>
> <Description>Description3</Description>
> </MyLine>
> <MyLine>
> <Name>Name4</Name>
> <Description>Description4</Description>
> </MyLine>
> </MyLines>
> </clsOrder>
> ----------------
> In addition, here is some tech references in MSDN on the how to use and
> control the XmlSerializer, I believe they'll be helpful to you:
> #Introducing XML Serialization
http://msdn.microsoft.com/library/e...roducingxmlseri
> alization.asp?frame=true
> #Examples of XML Serialization
http://msdn.microsoft.com/library/e...xampleofxmlseri
> alizationwithxmlserializer.asp?frame=true
> #Controlling XML Serialization Using Attributes
http://msdn.microsoft.com/library/e...trollingseriali
> zationbyxmlserializerwithattributes.asp?frame=true
> #Attributes That Control XML Serialization
http://msdn.microsoft.com/library/e...ributesthatcont
> rolserialization.asp?frame=true
> Please check out my preceding suggestions, if you have any questions on
> them, please feel free to let me know.
>
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security
> (This posting is provided "AS IS", with no warranties, and confers no
> rights.)
Hi George,

Thank you for the response. Regarding on the issue, I am
finding proper resource to assist you and we will update as soon as posible.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security(This posting is provided "AS IS",
with no warranties, and confers no rights.)
Hi George,

We are still researching this issue. We will post more information as soon
as we can.

Thank you, Mike
Microsoft, ASP.NET Support Professional

Microsoft highly recommends to all of our customers that they visit the
http://www.microsoft.com/protect site and perform the three straightforward
steps listed to improve your computers security.

This posting is provided "AS IS", with no warranties, and confers no rights.

-------
> X-Tomcat-ID: 199496731
> References: <OxJQSeZ6DHA.2496@.TK2MSFTNGP09.phx.gbl>
<DaO7nzf6DHA.3736@.cpmsftngxa07.phx.gbl>
<u4mVwal6DHA.1428@.TK2MSFTNGP12.phx.gbl>
> MIME-Version: 1.0
> Content-Type: text/plain
> Content-Transfer-Encoding: 7bit
> From: v-schang@.online.microsoft.com (Steven Cheng[MSFT])
> Organization: Microsoft
> Date: Wed, 04 Feb 2004 11:54:58 GMT
> Subject: Re: strugling with Atributed XML parsing.
> X-Tomcat-NG: microsoft.public.dotnet.framework.aspnet
> Message-ID: <wwyD$Wx6DHA.1988@.cpmsftngxa07.phx.gbl>
> Newsgroups: microsoft.public.dotnet.framework.aspnet
> Lines: 9
> Path: cpmsftngxa07.phx.gbl
> Xref: cpmsftngxa07.phx.gbl microsoft.public.dotnet.framework.aspnet:207429
> NNTP-Posting-Host: TOMCATIMPORT1 10.201.218.122
> Hi George,
> Thank you for the response. Regarding on the issue, I am
> finding proper resource to assist you and we will update as soon as
posible.
>
> Regards,
> Steven Cheng
> Microsoft Online Support
> Get Secure! www.microsoft.com/security(This posting is provided "AS IS",
> with no warranties, and confers no rights.)
I used the Xml Schema tool(xsd.exe) to automatically generate the schema
and serialize mapping class. To my surprise, the tool generated class
worked. Here is the xml format I used as example to generate class:
<clsOrder>
<MyHeader>Test Order</MyHeader>
<MyLine> dsfsdffd</MyLine>
<MyLine>dsfsdf</MyLine>
<MyLine> fdfdsf</MyLine>
</clsOrder
Then, I used xsd.exe to generate the schema and class ,here is the
generated class:

[System.Xml.Serialization.XmlRootAttribute(Namespac e="",
IsNullable=false)] public class clsOrder {

[System.Xml.Serialization.XmlElementAttribute(Form= System.Xml.Schema.XmlSche
maForm.Unqualified)]
public string MyHeader;

[System.Xml.Serialization.XmlElementAttribute("MyLine",
Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=true)]
public clsOrderMyLine[] MyLine;
}

public class clsOrderMyLine {

[System.Xml.Serialization.XmlTextAttribute()]
public string Value;
}

[System.Xml.Serialization.XmlRootAttribute(Namespac e="",
IsNullable=false)] public class NewDataSet {

[System.Xml.Serialization.XmlElementAttribute("clsOrder")]
public clsOrder[] Items;
}

It could serialize and deserialize with the xml format the customer exactly
want. Hope this help!

-Thank you
Madhu
Microsoft Developer Engineer

(This posting is provided "AS IS", with no warranties, and confers no
rights.)
closing this thread