TextToSplit does not exist in current context - c#

Am giving to 2 variables the data type as string and integer.
However C# is saying that they don't exist.
Have tried something as object TexttoSplit { get; private set; } but still doesn't run correctly.
Any help would be much appreciated!
private static List<string> SplitTextByLengthEngine(string Texttosplit, int MaxLineLength)
{
List<string> RetVal = new List<string>();
MaxLineLength = Math.Min(MaxLineLength, TexttoSplit.Length);
int LastIndex = TexttoSplit.Substring(0, Math.Min((MaxLineLength + 1), TextToSplit.Length)).LastIndexOf(" ");
if (((TextToSplit.Length <= MaxLineLength)
|| (LastIndex == -1)))
{
RetVal.Add(TexttoSplit.Substring(0, MaxLineLength));
string RemainingText = TexttoSplit.SubString(MaxLineLength, (TextToSplit.Length - MaxLineLength)).Trim();
}
if ((RemainingText.Length > 0))
{
RetVal.AddRange(SplitTextByLengthEngine(RemainingText, MaxLineLength));
}
else
{
// Track backwards to find previous non-space character
int Index = (LastIndex - 1);
while (((Index >= 0)
&& (TextToSplit.SubString(Index, 1) == " ")))
{
Index--;
}
if ((Index >= 0))
{
RetVal.Add(TextToSplit.SubString(0, (Index + 1)));
string RemainingText = TexttoSplit.SubString((Index + 1), (TextToSplit.Length
- (Index + 1))).Trim();
}
if ((RemainingText.Length > 0))
{
RetVal.AddRange(SplitTextByLengthEngine(RemainingText, MaxLineLength));
}
return RetVal;
}
}

The method argument is called Texttosplit
In the method body you refer to TextToSplit
Note the difference in upper/lowercase

Related

How to check if all strings in array are the same length c#

for instance,
string[] text=new string[] {"string1", "string2", "string3"};
how do i know if all string's length in this array are equal?
Another solution:
bool allSameLength = !text.Any(t => t.Length != text[0].Length));
Here is a solution without using for(each) as requested:
string[] text = new string[] {"dsasaffasfasfafsa", "siuuuuu", "ewqewqeqeqewqeq"};
int index = 0, firstLength = -1;
bool allSameLength = true;
while(index < text.Length)
{
int length = (text[index] + '\0').IndexOf('\0');
firstLength = (index == 0) ? length : firstLength;
allSameLength &= (length != firstLength) ;
index += 1;
}
return allSameLength;
Here is another solution that does not use for(each) and does not try to cheat by using a different type of loop (like while):
string[] text = new string[] {"dsasaffasfasfafsa", "siuuuuu", "ewqewqeqeqewqeq"};
List<string> texts = new List<string>();
texts.Add(null);
texts.AddRange(text);
texts.Add(null);
bool CheckSameLength(int index)
=> (texts[index + 1] == null) ? true
: texts[index] == null ? CheckSameLength(1)
: texts[index].Length == texts[index + 1].Length ? CheckSameLength(index + 1)
: false;
return CheckSameLength(texts, 0);
Most ridiculous use of recursion?
public class Program {
public static void Main() {
string[] text = new string[] {"dsasaffasfasfafsa", "siuuuuu", "ewqewqeqeqewqeq"};
Console.WriteLine(AllLengthsEqual(text));
}
public static bool AllLengthsEqual(string[] strArr) {
return strArr == null ? true : (strArr.Length < 2 ? true : AllLengthsEqual(strArr, 0));
}
private static bool AllLengthsEqual(string[] strArr, int index) {
return AllLengthsEqual(strArr, index + 1, strArr[index] != null ? strArr[index].Length : -1);
}
private static bool AllLengthsEqual(string[] strArr, int index, int prevLength) {
if (index < strArr.Length) {
int thisLength = strArr[index] != null ? strArr[index].Length : -1;
return (thisLength == prevLength) && AllLengthsEqual(strArr, index + 1, thisLength);
}
else
return true;
}
}

