Hide or add new line to variable - c#

Let's say I have this variable in my C# Code
string longVariableStuff = "hsduifgnw8e7rty83rfgediguidogy7834rghf7834ghf170934hf7034hgf734gf8170g437fg73408g1f784g1387fg4731gf7g13fg18347gf78134gf7834gf780134gfuhsdjkfhsdjkafhldsj";
Every time I'm coding, it gets a bit annoying when I scroll back it with the keyboard and my screen jumps to the right.
Is there anyway to just minimize it? Or maybe add a new line in the middle so I can view the whole thing without scrolling right?

Sure, you can just break it up:
string longVariableStuff =
"hsduifgnw8e7rty83rfgediguidogy7834rghf7834ghf170934hf7034hgf7" +
"34gf8170g437fg73408g1f784g1387fg4731gf7g13fg18347gf78134gf783" +
"4gf780134gfuhsdjkfhsdjkafhldsj";
This incurs absolutely no performance penalty, because the strings will be concatenated back into one string at compile time.

If you have really long strings it could be easier to manage them as string resource.
Right click on the project > Properties > Resources. Select Strings from the combo box. Enter a resource name and the string.
After saving, you should be able to access your string with
string s = Properties.Resources.MyStringName;

#Blorgbeard probably has the better answer, but there is a second way
string x = #"abcd
abcd
abcd
abcd";
Will get you "abcdabcdabcdabcd". The other version is much cleaner though so you should probably use that, I'm just adding this as an alternative.
Second idea that technically solves your problem but is a little clunky:
You can use a region to hide it in visual studio so you don't have to look at it when you don't have to.
#region my long string is in here
string longVariableStuff = "hsduifgnw8e7rty83rfgediguidogy7834rghf7834ghf170934hf7034hgf734gf8170g437fg73408g1f784g1387fg4731gf7g13fg18347gf78134gf7834gf780134gfuhsdjkfhsdjkafhldsj";
#endregion
Visual studio will allow you to collapse it so you don't have to look at it, and it won't affect horizontal scrollbar as you move the cursor over it.

Using the c# verbatim operator
MSDN
string multilinestring = #"my-
multiline
string";

StringBuilder is the performant way to concatenate long strings together.
String interpolation is another performant way. $"{a}{b}"

Related

WPF Fixed width Textbox font (Like Hex Editor)

