In JavaScript I can easily get a value from a css file. For example, the width of a certain class. This is done in the question below:
How do you read CSS rule values with JavaScript?
I want to know the CSS width value in my C# code to calculate the width of my scroll area. What I have so far is:
int toDoWidth = 100;
using (StreamReader cssFile = File.OpenText(Server.MapPath("~/Content/Tracker.css")))
{
string line = null;
while ((line = cssFile.ReadLine()) != null)
{
if (line == ".my_note {")
{
line = cssFile.ReadLine();
if (line != null)
{
line = line.Substring(line.IndexOf(":")+2);
line = line.Substring(0, line.IndexOf("px"));
toDoWidth = line.AsInt();
}
break;
}
}
}
...
My code simply does not feel right. If later in development someone changes the CSS by adding a value before width in my_note class, then my code would not work anymore...
Is there a simpler/better way to open the CSS file and read a certain property in C# code?
p.s.: I'm reading/searching since years on Stack Overflow, but I thought it's time to post my first question ;)
Related
I'm pulling the content from a text file into a RichTextBox. I've got the RichTextBox set up to where it only shows 6 lines at a time. I've got a search method that finds the text I need within the RichTextBox, but what I am needing it to do is display 6 specific lines. Each "item" in my text file consists of 6 lines. No matter which of the six lines the search method finds the text on, I need the RichTextBox to only display the 6 lines of each "item" with the currently selected "found" text remaining highlighted.
I've gotten it working reasonably well thanks to a few code examples I've pull from this site. But every now and then, it doesn't work entirely well, and am looking for some advice from a fresh set of eyes looking at my code and perhaps even be told an easier/more efficient way to go about it. But here is my code so far. Thanks in advance!
try
{
string s = txtFindPlaylistEntry.Text;
rtxEditPlaylistEntry.Focus();
findPosEntry = rtxEditPlaylistEntry.Find(s, findPosEntry, RichTextBoxFinds.None);
// Jump to the line we need.
int count = rtxEditPlaylistEntry.GetLineFromCharIndex(findPosEntry);
count = (count - (count % 6)) + 1; // Must be divisible by 6 then plus 1
rtxEditPlaylistEntry.SelectionStart = rtxEditPlaylistEntry.Find(rtxEditPlaylistEntry.Lines[count]);
rtxEditPlaylistEntry.ScrollToCaret();
rtxEditPlaylistEntry.Select(findPosEntry, s.Length);
findPosEntry += txtFindPlaylistEntry.Text.Length;
}
catch
{
MessageBox.Show("No occurences found");
findPosEntry = 0;
}
As of right now, I'm attempting to use a line count with modulus plus 1 to get the line I need. Like I said, it works, just not 100% of the time and I can't figure out why.
EDIT to try to accommodate Minimal, Complete, Verifiable.
I've already posted my "find" function. Here is other related code that might be useful. First, here is my code for creating the various controls I am using.
rtxEditPlaylistEntry = new RichTextBox();
rtxEditPlaylistEntry.Location = new System.Drawing.Point(15, 90);
rtxEditPlaylistEntry.Size = new System.Drawing.Size(375, 85);
rtxEditPlaylistEntry.Multiline = true;
rtxEditPlaylistEntry.ScrollBars = RichTextBoxScrollBars.None;
Here is my button function to pull text from a file and place it into the RichTextBox.
private void btnBrowseForPlaylistToEditEntry_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "LPL Files|*.lpl";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
savedFileNameEntry = openFileDialog.SafeFileName;
txtPathToPlaylistToEditEntry.Text = openFileDialog.FileName;
}
// After finding the file, load it into the richtextbox control
using (StreamReader sr = File.OpenText(openFileDialog.FileName))
{
// Initially show the first 6 lines (IE first entry). This should be accomplished by
// the richtextbox control settings
rtxEditPlaylistEntry.Text = sr.ReadToEnd();
}
previousNextCount = 0;
}
I hope this is sufficient. If not please let me know!
I'm trying to highlight a whole line in a RichTextBox. Right now I have this method
if (Current != null)
{
selectStart = this.textBox.Text.Length;
foreach (string s in Current.Details)
{
this.textBox.AppendText(s + Environment.NewLine);
}
selectEnd = this.textBox.Text.Length;
this.textBox.Select(selectStart, selectEnd - selectStart);
this.textBox.SelectionBackColor = Color.FromArgb(51, 255, 51);
}
But this results with only highlighting the text, as shown here:
I want the code to highlight the whole line length. Is there a way to do that ?
I don't think you can do what you want to do as the RichTextBox does not support the box model (like browsers would with a <div> block). It will only ever decorate the text itself.
I want to implement something that programmatically changes the background of the text when provided with a documentline.(Something that looks very similar to a block selection of a text. I'm going to be using this for debug breakpoints of an IDE I'm designing). I don't want to have to use selection as it causes the textbox to scroll.
I think I need to make use of DocumentColorizingTransformer but I'm not 100% sure how to go about this.
public class ColorizeAvalonEdit : ICSharpCode.AvalonEdit.Rendering.DocumentColorizingTransformer
{
protected override void ColorizeLine(ICSharpCode.AvalonEdit.Document.DocumentLine line)
{
int lineStartOffset = line.Offset;
string text = CurrentContext.Document.GetText(line);
int start = 0;
int index;
if (line.LineNumber == LogicSimViewCodeWPFCtrl.currentLine)
{
while ((index = text.IndexOf(text, start)) >= 0)
{
base.ChangeLinePart(
lineStartOffset + index, // startOffset
lineStartOffset + index + text.Length, // endOffset
(VisualLineElement element) =>
{
element.TextRunProperties.SetBackgroundBrush(Brushes.Red);
});
start = index + 1; // search for next occurrence
}
}
}
}
currentLine is the portion that will be highlighted.
The above code does work properly.. only problem is if the currentLine ever changes while I am viewing that line, it doesn't highlight the updated line until I scroll to another portion of the document (hiding the updated line), and come back to the updated line.
Also, how do I make the line numbers start from zero?
Since it was their creation, I peeked at SharpDevelop's source and how they did it.
They defined a bookmark type (BreakpointBookmark) and added bookmark to the line.
bookmark itself sets the color of the line in CreateMarker method. It is strange that it is not possible to configure colors of the break-point in SharpDevelop.
Hope it helps.
protected override ITextMarker CreateMarker(ITextMarkerService markerService)
{
IDocumentLine line = this.Document.GetLine(this.LineNumber);
ITextMarker marker = markerService.Create(line.Offset, line.Length);
marker.BackgroundColor = Color.FromRgb(180, 38, 38);
marker.ForegroundColor = Colors.White;
return marker;
}
I found the answer
TxtEditCodeViewer.TextArea.TextView.Redraw();
Isn't this a duplicate of this question?
However it looks like you should call InvalidateArrange() on the editor or InvalidateVisual() on each changed visual.
I know that this is possible to be done with application settings, but I want to do it this way:
I have some textboxes and other controls that have Text property. I am doing a loop and save the Name and Text property of them in a text file. The saving statement is like:
if (ctrl != null) sb.AppendLine(ctrl.Name.ToString() + ":" + ctrl.Text);
When I want to load them back I want to do it this way, but since I can not point to the Name of the controls, I am stuck! (I beleive it was possible in PHP to point to a variable using other variables!)
using (StreamReader file = new StreamReader(ofile.FileName))
{
while((line = file.ReadLine()) != null)
{
if (line.StartsWith("#")) continue; //Line is a commment so skip
else
{
data = line.Split(':');
//How to set back the text property to the variable?
}
}
}
What I have in mind now, is to save Tag property of controls instead of theire Name property. But the problem is my controls are all scaterred in side nested panels and stuff like that so I have to do a lot of LOOPING! to compare theire tags with tags avilable in my saved file (note that I am not going to save all controls in the text file, just some of em!)
What to do ?
You can find control by it's name if you have access to form's Controls property
var textBox = yourForm.Controls.Find("name", true) as TextBox;
if(textBox != null)
textBox.Text = "text";
Store all your controls in a key value pair container where key is the name of the control and value is a reference to the control it self. You can use a Dictionary to store them. When loading back from the text file, use the key to find the appropriate control and set the text.
your question is unclear .what i understand is you want to write text property to a text file and later restore via txt file if so then its a straighforward solution [in Winform]
to save use the format control-name:text
later on load
use
this.Controls[<controlname>].Text=Text
i.e. in your context
while((line = file.ReadLine()) != null)
{
if (line.StartsWith("#")) continue; //Line is a commment so skip
else
{
string[] data = line.Split(':');
if(data.Length>0)
{
if(this.Controls.ContainsKey(data[0]))
{
if(this.Controls[data[0]] is TextBox)
{
//generic
// this.Controls[data[0]].Text=data[1];
//or use
((TextBox) this.Controls[data[0]]).Text=data[1];
}
}
}
}
}
please note that this.Controls return a Control Object if you want to do any specific operations please Type Cast and then apply.
Also if you try to access
Hope that helps.
I have an Asp.Net page with a list of options accompanied by a checkbox in a ListView control. I have applied Paging using the paging control. However I want to maintain the status of the checkboxes across the various paged pages of the ListView. I have done this with the following code
private List<int> IDs
{
get
{
if (this.ViewState["IDs"] == null)
{
this.ViewState["IDs"] = new List<int>();
}
return (List<int>)this.ViewState["IDs"];
}
}
protected void AddRowstoIDList()
{
int checkAction = 0;
foreach (ListViewDataItem lvi in lvCharOrgs.Items)
{
CheckBox chkSelect = (CheckBox)lvi.FindControl("chkSelect");
if ((((chkSelect) != null)))
{
int ID = Convert.ToInt32(lvCharOrgs.DataKeys[lvi.DisplayIndex].Value);
if ((chkSelect.Checked && !this.IDs.Contains(ID)))
{
this.IDs.Add(ID);
checkAction += 1;
}
else if ((!chkSelect.Checked && this.IDs.Contains(ID)))
{
this.IDs.Remove(ID);
}
}
}
}
protected void lvCharOrgs_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem lvi = (ListViewDataItem)e.Item;
if ((lvi.ItemType == ListViewItemType.DataItem))
{
// Find the checkbox in the current row
CheckBox chkSelect = (CheckBox)lvi.FindControl("chkSelect");
// Make sure we're referencing the correct control
if ((chkSelect) != null)
{
// If the ID exists in our list then check the checkbox
int ID = Convert.ToInt32(lvCharOrgs.DataKeys[lvi.DisplayIndex].Value);
chkSelect.Checked = this.IDs.Contains(ID);
}
}
if (Profile.proUserType == "basic")
{//basic account so no choice of charity
((CheckBox)e.Item.FindControl("chkSelect")).Checked = true;
((CheckBox)e.Item.FindControl("chkSelect")).Enabled = false;
}
}
Now I have a CustomValidator control which checks to ensure between 3 & 5 records have been selected. If this is true the page is valid and processed. If it is not the case (eg less than 3 or more than 5) the page is Invalid and the CustomValidator throws up a label to notify of this fact.
I use the following code on the serverside to implement this.
protected void lvCharOrgsValidator_ServerValidate(object source, ServerValidateEventArgs args)
{// Custom validate lvCharOrgs
//update selected rows
AddRowstoIDList();
//get count and verify is correct range
int counter = this.IDs.Count;
args.IsValid = (counter >=3 && counter <=5) ? true : false;
}
This all works fine except I need to implement a 'ValidatorCallout' extender from the AJAX Control Toolkit. However this doesn't work with CustomValidators unless they implement clientSide validation. Thus I need to convert the 'lvCharOrgsValidator_ServerValidate' method to a clientside JavaScript function.
Hope this clarifies my requirements.
What does the following do?
AddRowstoIDList();
Something like the following is a start, but will need more details on the above method to provide a working answer
function validateRowCount(sender, args) {
//update selected rows
AddRowstoIDList(); // Does this add row indexes to an array?
//get count and verify is correct range
var counter = IDList.length;
args.IsValid = (counter >=3 && counter <=5);
}
It might be worth looking at Script# for a longer term solution, if you're planning on doing a lot of conversion.
EDIT:
now I can see the AddRowstoIDList() method, to do this on the client-side will be slightly different. Firstly, get a reference to the DOM element that is rendered for lvCharOrgs. Probably the most straightforward way to do this in vanilla JavaScript would be to put the JavaScript function in the page and use the server tags to get the rendered ClientID.
function validateRowCount(sender, args) {
var lvCharOrgs = document.getElementById('<%= lvCharOrgs.ClientID %>');
var checkboxes = lvCharOrgs.getElementsByTagName('input');
var len = checkboxes.length;
var counter = 0;
for(var i =0; i < len; i++) {
if (checkboxes[i].type == "checkbox" && checkboxes[i].checked) counter++;
}
args.IsValid = (counter >=3 && counter <=5);
}
Should work something like this - Working Demo
add /edit to the URL if you want to see the code
If you change int to var, your code is valid JavaScript. (But since it depends on other functions and objects you need to convert those as well.) Also if you're using the c# 3.5 compiler it will stay valid C# even with var instead of int.
Probably not what you want, but there is jsc:
"Web 2.0 hype? Want build better web
sites, but javascript is too hard? No
real IDE? Maybe you should try jsc.
The web app can be built within Visual
Studio 2008 or any other c# compliant
IDE, and then the application
magically appears. You should think of
it as a smart client. Precompile your
c# to javascript with jsc! As an
option instead of using IIS and
asp.net, you could get away by using
apache, with mysql and php."
Have a look at this article. It applies to asp.net mvc, but it also covers some basics and you might be able to do something similar for asp.net. In particular, you might find the jquery remote validation attributes shown in the article useful for what you intend to do.
SharpKit converts C# to client side javascript.
https://sharpkit.github.io/
Well, you can always include your own javascript with custom validators. Here is a link to an article that introduces adding javascript to a validator. You just have to write your own javascript, really.
I heard about a cross-compiler from c# (or was it IL?) to JavaScript but unfortunatly do not remember the name anymore, but a google-search turned up stuff like this: http://jsc.sourceforge.net/