Find maximum depth/level of a nested collection

I want to create a Property which can find the depth of the nested tree structure. The below static finds out the depth/level by recursion. But is it possible to make this function as a property in the same class instead of a static method?
public static int GetDepth(MenuGroup contextMenuItems)
{
if (contextMenuItems == null || contextMenuItems.Items.Count == 0)
return 0;
var subMenu = contextMenuItems.Items.Select(b => b as MenuGroup);
if (!subMenu.Any())
return 1;
var subLevel = subMenu.Cast<MenuGroup>().Select(GetDepth);
return !subLevel.Any() ? 1 : subLevel.Max() + 1;
}
Some more info on the code:
MenuGroup and MenuItem are derived from MenuBase
MenuGroup has children nodes with ObservableCollection<MenuBase> Items as Child Elements
MenuItem is a leave node without any child.
Well you could easily turn it into an instance property, yes:
public int Depth
{
get
{
if (Items.Count == 0)
return 0;
var subMenu = Items.Select(b => b as MenuGroup);
if (!subMenu.Any())
return 1;
var subLevel = subMenu.Cast<MenuGroup>().Select(x = > x.Depth);
return !subLevel.Any() ? 1 : subLevel.Max() + 1;
}
}
That won't quite work yet due to the handling of non-MenuGroup items, but it can easily be fixed, using OfType instead of the Select and then Cast:
public int Depth
{
get
{
// Completely empty menu (not even any straight items). 0 depth.
if (Items.Count == 0)
{
return 0;
}
// We've either got items (which would give us a depth of 1) or
// items and groups, so find the maximum depth of any subgroups,
// and add 1.
return Items.OfType<MenuGroup>()
.Select(x => x.Depth)
.DefaultIfEmpty() // 0 if we have no subgroups
.Max() + 1;
}
}
public string GenerateMenu()
{
StringBuilder sb = new StringBuilder();
sb.Append("<nav id=\"nvMenu\" class=\"main-nav\"><ul>");
sb.Append(PrepareMenuUL(AppConfig._AppConfigInstance.Navigation.FirstOrDefault().NavigationClass));
sb.Append("</ul></nav>");
return sb.ToString();
}
private string PrepareMenuUL(List<Navigation> navigation)
{
StringBuilder sb = new StringBuilder();
if (Liflag == 1)
{
sb.Append("</li>");
Liflag = 0;
}
foreach (var item in navigation)
{
var subMenu = item.NavigationClass.Select(b => b as Navigation);
if (subMenu.Any())
{
sb.Append("<li class=\"dropdown\">");
if (subMenu.Any() && item.Url == "#")
sb.Append(string.Format("{1}<i class=\"icon-arrow\"></i>", BaseUrl + item.Url, item.Name));
else if (subMenu.Any() && item.Url != "#" && item.Url != null)
sb.Append(string.Format("{1}<i class=\"icon-rightarrow\"></i>", BaseUrl + item.Url, item.Name));
}
else
{
sb.Append("<li>");
sb.Append(string.Format("{1}", BaseUrl + item.Url, item.Name));
}
if (subMenu.Any())
sb.Append("<ul class=\"wd190\">");
if (item.NavigationClass.Count > 0)
{
Liflag = 1;
sb.Append(PrepareMenuUL(item.NavigationClass));
}
sb.Append("</li>");
if (subMenu.Any())
sb.Append("</ul>");
}
return sb.ToString();
}

Mixed managed C++ method does not always return the same result to the calling C# code

