Showing posts with label created. Show all posts
Showing posts with label created. Show all posts

Monday, March 26, 2012

StringBuilder with line break escape.

I created a StringBuilder and append string values to it, but each string I inserted a "\n" to sparate values. When I write the StringBuilder values out to a text file. The line break with "\n" did not work. Anybody knows why?

StringBuilder sb = new StringBuilder();
sb.Append("Some Value \n");
sb.Append("Another Value \n");

// create a stream writer and write all string values to the file
StreamWriter sw = File.CreateText(path)
sw.WriteLine(sb.ToString());

Another question, what is the default Capacity of a StringBuilder object created like the code above?\n is a javascript newline but you are not using javascript...instead do something like this:


StringBuilder sb = new StringBuilder();
sb.Append("Some Value" & vbcrlf);
sb.Append("Another Value" & vbcrlf);

'or

StringBuilder sb = new StringBuilder();
sb.Append("Some Value" & vbnewline);
sb.Append("Another Value" & vbnewline);


oooh, just realized that this is c#....I know the vbnewline and vbcrlf do new lines in VB but not sure about c#...sorry

Also, to your other question...from the online notes for stringbuilder:
----------------------
Notes to Implementers: The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue.
----------------------

MajorCats
All .net languages support the Environment.NewLine property. The property value is a constant customized specifically for the current platform. This value is automatically appended to text when using WriteLine methods.

Try that instead.

However, couldn't you simply rewrite the entire chunk as:


StreamWriter sw = File.CreateText(path)
sw.WriteLine("Some Value");
sw.WriteLine("Another Value");
...and avoid the StringBuilder entirely (since the WriteLine method will automatically insert on a newline?

Not sure about the Capacity question. From MSDN:

Capacity does not affect the string value of the current instance. Capacity can be decreased as long as it is not less than Length.

The StringBuilder dynamically allocates more space when required and increases Capacity accordingly. For performance reasons, a StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation-specific.
First of al it is better to use Environment.NewLine.
But if you realy want to use it, use \r\n ... that will work
Cool, thank you all.

Environment.NewLine works perfectly in my situation, "\r\n" works as well in C#.
In addition to daver's post:

The StringBuilder allows for specifying the capacity by using the Capacity property:
sb.Capacity = 200 allows for 200 characters. The default capacity is 16.

so don't think that you should never use StringBuilder. The StringBuilder should be used in place of concatenating strings instead of using the &= as that creates a new instance of the string each time it is used and should provide better performance with large strings.
I use StringBuilder just for the performance reason you mentioned. But, I don't believe its default capacity is 16, as it's too small. The first replier said it is the maximum value of int. This sounds reasonable to me. Are you saying that it initially allocate a buffer for 16 characters, and will auto-expand the buffer as needed? The fininal buffer size would not exceed StringBuilder's default capacity. Is this right?
The default capacity for this implementation is 16, and the default maximum capacity is Int32.MaxValue (2,147,483,647; that is, hexadecimal 0x7FFFFFFF)
Hi, adec

What do you mean by "this implementation"? When I create a StringBuilder object by:

StringBuilder sb = new StringBuilder();

What does the "16" mean to me? I should not worry about anything as long as total number of char in my final string is less than Int32.MaxValue, shouldn't I?
You do not really have to worry about it. If you are pretty sure to what capacity your SB should cater, set it to limit the memory allocated. If you don't, the SB will automatically adapt. In fact you may well set it to 16 (characters) in the first place. It will dynamically adapt.
I've never done the performance comparison,
but rather than concatenate the newline (we're avoiding concatenation - right?)

try using the stringbuilder.appendformat method

sb.AppendFormat("Some Value{0}", Environment.NewLine);
sb.Appendformat("Another Value{0}", Environment.NewLine);
As a general rule, if you need to create a lot of text, do not use Concatenation. Performance wise, the Stringbuilder is superior to Concatenation, and should be used in place of this.
try this:


StringBuilder s = new StringBuilder();
s.Append("HEllo <BR>");
s.Append("World");
Response.Write(s);

I am actually kind of curious as to why one would instantiate a StringBuilder (using line terminations), use the File.CreateText to create a StreamWriter, and then call StreamWriter.Write() passing the StringBuilder to the StreamWriter when the StreamWriter does it all?
StreamWriter sw = new StreamWriter(@."path");
sw.WriteLine("SomeValue");
sw.WriteLine("AnotherValue");
sw.Close();

Is there anything wrong with this approach?
I suppose that all depends on what you need the string for.

if you need it for multiple purposes, then creating a stringbuilder is ok as its reusable.
if you need to perform replacements then appendformat is very useful.
if you have additional concatenations to perform then stringbuilder is best.
i.e. dont do (sw.WriteLine("SomeValue" & "somother value" & "yet anothervalue");

if you're just blasting data into a disk file, then perhaps a stringbuilder represents an extra [unnecessary] step.

of course, we're all just speculating about the real world requirement behind the original posters question...

Saturday, March 24, 2012

Strong name signature could not be verified

Hi,

I've downloaded a set of C++ files written by someone else (a wrapper for the ImageMagick object called MagickNet), created an snk file using sn -k and figured out how to add this reference to the assembly (I'm not a C++ programmer, but I figured out to use assembly:AssemblyKeyFileAttribute in AssemblyInfo.cpp). The result seems to compile fine.

However, when I add a reference to the dll in VS2005 and try to compile my project there, I get:

Error 4 Could not load file or assembly 'MagickNet' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)

I get something similar trying to use gacyutil to add the dll to the GAC.

Does anyone know what on earth is going on here? I've googled this and it looks like a pretty rare error message, certainly no-one else out there seems able to shed any light on it.

Can anyone assist?

Cheers,

Matt

Sorted it eventually, thought I'd post here with the solution in case anyone else came across the problem.

The issue turns out to be with the way you assign the key file to the build in C++. In older versions of Visual Studio the solution I adopted (adding a line to AssemblyInfo.cpp) was apparently the correct one but it's not correct in Visual Studio 2005, although it won't give you an error if you build with it. Instead you need to go to project properties, then linker, then advanced and edit the entry for key file in there. This will build a correctly signed assembly.

This is really poorly documented. Astonishingly, I only found the answer on a generic page about file building focused on C# and VB ... there's nothing about this I can see in the equivalent C++ pages!

http://msdn2.microsoft.com/en-us/library/6f05ezxy(VS.80).aspx

Cheers,

Matt

Thursday, March 22, 2012

Strongly typed datasets and nested repeaters

I have a strongly typed dataset that returns two tables - "items" and
"itemdetails". In the strongly-typed dataset designer, I've created a link
(relationship) between the two tables based on a foreign key.

I want to put them into a nested repeater, but I'm having problems finding a
"nice" way of doing it.

Can someone please point me in the direction of a tutorial or best practice
to achieve this?

Thanks in advance,

Duncanassign the "Items" table to the outter repeater, then in the
OnItemDataBound event handler:

switch (e.Item.ItemType){
case ListItemType.Item: case ListItemType.AlternatingItem:
Repeater ir = e.Item.FindControl("rptInnerRepeater")
ir.DataSource =
((DataRowView)e.Item.DataItem).CreateChildView("ItemDetailDataRelation");
ir.DataBind();
}

hope that helps
Thanks for your reply; I saw this example on the web, but I'm unsure where
the ItemDetailDataRelation comes from. I tried all the relationship names
that were in the strongly-typed dataset designer, but they gave an error.

I got the impression that if you were doing it between two datatables, that
would be the name of the Relations.Add(... but I couldn't seem to create a
programatic relationship between two fields in a strongly typed dataset.

Duncan

"bfking" <bfking@.gmail.com> wrote in message
news:1112879887.227421.298170@.g14g2000cwa.googlegr oups.com...
> assign the "Items" table to the outter repeater, then in the
> OnItemDataBound event handler:
> switch (e.Item.ItemType){
> case ListItemType.Item: case ListItemType.AlternatingItem:
> Repeater ir = e.Item.FindControl("rptInnerRepeater")
> ir.DataSource =
> ((DataRowView)e.Item.DataItem).CreateChildView("ItemDetailDataRelation");
> ir.DataBind();
> }
> hope that helps
The relation is set up in the dataset.

something like
_myDataSet.Relations.Add("Users_Results", _myDataSet.TableA.UsersNameColumn,
_myDataSet.TableB.UsersNameColumn);

where _myDataSet is your strongly typed DataSet.
in your nested Repeater you would then do something like this:

<asp:repeater id="_reportoutput" Runat="server"
...templates

//nested repeater
<asp:repeater id="_nextstuff" Runat="server" DataSource='<%#
GetChildRelation(Container.DataItem,"Users_Results")%>'
with the following in your code behind:

public static DataView GetChildRelation(object dataItem, string relation)
{
DataRowView drv = dataItem as DataRowView;
if (drv != null)

return drv.CreateChildView(relation);
else
return null;
}

MattC
"Duncan Welch" <dunc@.ntpcl.f9.co.uk> wrote in message
news:usyUFl3OFHA.984@.TK2MSFTNGP10.phx.gbl...
> Thanks for your reply; I saw this example on the web, but I'm unsure where
> the ItemDetailDataRelation comes from. I tried all the relationship names
> that were in the strongly-typed dataset designer, but they gave an error.
> I got the impression that if you were doing it between two datatables,
> that
> would be the name of the Relations.Add(... but I couldn't seem to create a
> programatic relationship between two fields in a strongly typed dataset.
> Duncan
> "bfking" <bfking@.gmail.com> wrote in message
> news:1112879887.227421.298170@.g14g2000cwa.googlegr oups.com...
>> assign the "Items" table to the outter repeater, then in the
>> OnItemDataBound event handler:
>>
>> switch (e.Item.ItemType){
>> case ListItemType.Item: case ListItemType.AlternatingItem:
>> Repeater ir = e.Item.FindControl("rptInnerRepeater")
>> ir.DataSource =
>> ((DataRowView)e.Item.DataItem).CreateChildView("ItemDetailDataRelation");
>> ir.DataBind();
>> }
>>
>> hope that helps
>>

Strongly typed datasets and nested repeaters

I have a strongly typed dataset that returns two tables - "items" and
"itemdetails". In the strongly-typed dataset designer, I've created a link
(relationship) between the two tables based on a foreign key.
I want to put them into a nested repeater, but I'm having problems finding a
"nice" way of doing it.
Can someone please point me in the direction of a tutorial or best practice
to achieve this?
Thanks in advance,
Duncanassign the "Items" table to the outter repeater, then in the
OnItemDataBound event handler:
switch (e.Item.ItemType){
case ListItemType.Item: case ListItemType.AlternatingItem:
Repeater ir = e.Item.FindControl("rptInnerRepeater")
ir.DataSource =
((DataRowView)e.Item.DataItem).CreateChildView("ItemDetailDataRelation");
ir.DataBind();
}
hope that helps
Thanks for your reply; I saw this example on the web, but I'm unsure where
the ItemDetailDataRelation comes from. I tried all the relationship names
that were in the strongly-typed dataset designer, but they gave an error.
I got the impression that if you were doing it between two datatables, that
would be the name of the Relations.Add(... but I couldn't seem to create a
programatic relationship between two fields in a strongly typed dataset.
Duncan
"bfking" <bfking@.gmail.com> wrote in message
news:1112879887.227421.298170@.g14g2000cwa.googlegroups.com...
> assign the "Items" table to the outter repeater, then in the
> OnItemDataBound event handler:
> switch (e.Item.ItemType){
> case ListItemType.Item: case ListItemType.AlternatingItem:
> Repeater ir = e.Item.FindControl("rptInnerRepeater")
> ir.DataSource =
> ((DataRowView)e.Item.DataItem).CreateChildView("ItemDetailDataRelation");
> ir.DataBind();
> }
> hope that helps
>
The relation is set up in the dataset.
something like
_myDataSet.Relations.Add("Users_Results", _myDataSet.TableA.UsersNameColumn,
_myDataSet.TableB.UsersNameColumn);
where _myDataSet is your strongly typed DataSet.
in your nested Repeater you would then do something like this:
<asp:repeater id="_reportoutput" Runat="server">
...templates
//nested repeater
<asp:repeater id="_nextstuff" Runat="server" DataSource='<%#
GetChildRelation(Container.DataItem,"Users_Results")%>'>
with the following in your code behind:
public static DataView GetChildRelation(object dataItem, string relation)
{
DataRowView drv = dataItem as DataRowView;
if (drv != null)
return drv.CreateChildView(relation);
else
return null;
}
MattC
"Duncan Welch" <dunc@.ntpcl.f9.co.uk> wrote in message
news:usyUFl3OFHA.984@.TK2MSFTNGP10.phx.gbl...
> Thanks for your reply; I saw this example on the web, but I'm unsure where
> the ItemDetailDataRelation comes from. I tried all the relationship names
> that were in the strongly-typed dataset designer, but they gave an error.
> I got the impression that if you were doing it between two datatables,
> that
> would be the name of the Relations.Add(... but I couldn't seem to create a
> programatic relationship between two fields in a strongly typed dataset.
> Duncan
> "bfking" <bfking@.gmail.com> wrote in message
> news:1112879887.227421.298170@.g14g2000cwa.googlegroups.com...
>

Struct Default Constructor Question

When I create a new object of type struct, I want objects to be created for each member variable in that struct. For example:

private struct Strings {
public string s1;
public string s2;
}

Strings myStrings = new Strings();

Based on what I read, the default constructor for the struct should automatically initalize s1 and s2 to string.Empty implicitly. However, doing something like int size = myStrings.s1.Length throws a NullReferenceException. I don't understand why myStrings.s1 does not exist. Aren't s1 and s2 created automatically when I create a new object called myStrings??

Hello anonim:

> Based on what I read, the default constructor for the struct should automatically initalize s1 and s2 to string.Empty implicitly.

I'm afraid this is not correct. There's no implicit initialization of objects anywhere and your strings won't be created automatically.

So here is how one commonly would write it:

private struct Strings {
public string s1;
public string s2;

public Strings() {
s1 = String.Empty;
s2 = String.Empty;
}
}

Strings myStrings = new Strings();

Feel free to ask more.

HTH. -LV


Ludovico, thanks for your reply.

Per the MSDN [link]:

"Unlike a class, a struct is not permitted to declare a parameterlessinstance constructor. Instead, every struct implicitly has aparameterless instance constructor that always returns the value thatresults from setting all value type fields to their default value andall reference type fields to null. A struct can declare instance constructors having parameters."

So based on that, you cannot create a parameterless constructor for any struct (public Strings() { ...} does not compile - try it).

The statement above says all value type fields are set to their default value, and all reference type fields are set to null. Based on the fact that the implicit constructor does not initialize the string variables in my struct, I can safely assume that these string variables are reference types, correct? So, what I must do is to create a constructor with parameters and use that to instantiate and initialize the struct member variables.

Thanks for your help.

anonim:

> Unlike a class, a struct is not permitted to declare a parameterless instance constructor.

Yes, you are right, sorry...

> The statement above says all value type fields are set to their default value, and all reference type fields are set to null. Based on the fact that the implicit constructor does not initialize the string variables in my struct, I can safely assume that these string variables are reference types, correct?

Yes: String is a class, so strings are reference types, not value types.

> So, what I must do is to create a constructor with parameters and use that to instantiate and initialize the struct member variables.

Right again!

Cheers. :) -LV


Thank you much!

Structure

Hello,

I have created a structure, MyStruct, with 3 properties: Name
(String), Valid (Boolean) and Type (Enumeration Type).

I need to do the following:
1. Create a list of items of type MyStruct using a simple method like:
MyStruct.Add(...)
2. Access each list item using a For Loop.

Could someone, please help me out?

I have been trying collections, arrays, adding methods inside my
structure but I have not been able to make this work.

Thank You Very Much,
MiguelIf you are using 2.0, a generic list is the best approach.

dim something as new List(of MyStruct)

something.Add(firstStructure)

for each struct as MyStruct in something
'do something
next

Karl

In 1.x, you can either use an ArrayList, or create a custom collection by
extending the CollectionBase class

--
http://www.openmymind.net/
http://www.fuelindustries.com/
"shapper" <mdmoura@.gmail.comwrote in message
news:1173113846.509770.105130@.q40g2000cwq.googlegr oups.com...

Quote:

Originally Posted by

Hello,
>
I have created a structure, MyStruct, with 3 properties: Name
(String), Valid (Boolean) and Type (Enumeration Type).
>
I need to do the following:
1. Create a list of items of type MyStruct using a simple method like:
MyStruct.Add(...)
2. Access each list item using a For Loop.
>
Could someone, please help me out?
>
I have been trying collections, arrays, adding methods inside my
structure but I have not been able to make this work.
>
Thank You Very Much,
Miguel
>

Structure

Hello,

I have created a structure, MyStruct, with 3 properties: Name (String), Valid (Boolean) and Type (Enumeration Type).

I need to do the following:
1. Create a list of items of type MyStruct using a simple method like:
MyStruct.Add(...)
2. Access each list item using a For Loop.

Could someone, please help me out?

I have been trying collections, arrays, adding methods inside my structure but I have not been able to make this work.

Thank You Very Much,
Miguel

shapper:

Hello,

I have created a structure, MyStruct, with 3 properties: Name (String), Valid (Boolean) and Type (Enumeration Type).

I need to do the following:
1. Create a list of items of type MyStruct using a simple method like:
MyStruct.Add(...)

Rather Use Classes where you can have the above 3 properties & also get Methods Like Add() ,Delete() etc.Then Create an Array of that Class.
2. Access each list item using a For Loop.
When u make the Array of a Class u can use the For/ForEach loops to access the element of the array.
Could someone, please help me out?

I have been trying collections, arrays, adding methods inside my structure but I have not been able to make this work.

Thank You Very Much,
Miguel