C# / Windows Forms: error cs1519 - c#

I'm working on a graphics transformation program, setting up a listbox to read in the names of files in a directory. The code is based off an example from my instructor, so I thought it would work fine, but it seems to create errors everywhere. I googled "error CS1519: Invalid token ‘,’ in class, struct, or interface member declaration", but what I found looked unapplicable. Here it is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Transformer
{
public partial class Transformer : Form
{
/* Initialize parameters */
private bool drawAxes = true;
private bool drawGrid = true;
private List<ObjectSettings> dispObjects = new List<ObjectSettings>();
/* Initialize form */
public Transformer()
{
InitializeComponent();
}
private void Transformer_Load(object sender, EventArgs e)
{
}
/* Populate available objects listbox */
private int selFile = 0;
private string currentDir = Directory.GetCurrentDirectory();
// errors start around here
private string[] fileEntries = Directory.GetFiles(currentDir+#"\Objects");
foreach (string s in fileEntries) {
int start = s.LastIndexOf(#"\");
int end = s.LastIndexOf(#".");
availObjectsListBox.Items.Add(s.Substring(start + 1, end - start - 1));
} // end foreach
}
}

That's because you need to put:
foreach (string s in fileEntries) {
int start = s.LastIndexOf(#"\");
int end = s.LastIndexOf(#".");
availObjectsListBox.Items.Add(s.Substring(start + 1, end - start - 1));
}
in a function.
Maybe you can do something like:
private void Transformer_Load(object sender, EventArgs e)
{
int selFile = 0;
string currentDir = Directory.GetCurrentDirectory();
string[] fileEntries = Directory.GetFiles(currentDir+#"\Objects");
foreach (string s in fileEntries) {
int start = s.LastIndexOf(#"\");
int end = s.LastIndexOf(#".");
availObjectsListBox.Items.Add(s.Substring(start + 1, end - start - 1));
} // end foreach
}
Note that you put the foreach loop inside the Transformer_Load function; of course, you can put it in any other function. And note that there is no modifier (private) in front of selFile, currentDir and fileEntries variable.

Look where the errors start!
You cant have statements in the class body. It needs to be in a method/property/constructor.

Related

How do make the code display the information?

I'm trying to debug the C# code but can't find the logic error of why it's not displaying the data and no error message.
To begin with, the code was in large chunks so I then tried splitting the code into smaller methods but still unable to find the issue of where I'm going wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Drivers_license_exam
{
public partial class Form1 : Form
{
private string[] studentAnsArray = new string[20];
private string[] correctAnsArray = { "B", "D", "A", "A", "C", "A","B", "A", "C", "D", "B","C",
"D", "A", "D", "C","C", "B", "D", "A" };
public Form1()
{
InitializeComponent();
}
private void GetFile(out string fileName)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
fileName = openFile.FileName;
}
else
{
fileName = "";
}
}
private void GetAndReadFile(string fileName)
{
string results;
StreamReader inputFile = File.OpenText(fileName);
while (!inputFile.EndOfStream)
{
results = inputFile.ReadLine();
studentAns.Items.Add(results);
//studentAnsArray[index] = inputFile.ReadLine();
//correctAns.Items.Add(studentAnsArray);
}
foreach (string answers in correctAnsArray)
{
correctAns.Items.Add(answers);
}
inputFile.Close();
}
private int TotCorrect()
{
int correct = 0;
for (int index = 0; index < correctAnsArray.Length; index++)
{
if (studentAnsArray[index]== correctAnsArray[index])
{
correctTxt.Text = index.ToString();
correct++;
}
}
return correct;
}
private int TotIncorrect()
{
int incorrect = 0, questNum = 1;
for (int index = 0; index < correctAnsArray.Length; index++)
{
if (studentAnsArray[index] == correctAnsArray[index])
{
incorrectAns.Items.Add("Question: " + questNum);
incorrectAns.Items.Add("Incorrect");
incorrect++;
}
}
return incorrect;
}
private bool PassedTest()
{
bool pass = false;
if (TotCorrect() >= 15)
{
passFailedTxt.Text = "Passed";
}
if (TotIncorrect() < 15)
{
passFailedTxt.Text = "Failed";
}
return pass;
}
private void displayRes_Click(object sender, EventArgs e)
{
string studentAns;
GetFile(out studentAns);
GetAndReadFile(studentAns);
TotCorrect();
TotIncorrect();
PassedTest();
}
private void exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Clear_Click(object sender, EventArgs e)
{
}
}
}
What I expected the code to do is output the following:
display the incorrect results
display pass or fail in a text box
display the total of correct and incorrect answers in a text box
The output that I'm getting from this code is:
- doesn't display the incorrect answers in the list box
- displays fail although the answers from the text and the array are correct
- doesn't display the total of correct and incorrect answers

C# Hashset<string> Contains incorrectly returns false

I am trying to compare a Hashset of strings populated from a database against a string property from an object. I know that it exists in the hashset, but it is always returning false.
Oddly enough, I wrote a test program that behaves how I would expect. See Below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string test = "A";
HashSet<String>[] array = new HashSet<string>[1];
array[0] = new HashSet<string>();
Boolean isA = true;
Boolean isB = false;
array[0].Add("A");
if (array[0].Contains(test) && isA || isB)
if (test.Equals("A")) {
Console.WriteLine("A");
}
return;
}
}
}
On the other hand, this does not. Do I have to write a custom comparator for this? This is not a custom object, I'm just comparing strings. I know that the string is contained in the hash set.
private readonly HashSet<string>[] cars = new HashSet<string>[5];
for (int i = 0; i < cars.Length; i++)
cars[i] = new HashSet<string>();
foreach (DataRow dr in dt.Rows)
{
switch (dr[0].ToString())
{
case "1":
cars[0].Add(dr[1].ToString());
break;
}
}
bool test = cars[0].Contains("A"); //Always returns false
Try to add with it cars[0].Add(dr[1].ToString().Trim().ToUpper()) and check.

convert visio vba method into c#

Hello I would like to convert this vba method into C#. I am trying to get the IDs of a selection and print them out. In particular I am having trouble converting the GetIDs() method(a built in method within visio vba) into C#.
Public Sub getCapabilityRectIDs()
Dim vsoSelection1 As Visio.Selection
Dim selectionIDs() As Long
Set vsoSelection1 = Application.ActiveWindow.Page.CreateSelection(visSelTypeByLayer, visSelModeSkipSuper, "Capability")
Application.ActiveWindow.Selection = vsoSelection1
Call vsoSelection1.GetIDs(selectionIDs)
For i = 0 To UBound(selectionIDs)
Debug.Print selectionIDs(i)
Next i
End Sub
This is what I have so far in C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("Capability");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"............. - abc.vsdm");
ActiveDoc = VisApp.ActiveDocument;
acPage = VisApp.ActivePage;
}
public void selectShpLayer (string layerName){
Int i = 0;
long[] lngRowIDs;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeOnlySuper,layerName);
LayerSelection.GetIDs(lngRowIDs);
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write(lngRowIDs[i]);
}
}
}
Thanks in advance!
I created a visio doc and drew 3 simple shapes. I then created a layer called "cool" and added those 3 shapes to it.
I don't understand enough about the shape selection, you had visSelModeOnlySuper which may work for you, but did not work for the case I created. The default is visSelModeSkipSuper (which worked for me)
Here's the API page that describes how to use the createSelection:
https://msdn.microsoft.com/en-us/library/office/ff765565.aspx
Here is my sample code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
class Program
{
static void Main(string[] args)
{
//create the object that will do the drawing
VisioDrawer Drawer = new VisioDrawer();
Drawer.selectShpLayer("cool");
}
}
class VisioDrawer
{
public Visio.Application VisApp;
public static Visio.Page acPage;
public Visio.Selection LayerSelection;
public VisioDrawer()
{
//create the application
VisApp = new Visio.Application();
VisApp.Documents.Open(#"c:\temp\trial.vsdm");
acPage = VisApp.ActivePage;
}
public void selectShpLayer(string layerName)
{
int i = 0;
int[] lngRowIDs;
Array lngRowIDArray;
//this selects the shapes of the selected layer
LayerSelection = acPage.CreateSelection(Microsoft.Office.Interop.Visio.VisSelectionTypes.visSelTypeByLayer, Microsoft.Office.Interop.Visio.VisSelectMode.visSelModeSkipSuper, layerName);
LayerSelection.GetIDs(out lngRowIDArray);
lngRowIDs = (int[])lngRowIDArray;
for (i = 0; i < lngRowIDs.Length; i++)
{
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + "\n");
}
}
}
And it produces this output:
Object ID: 1
Object ID: 2
Object ID: 3
If you change the debug line to this:
Debug.Write("Object ID: " + lngRowIDs[i].ToString() + " -- " + acPage.Shapes.ItemFromID[i].Name + "\n");
The output gets even more useful:
Object ID: 1 -- ThePage
Object ID: 2 -- Circle
Object ID: 3 -- Rectangle