A C++ method returns the correct value when I use a conditional breakpoint, but an incorrect value without a breakpoint.
C# method which calls C++:
bool SetProperty(Element element, Node referencePoint, List<Materializer> materializers, List<ulong> properties)
{
// Loop over STLs
for (int i = 0; i < materializers.Count; i++)
{
Materializer materializer = materializers[i];
if (materializer.IsPointInside(referencePoint.X, referencePoint.Y, referencePoint.Z, pentalTreeDatasets[i].top))
{
element.PropertyId = properties[i];
return true;
};
}
return false;
}
C++ methods in the header file:
int CountIntersects(double x, double y, double z, PentalTreeNode ^root)
{
Math3d::M3d rayPoints[2], intersectionPoint;
rayPoints[0].set(x,y,z);
rayPoints[1].set(x,y,1.0e6);
if(!root)
return 0;
else
{
int special = CountIntersects(x,y,z,root->special);
if (x <= root->xMax && x >= root->xMin && y <= root->yMax && y >= root->yMin)
{
if( _stlMesh->IsRayIntersectsPoly(root->index, rayPoints, intersectionPoint))
{
return (1 + special);
}
else
return special;
}
else
{
if (y>root->yMax)
{
return (CountIntersects(x,y,z,root->top)+special);
}
else if(y<root->yMin)
{
return (CountIntersects(x,y,z,root->bottom)+special);
}
else if(x<root->xMin)
{
return (CountIntersects(x,y,z,root->left)+special);
}
else if(x>root->xMax)
{
return (CountIntersects(x,y,z,root->right)+special);
}
else
return special;
}
}
}
bool IsPointInside(double x, double y, double z, PentalTreeNode ^root)
{
int intersectionCount = 0;
Math3d::M3d rayPoints[2], intersectionPoint;
rayPoints[0].set(x,y,z);
rayPoints[1].set(x,y,1.0e6);
if(_box->IsContainingPoint(x,y,z))
{
intersectionCount=CountIntersects(x,y,z,root);
return (intersectionCount%2!=0);
}
}
C++ methods in other header files:
bool IsRayIntersectsPoly(int nPolygonIndex, Math3d::M3d RayPoints[2], CVector3D& IntersectionPoint)
{
CMeshPolygonBase& Poly = m_PolygonArray[nPolygonIndex];
CArrayResultI Result;
int* pPolygonPoints = GetPolygonPoints(Poly, Result);
Math3d::MPlane TrianglePlane;
double Atmp[3], A;
CVector3D* pPoints[3];
pPoints[0] = &m_PointArray[*pPolygonPoints].m_Position;
for(int i = 1; i < Result.GetSize() - 1; i++)
{
pPoints[1] = &m_PointArray[*(pPolygonPoints+i)].m_Position;
pPoints[2] = &m_PointArray[*(pPolygonPoints+i+1)].m_Position;
TrianglePlane.Init(*pPoints[0], *pPoints[1], *pPoints[2]);
TrianglePlane.IntersectLine(RayPoints[0], RayPoints[1], IntersectionPoint);
A = GetTriangleArea(*pPoints[0], *pPoints[1], *pPoints[2]);
for(int j = 0; j < 3; j++)
{
Atmp[j] = GetTriangleArea(*pPoints[j], *pPoints[(j+1)%3], IntersectionPoint);
}
if( fabs(A - Atmp[0] - Atmp[1] - Atmp[2]) < 1.0e-5 ) return true;
}
return false;
};
double GetTriangleArea(CVector3D& T1, CVector3D& T2, CVector3D& T3)
{
double a, b, c, s;
a = (T1 - T2).length();
b = (T2 - T3).length();
c = (T3 - T1).length();
s = 0.5 * (a + b + c);
return( sqrt(s * (s - a)* (s - b)* (s - c)) );
}
When I start the program which calls SetProperty() within the for-loop, the results for some iterator values are wrong. When I set conditional breakpoints for critical iterator values in the for-loop and step over it, then the result is OK for that item. What may be the problem?
This is method in which I post breakpoint. For example, for critical element.Id==2393.
private void StartButton_Click(object sender, EventArgs e)
{
DateTime startTime = DateTime.Now;
List<Materializer> materializers = new List<Materializer>();
List<ulong> properties = new List<ulong>();
// Load STLs
for (int i = 0; (int)i < (this.dataGridView.RowCount - 1); i++)
{
if (dataGridView.Rows[i].Cells[1].Value != null && (string)dataGridView.Rows[i].Cells[1].Value != "")
{
Materializer materializer = new Materializer();
materializer.LoadSTLMesh(dataGridView.Rows[i].Cells[0].Value.ToString());
materializers.Add(materializer);
properties.Add((ulong)dataGridView.Rows[i].Cells[1].Tag);
}
}
CreatePentalTrees(materializers);
int processedElementCount = 0;
int changedElementCount = 0;
// Loop over elements
foreach (Element element in model.ElementsList.Values)
if ((element.Topology == 7 || element.Topology == 8) && !lockedProperties.ContainsKey(element.PropertyId)) // 3D elements only
{
Node center = this.CenterPoint(element, model.NodesList);
if (element.Id == 2393)
{
//if breakpoints thats ok, else not ok
Console.WriteLine(element.Id);
Console.WriteLine(element.PropertyId);
}
if (SetProperty(element, center, materializers, properties)) // Check for center point
{
//changedElements.Add(element.Id, true);
changedElementCount++;
}
else
{
// Check for all nodes if center point does not belong to any STL
int[] nodeOrder;
switch (element.Topology)
{
case 7:
nodeOrder = wedgeNodeOrder;
break;
case 8:
nodeOrder = brickNodeOrder;
break;
default:
throw new Exception("Unknown topology " + element.Topology.ToString());
}
for (int i = 0; i < nodeOrder.Length; i++)
{
Node node = model.NodesList[element.NodeIds[nodeOrder[i]]];
if (SetProperty(element, node, materializers, properties))
{
//changedElements.Add(element.Id, true);
changedElementCount++;
break;
}
}
}
if (++processedElementCount % 100 == 0)
{
labelTime.Text = "Changed/processed elements: " + changedElementCount.ToString() + "/" + processedElementCount.ToString();
labelTime.Refresh();
Application.DoEvents();
}
}
DateTime endTime = DateTime.Now;
labelTime.Text = "Total time: " + (endTime - startTime).TotalSeconds.ToString() + " s";
MessageBox.Show("Completed.");
SaveFileDialog saveFileDlg = new SaveFileDialog();
saveFileDlg.Title = "Save FEMAP neutral file";
saveFileDlg.Filter = "(*.neu)|*.neu";
if (saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FemapNeutral.ExportNeu(saveFileDlg.FileName, model);
}
}
You seem to be calling a lot of methods you haven't listed, and/or the wall of code made me get lost. Adding that code won't help: reducing your problem to a simpler one that demonstrates the problem might.
However, the most likely cause of your problem, if you have unmanaged code reading managed data, is that you failed to marshal or pin the data prior to using the managed code.
Unpinned data can be moved around by the garbage collector in unexpected ways.