I am building a file parsing tool in WPF that let's me adjust line length till data lines up. See this video around 2:10 https://www.youtube.com/watch?v=OMeghA82kSk
I really need to fix it so that the text has a fixed width. I had thought about maybe doing a DataGridView and having each cell be a character, but that seems slow and kinda silly. Since it is recreating the view constantly, it needs to perform rather quickly.
I feel like what I am asking isn't that unusual, but I have tried using all the Fixed Width fonts, but when it gets to the out of normal range control chars, it doesn't hold up.
I see other applications such as v64 that do exactly what I am looking for (see below). Do I need to use something other than a TextBox? What would be the ideal way to do this?
Ok, so I found the issue. First off, you HAVE to specify the file encoding or else it will skip some bytes. In my case it was skipping \x86 which threw everything off.
The only way I figured that out was by doing:
string shortText = File.ReadAllText("Original.dat");
File.WriteAllText("New.dat", shortText);
And then doing a byte by byte analysis. The right way is to do the following:
string shortText = File.ReadAllText("Wrapped.dat", Encoding.ASCII);
Even then, and even with a monospaced font it won't look correct. That is because most TTF fonts don't have a definition for things that aren't alphanumeric, so you add in a regular expression to strip out the rest and it works.
shortText = Regex.Replace(shortText, #"[^\w\n',|\.#-]", " ", RegexOptions.None);

Calling .ToString() on a string to change its format

In order to be able to dynamically change a value in my application I am storing it in the resx file. Of course this is a string.
MaximumSpend - 5000
In my code I do int.Parse(MyApp.MaximumSpend). Now I can change the max spend in one place and the application handles it with no futher changes.
In the front end I want to show the value as $5,000.
If this were an int, I would do
MyInt.ToString("0#,##0")
But it is already a string. I could convert to an int and then call .ToString() on it but that seems wasteful.
Is there a much better way of changing 5000 to 5,000 in my front end code? Or is changing to an int and back the best way?
UPDATE: Thanks everyone. I've gone ahead and done the int.parse and back to a string.
$('#MaximumSpend').text("#int.Parse(MyResources.MyNamespace.MaximumSpend).ToString("##,###")");
I'll be using the web.config for this in the future (I've already done that for other items, just not these which started as a purely front-end thing then I decided to use it in the backend).
I have upvoted accordingly
Resx files are not configuration files. They are meant to store static resources, like localized strings, images, and so on.
What you probably want is a Setting, which is two tabs down in the Visual Studio properties. There you can define an application-scoped setting which is typed to be an int, and it will generate a strongly typed accessor. No parsing required*.
Properties.Settings.Default.MyInt.ToString("0#,##0");
Here's some more information on the subject: Using Settings in C#.
* Technically, it's still parsed, but .NET does it for you.
Just clone a en-US culture (which uses $ as a CurrencySymbol), set it's CurrencyDecimalDigits to 0 and format your number with The "C" format specifier and that cloned culture as;
int i = 5000;
var clone = (CultureInfo)CultureInfo.GetCultureInfo("en-US").Clone();
clone.NumberFormat.CurrencyDecimalDigits = 0;
Console.WriteLine(i.ToString("C", clone)); // $5,000
EDIT: Looks like you have a string "5000" in first place, you need to parse it first to int with int.Parse and then can use that integer value to generate specific formatted string.
int i = int.Parse("5000");
...
...
The short answer is: no, there's no better way
The long answer is:
You could parse the string and convert it, but it'd probably be way worse than just converting to int, then back to string with formatting.
You could just store the value in your resource as an integer directly, instead of as an string. The designer doesn't allow you to directly do it, but you can open the .resx file with a text editor (or in Visual Studio, right click on it, Open With and select the XML Text Editor), and add your resource on the correct section, like this:
<data name="MaximumSpend" xml:space="preserve" type="System.Int32, mscorlib">
<value>5000</value>
</data>
Afterwards, you can view it on the normal resource editor (you'll see your value in the Other section. You can even edit it, just not "add more")
Or:
Use a settings file, instead of a resource, which probably makes more sense for this kind of data
I think changing from an int and back to a string is perhaps the best way. For example:
string strIntString = strMaxSpend.Split("-").Trim();
int nValue;
if (!Int32.TryParse(strIntString, out nValue))
{
//Parse failed
}
Note I use TryParse instead of a straight Convert call incase the conversion fails so we can fail smoothly.
Then just doing the ToString() part as mentioned in your question.
Try This :
string s = "2342314854";
string s1 = string.Format("{0:C}", Double.Parse(s));
Result will be : $2,342,314,854.00
this code will work to convert string value into currency.

Declaring variables slow down program

I have a program which uses a RichTextBox (which is part of Tab Control) and in the TextChanged event I these variable declarations:
RichTextBox programTextBox = (RichTextBox)tabControl.TabPages[tabControl.SelectedIndex].Controls[0];
int selectStart = programTextBox.SelectionStart;
int programCurrentLine = programTextBox.GetLineFromCharIndex(programTextBox.SelectionStart);
int programCurrentLineIndex = programTextBox.GetFirstCharIndexFromLine(programCurrentLine);
int programCurrentLineLength = programTextBox.Lines[programCurrentLine].Length;
string programCurrentLineText = programTextBox.Lines[programCurrentLine].ToString();
All of them are important in that particular event and I use them multiple times for multiple purposes. However, recalculating every single time slows down my program.
For example, I've noticed that if I open a somewhat large file (with my RichTextBox) and then start pressing e.g. the 'a' button, there is some noticable lag. Deleting every single piece of code except the declaration of these variables does not help at all with the lag, but also deleting the code above, completely solves the problem.
I have two questions: 1) Why do these declarations slow down that much the TextChanged event and 2) What can I do? (Is there a faster way to calculate these variables?)
It's not the variable declarations - it's the code you're using to initialize them. I wouldn't be at all surprised to find that GetLineFromCharIndex and GetFirstCharIndexFromLine were expensive - and currently you're calling the Lines property twice.
You could probably improve matters at least slightly just by removing one of those Lines calls, simply by fetching the line first and then looking at its length:
// No need to call ToString() - Lines is a string[]
string programCurrentLineText = programTextBox.Lines[programCurrentLine];
int programCurrentLineLength = programCurrentLineText.Length;
It's a shame there isn't some way of saying "Get all the information about the position of the given index: its line, first char index from line, and the line itself" in one call :(
If it is not important to recalculate on every key press you might be better off implementing a boolean variable which is set on keypress then has a timer to reset it. For example adding a 1.2 second delay on the event. I am not sure the needs of your app so that time might be a bit much.

Acceptable to have spaces before dot?

What is the general opinion on the 2nd indentation method below.
// Normal indentation
a.Value = "foobar";
ab.Checked = false;
foo.Value = "foobar";
foobar.Checked = true;
// Spaces before the dot to align the properties/methods
a .Value = "foobar";
ab .Checked = false;
foo .Value = "foobar";
foobar.Checked = true;
This should probably be a wiki, but I either don't have enough privileges or don't know how to change it.
edit
I've decided to add another example to better show where such an indentation style might be useful.
fooA .PropertyA = true;
foobarB.PropertyA = true;
Changing PropertyA on all lines would be much easier with the new multi-line editing feature in VS2010.
Also having whitespace, and even line-breaks before the dot is not uncommon at all in C# (see LINQ).
Spaces before the dot? Dear God no!
I would never use either personally. I would use just traditional formatting, eg:
a.Value = "foobar";
ab.Checked = false;
foo.Value = "foobar";
foobar.Checked = true;
I understand this may not be as pleasing to the eye, but feel the others are less ideal.
Reasons being:-
Harder to maintain: Sometimes you may have smaller or larger variable names, or introduce other variables in your code which means you have to adjust formatting of all entries.
Automatic formatting might mess this up: If you use ReSharper (possibly with standard VS?) when pressing ; the formatting will adjust it back into line anyway, so you have to go out of your way to ensure it wouldn't do this.
I can't think of one right now, but I can't handle only having two points.
Edit! Thought of another point. There are more tricky keystrokes involved: For instance, for me with ReSharper to achieve the latter formatting I would type foo, enter/tab (to confirm auto-complete), tab times X amount of tabs required up to variable length (annoying), ., Value, tab to confirm auto-complete again, = then assigning data then ; and then yell at Visual Studio because all my non-standard formatting was undone as I expressed in point 2, so finally a press of CTRL+z would restore back the formatting we just had. :)
I've always used "Normal indentation." The other way seems less clear to me because I am not expecting to see indentation of that nature.
I would use spaces before the dot only if it's all the same property/method. If it's a mix of properties, like you have in your example, I'd stick with 'Normal'.
However, I think it's a moot point, because the Visual Studio autoformatter will collapse everything next time someone types a } to close any enclosing block.
Acceptable from C# language point of view.
First style is easier for me to read compared to second. I think it is because spaces before dot look very strange - in most written languages there is no space before dot.
I personally don't fight with VS IDE. Default style is fine with me.
Note that using proportional fonts totally breaks such formatting (using such fonts is extremly unusual for editing code, but ask around).
Edit: using space (+new line) for fluent interfaces looks good ( http://en.wikipedia.org/wiki/Fluent_interface#C.23).
I tried it a couple of time. Never was happy with out it looked afterwords.
I always thought aligning on the 'dot' might work in the right context:
// -----------------------
// decimal-style alignment
// -----------------------
a.Value = "foobar" ;
ab.Checked = false ;
foo.Value = "foobar" ;
foobar.Checked = true ;
But you lose the clean left margin that leads the eye down the page and maintains your sense of indent level. So you're back to keeping the dot with the identifiers it connects. However...
Aligning the equal signs is good practice as it helps order the whole set:
// -----------------------
// tabular coding
// -----------------------
a.Value = "foobar" ;
ab.Checked = false ;
foo.Value = "foobar" ;
foobar.Checked = true ;
The more order one imposes on one's code the more likely one is to notice things that are out of whack.
The parser doesn't care about tidy, readable code, but the compiler isn't the target audience for your code. Your target audience is other human beings that have to read it and comprehend it. In particular the poor schmuck — who might be you! — that has to pick up the code in a hurry and fix it 3 or 5 years from now, without no documentation to aid in understanding.
The spaces before the dots I would NEVER do, simply because as I am reading code I stop looking for a dot as soon as I see a space. The spaces after the dot, I HAVE done in the past, but hardly ever and I really prefer not to use it. The problem with using a style like that is that even if it is more readable to you, if you take such a large leap (meaning the spaces before the dot) from what might be considered a "norm" then you are going to hinder more people than help. Sticking with the standard in your team or workplace is the most important thing. Even if it is not a black and white standard, if the other 99 developers at your company us VS standard and you put all the spacing before your dots it is not going to improve anything.

C# Application Becomes Slow and Unresponsive as String in Multiline Textbox Grows

I have a C# application in which a LOT of information is being added to a Textbox for display to the user. Upon processing of the data, almost immediately, the application becomes very slow and unresponsive. This is how I am currently attempting to handle this:
var saLines = textBox1.Lines;
var saNewLines = saLines.Skip(50);
textBox1.Lines = saNewLines.ToArray();
This code is run from a timer every 100mS. Is there a better way to handle this? I am using Microsoft Visual C# 2008 Express Edition. Thanks.
The simple answer is TextBox.AppendText().
You get much better performance initially.
I tested writing a 500 char message every 20 ms for 2 mins (with BackgroundWorker) and the UI remained responsive and CPU minimal. At some point, of course, it will become unresponsive but it was good enough for my needs.
Try by having in memory a list with the content, and removing the first 50 elements by RemoveRange and then going with ToArray();
Like this :
lst.RemoveRange(0,50);
textBox1.Lines = lst.ToArray();
It should be a lot faster.
I'd say your main problem here is that you are using the TextBox as your primary storage for your text. Everytime you call TextBox.Lines, the string is split on Environment.NewLine.
Try turning it around:
Store the text in a new List<String>(maxLines)
In your AddLine method, check the length of your text buffer and use RemoveRange(0, excessCount)
Update your display TextBox by calling String.Join(Environment.NewLine, textBuffer.ToArray())
That last call is a bit expensive, but it should stop your slowdowns. To get it any faster you'd need to use a statically sized string array and move the references around yourself.
The most efficient way to trim an array is to create a new array of the desired size, then use Array.Copy to copy the desired portion of the old array.
I would recommend that you maintain a List<string> containing all of your lines.
You should use a StringBuilder to build a string containing the lines you're looking for, and set the textbox's Text proeprty to the StringBuilder's string. For added performance, set the StringBuilder's capacity to a reasonable guess of the final sie of the string. (Or to list.Skip(...).Take(...).Sum(s => s.Length))
If you're concerned about memory, you can trim the List<string> by calling RemoveRange.
As long as you don't put too much in the textbox at once, doing it this way should be extremely fast. All of the manipulation of the List<string> and the StringBuilder can be done in a background thread, and you can pass the completed string to the UI thread.
The TextBox.Lines property simply concatenates the array you give it using a StringBuilder, so there's no point in using it (and making a needless array).
Instead of splitting the text and then re-joining it, just get the sub-string from the 51st line:
int i = textBox1.GetFirstCharIndexFromLine(50);
if (i > 0) textBox1.Text = textBox1.Text.Substring(i);

Categories

Resources