Find certain text in PDF, then return page number found on to another section NOTE: Uses Docotic.pdf

In the following code, the user will input a search string (barcodedata). That string will then be truncated to the first 5 characters, and used as the jobnumber. The jobnumber, is also the name of the pdf I will be scanning for the barcodedata.
What I would like, is for the 'Find it' button to execute the below code, then return the value found to startpagedata.
I can't tell if the program just isn't actually scanning the PDF for the search string, or if the value simply isn't returning to the program.
using BitMiracle.Docotic.Pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using Acrobat;
namespace BarCodeReader
{
public partial class Form1 : Form
{
public string stringsToFind;
public string pathtofile;
public Form1()
{
InitializeComponent();
}
private void barcodedata_TextChanged(object sender, EventArgs e)
{
stringsToFind=barcodedata.Text;
pathtofile = "C:\\" + StringTool.Truncate(barcodedata.Text, 5) + ".pdf";
jobnumberdata.Text = StringTool.Truncate(barcodedata.Text, 5);
}
private void label4_Click(object sender, EventArgs e)
{
}
private void jobnumberdata_TextChanged(object sender, EventArgs e)
{
jobnumberdata.Text = jobnumberdata.Text.TrimStart('0');
Console.WriteLine(jobnumberdata.Text);
}
private void startpagedata_TextChanged(object sender, EventArgs e)
{
Console.WriteLine(startpagedata.Text);
}
private void piecesdata_TextChanged(object sender, EventArgs e)
{
}
private void FindIt_Click(object sender, EventArgs e)
{
PdfDocument pdf = new PdfDocument(pathtofile);
for (int i = 0; i < pdf.Pages.Count; i++)
{
string pageText = pdf.Pages[i].GetText();
int count = 0;
int lastStartIndex = pageText.IndexOf(stringsToFind, 0, StringComparison.CurrentCultureIgnoreCase);
while (lastStartIndex != -1)
{
count++;
lastStartIndex = pageText.IndexOf(stringsToFind, lastStartIndex + 1, StringComparison.CurrentCultureIgnoreCase);
}
if (count != 0)
startpagedata.Text = Convert.ToString(lastStartIndex);
}
}
}
public static class StringTool
{
/// <summary>
/// Get a substring of the first N characters.
/// </summary>
public static string Truncate(string source, int length)
{
if (source.Length > length)
{
source = source.Substring(0, length);
}
return source;
}
/// <summary>
/// Get a substring of the first N characters. [Slow]
/// </summary>
public static string Truncate2(string source, int length)
{
return source.Substring(0, Math.Min(length, source.Length));
}
}
}
What is your problem with this code? If FindIt_Click is not executed on click then probably you don't associate it with the "Find it" button.
The code in FindIt_Click looks quite correct except several things:
It may not do what you expect. It returns the last index in the text of the last page where the search string was found. But may be you expect the index of the last page where the search string was found?
You may use pageText.LastIndexOf method to quickly find lastStartIndex.
Don't forget to Dispose PdfDocument instance. E.g. use using keyword:
using (PdfDocument pdf = new PdfDocument(pathtofile))
{
...
}
In order to use Docotic.pdf you can use Acrobat.dll to find the current page number. First of all open the pdf file and search the string using
Acroavdoc.open("Filepath","Temperory title")
and
Acroavdoc.FindText("String").
If the string found in this pdf file then the cursor moved into the particular page and the searched string will be highlighted. Now we use Acroavpageview.GetPageNum() to get the current page number.
Dim AcroXAVDoc As CAcroAVDoc
Dim Acroavpage As AcroAVPageView
Dim AcroXApp As CAcroApp
AcroXAVDoc = CType(CreateObject("AcroExch.AVDoc"), Acrobat.CAcroAVDoc)
AcroXApp = CType(CreateObject("AcroExch.App"), Acrobat.CAcroApp)
AcroXAVDoc.Open("File path", "Original document")
AcroXAVDoc.FindText("String is to searched", True, True, False)
Acroavpage = AcroXAVDoc.GetAVPageView()
Dim x As Integer = Acroavpage.GetPageNum
MsgBox("the string found in page number" & x)