Why isn't my undo/redo code functioning as required?

I need my undo/redo code to function like the undo/redo features found in Microsoft Notepad, Microsoft Word etc. (I am creating a Word Processor).
Currently, my Undo and Redo code is working to an extent. But there are a number of issues with the undo/redo functions in my application. These are as follows:
If I type a sentence, such as "Hello, my name is Toby.", and then I undo the text (leaving Hello still on the document), I can only redo up to "is".
If I undo all the text in the document, I cannot redo any of the text. So if I again type "Hello, my name is Toby.", and then I undo that line, I cannot then redo any of the text.
I was hoping somebody could help me rectify these issues.
As of now, the code used by both Undo and redo is as follows:
public struct UndoSection
{
public string Undo;
public int Index;
public UndoSection(int index, string undo)
{
Index = index;
Undo = undo;
}
private void richTextBoxPrintCtrl1_TextChanged(object sender, EventArgs e)
{
{
OldLength = richTextBoxPrintCtrl1.Text.Length; System.Text.RegularExpressions.MatchCollection wordColl = System.Text.RegularExpressions.Regex.Matches(richTextBoxPrintCtrl1.Text, "'?([a-zA-z'-]+)'?");
counter.Text = wordColl.Count.ToString();
}
try
{
if (IsRedoUndo == false && (richTextBoxPrintCtrl1.Text.Substring(richTextBoxPrintCtrl1.Text.Length - 1, 1) == " " || richTextBoxPrintCtrl1.Text.Substring(richTextBoxPrintCtrl1.Text.Length - 1, 1) == ","))
{
StackCount = StackCount + 1;
RTBRedoUndo[StackCount] = richTextBoxPrintCtrl1.Text;
}
}
catch { }
}
public string[] RTBRedoUndo;
public int StackCount = 0;
public int OldLength = 0;
public int ChangeToSave = 5;
public bool IsRedoUndo = false;
public void RTBTextChanged()
{
if (richTextBoxPrintCtrl1.TextLength - OldLength >= ChangeToSave | richTextBoxPrintCtrl1.TextLength - OldLength <= ChangeToSave)
{
StackCount += 1;
RTBRedoUndo[StackCount] = richTextBoxPrintCtrl1.Text;
}
The undo code:
public void UndoCode()
{
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount - 1] != null)
{
StackCount = StackCount - 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
}
The redo code:
public void RedoCode()
{
if (IsRedoUndo == false && richTextBoxPrintCtrl1.Text.Substring(richTextBoxPrintCtrl1.Text.Length - 1, 1) == " ")
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount + 1] != null)
{
StackCount = StackCount + 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
I'm not too sure what to try, so I was hoping that somebody with more of a knowledge of programming could help me, as I'm still a novice and in my learning stages.
Thanks :o)
You seem to be setting your stack count back to zero once you Undo. Thats why when u Redo it goes only up to the amount allowed -1
try
Undo Code
public void UndoCode()
{
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount] != null)
{
StackCount = StackCount - 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount+1];
}
}