How do i loop through two Lists to compare items in both Lists?

I have this code:
private void removeDuplicates(List<string> currentSites, List<string> visitedSites)
{
for (int i = 0; i < currentSites.Count; i++)
{
for (int x = 0; x < visitedSites.Count; x++)
{
}
}
}
Im getting two Lists and i need first to compare each item in one List to the items in the other List to loop over all the items in the other List and compare. If one of the items exist in the other List mark it as NULL.
I need to check that visitedSites are in the currentSites to take one item move over all the Lists to check if exit if it is to mark as null.
In any case i need to use two loop's one ine the other one.
When i find its null to mark it null and after it make break;
Then i need to add another loop FOR to move over the List currentSites if im not wrong and remove all the marked NULL items.
The idea is to compare the Lists by mark the duplicated items as null then to remove all the null's.
This is the code from the beginning:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Net;
using System.Web;
namespace GatherLinks
{
public partial class Form1 : Form
{
List<string> currentCrawlingSite;
List<string> sitesToCrawl;
int actual_sites;
BackgroundWorker worker;
int sites = 0;
int y = 0;
string guys = "http://www.google.com";
public Form1()
{
InitializeComponent();
currentCrawlingSite = new List<string>();
sitesToCrawl = new List<string>();
actual_sites = 0;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private List<string> getLinks(HtmlAgilityPack.HtmlDocument document)
{
List<string> mainLinks = new List<string>();
var linkNodes = document.DocumentNode.SelectNodes("//a[#href]");
if (linkNodes != null)
{
foreach (HtmlNode link in linkNodes)
{
var href = link.Attributes["href"].Value;
mainLinks.Add(href);
}
}
return mainLinks;
}
private List<string> webCrawler(string url, int levels , DoWorkEventArgs eve)
{
HtmlAgilityPack.HtmlDocument doc;
HtmlWeb hw = new HtmlWeb();
List<string> webSites;// = new List<string>();
List<string> csFiles = new List<string>();
csFiles.Add("temp string to know that something is happening in level = " + levels.ToString());
csFiles.Add("current site name in this level is : " + url);
try
{
doc = hw.Load(url);
currentCrawlingSite.Add(url);
webSites = getLinks(doc);
removeDuplicates(currentCrawlingSite, webSites);
removeDuplicates(currentCrawlingSite, sitesToCrawl);
sitesToCrawl = webSites;
if (levels == 0)
{
return csFiles;
}
else
{
for (int i = 0; i < webSites.Count() && i < 20; i++) {
int mx = Math.Min(webSites.Count(), 20);
if ((worker.CancellationPending == true))
{
eve.Cancel = true;
break;
}
else
{
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true))
{
actual_sites++;
csFiles.AddRange(webCrawler(t, levels - 1,eve));
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Level Number " + levels + " " + t + Environment.NewLine, Color.Red); }));
worker.ReportProgress(Math.Min((int)((double)i / mx * 100),100));
}
}
}
return csFiles;
}
}
catch
{
return csFiles;
}
}
So im calling the removeDuplicated function twice need to do in the removeDuplicated the things i wrote above then im not sure if to do sitesToCrawl = webSites; or ot add somehow the links in webSites to the sitesToCrawl. The idea is when i loop over the webSites that there will be no duplicated items when adding to the csFiles List.
Not sure if I understand your problem:
IEnumerable<string> notVisitedSites = currentSites.Except(visitedSites);

Categories