convert Javascript function to c#

I want to convert following javascript function to c#
can anyone help?
function parseCoordinate(coordinate,type,format,spaced) {
coordinate = coordinate.toString();
coordinate = coordinate.replace(/(^\s+|\s+$)/g,''); // remove white space
var neg = 0; if (coordinate.match(/(^-|[WS])/i)) { neg = 1; }
if (coordinate.match(/[EW]/i) && !type) { type = 'lon'; }
if (coordinate.match(/[NS]/i) && !type) { type = 'lat'; }
coordinate = coordinate.replace(/[NESW\-]/gi,' ');
if (!coordinate.match(/[0-9]/i)) {
return '';
}
parts = coordinate.match(/([0-9\.\-]+)[^0-9\.]*([0-9\.]+)?[^0-9\.]*([0-9\.]+)?/);
if (!parts || parts[1] == null) {
return '';
} else {
n = parseFloat(parts[1]);
if (parts[2]) { n = n + parseFloat(parts[2])/60; }
if (parts[3]) { n = n + parseFloat(parts[3])/3600; }
if (neg && n >= 0) { n = 0 - n; }
if (format == 'dmm') {
if (spaced) {
n = Degrees_to_DMM(n,type,' ');
} else {
n = Degrees_to_DMM(n,type);
}
} else if (format == 'dms') {
if (spaced) {
n = Degrees_to_DMS(n,type,' ');
} else {
n = Degrees_to_DMS(n,type,'');
}
} else {
n = Math.round(10000000 * n) / 10000000;
if (n == Math.floor(n)) { n = n + '.0'; }
}
return comma2point(n);
}
}
Check out Regex on MSDN or have a quick look on google for Regex C#
if (coordinate.match(/(^-|[WS])/i)) { neg = 1; }
would become:
using System.Text.RegularExpressions;
Regex myRegex = new Regex("/(^-|[WS])/i)");
if (coordinate.IsMatch(myRegex))
{
neg=1;
}
If it will always be like your above example 'N27 53.4891' then you could store it as a string. If the above latitude is in 2 parts ('N27' and 53.4891) and you need to access them seperately then you could have a custom Coordinate class, e.g.
public class coordinate
{
public string otherPart {get; set;} // N27
public float coordPart {get; set;} // 53.4891
}
You can then override the .toString() method to get 'N27 53.4891'.
Regex myPattern =new Regex("/(^-|[WS])/i)");
if(myPattern.isMatch(coordinate))
{ neg = 1; }
see if this works

Categories

Resources