C# ConsoleRead() input not saved in variable - c#

I am working with C# for the first time and I am facing a strange issue.
I am building my own class for a plugin, but copied parts of the code from an existing class. Basically it's
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
sanList = new List<string>(alternativeNames);
but somehow this doesn't work. The debug console says System.Console.ReadLine returned jogi,philipp string, but sanInput keeps null as its value.
Even stranger is the fact, that the next step works "a bit". string.Split returned {string[2]} string[], so it returns an array of [jogi, philipp], but still sanInput, alternativeNamesand sanList stay as null.
How is it possible, that the second line works if sanInput has no value and how can I fix this problem? When I work with the existing class with the same code everything works as expected.
//EDIT:
Looks like a quite complicated issue. Here is the complete method:
public override void HandleMenuResponse(string response, List<Target> targets)
{
if (response == "r")
{
Console.WriteLine("Which hosts do you want to configure? Enter numbers separated by a comma.");
var hostsInput = Console.ReadLine();
int[] hosts = null;
string[] alternativeNames = null;
List<string> sanList = null;
hosts = hostsInput.Split(',').Select(int.Parse).ToArray();
Console.Write("Generating certificates for ");
foreach (int entry in hosts)
{
Console.Write(targets[entry - 1].Host + ", ");
}
Console.Write("\n \n");
foreach (int entry in hosts)
{
int entry2 = entry - 1;
if (Program.Options.San)
{
Console.WriteLine("Enter all Alternative Names for " + targets[entry2].Host + " seperated by a comma:");
// Copied from http://stackoverflow.com/a/16638000
int BufferSize = 16384;
Stream inputStream = Console.OpenStandardInput(BufferSize);
Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, BufferSize));
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
sanList = new List<string>(alternativeNames);
targets[entry2].AlternativeNames.AddRange(sanList);
}
Auto(targets[entry - 1]);
}
}
if (response == "e")
{
string[] alternativeNames = null;
List<string> sanList = new List<string>();
if (Program.Options.San)
{
Console.WriteLine("Enter all Alternative Names seperated by a comma:");
// Copied from http://stackoverflow.com/a/16638000
int BufferSize = 16384;
Stream inputStream = Console.OpenStandardInput(BufferSize);
Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, BufferSize));
var sanInput = Console.ReadLine();
alternativeNames = sanInput.Split(',');
}
if (alternativeNames != null)
{
sanList = new List<string>(alternativeNames);
}
foreach (var entry in targets)
{
Auto(entry);
}
}
}
I know the code isn't pretty and efficient. All in all it let's the user decide if he wants to use all detected hosts (response e) or only single ones (response r). But the mentioned problem occurs only in the second if-method. If I switch them it's again the latter one. So maybe the reason lies in the main program or in this BufferSize-Stuff? I don't know.
//EDIT 2: I think I found the problem: Somehow the integer BufferSize (shortly before the Console.Read()) is set to 0, so of course without any buffer it can't read the input. So the question remains: Why?
//EDIT 3: Okay, I'm done. It looks like I can't use the same name for the variables although they are in two different if-methods. I just named them sanInput2, alternativeNames2 etc. and now everything works.

try this, all of the variables are having values(you can use var also for all the variables):
var sanInput = Console.ReadLine();
string[] alternativeNames = sanInput.Split(',');
List<string> sanList = new List<string>(alternativeNames);

The problem you mention is, that debugging code in VS do assignements in two steps. First is to execute Console.ReadLine() (therefore you see Console.Readline returned message) and AFTER that is is assigned into sanInput. Same situation is after Split. Function is called, but not assigned yet.
My recommendation: use rather the step over instead of step inside. After time, you get used to this functionality and appreciate it.

Related

Streamreader adds Column with opened File Dialog

in the following code I want to have my OpenFileDialog open in a method until a valid file is selected. This works only conditionally. For some reason it adds a column after the message is displayed. This causes correct data tables to also be read incorrectly if I have previously selected an incorrect file.
public static InputData GetCSVData()
{
InputData InputData = new InputData();
OpenFileDialog OFDReader = new OpenFileDialog();
//Filter OpenFileDialog; show only CSV-Files
OFDReader.Filter = "CSV files|*.csv;";
// check if data contains "Date/Time" .
OFDReader.FileOk += delegate (object s, CancelEventArgs ev)
{
//search for Line to start reader
int LineCounter = 0;
var readertmp = new StreamReader(OFDReader.FileName);
while (true)
{
string LineTmp = readertmp.ReadLine();
string record = "Date/Time";
if (LineTmp.Contains(record))
{ break; }
else if (readertmp.EndOfStream)
{
MessageBox.Show("Data has no DataPoints !", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
ev.Cancel = true;
{ break; }
}
LineCounter++;
}
//read InputData
var reader = new StreamReader(OFDReader.FileName);
for (int i = 0; i < LineCounter; i++)
{
reader.ReadLine();
}
// settings CSVHelper
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = ";", // Set delimiter
};
var csv = new CsvReader(reader, config);
var DataRead = new CsvDataReader(csv);
InputData.DataTable.Load(DataRead);
//check for enough columns
int ColumnCounter = 0;
ColumnCounter = InputData.DataTable.Columns.Count;
if (ColumnCounter <= 2)
{
MessageBox.Show("Data has not enough columns!", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
ev.Cancel = true;
}
};
if (OFDReader.ShowDialog() == DialogResult.OK)
{
InputData.FilePath = OFDReader.FileName;
}
return InputData;
}
}
It appears you are making this more complicated than it has to be. For starters it seems odd (at least to me) that you would bother with the FileOK delegate. I do not see what difference it would make if the user is presented with an OpenFileDialog once, twice or many times. Using a single OpenFileDialog for this just seems like a waste of effort.
If the user selects a file and it fails to meet the necessary requirements, then simply open another OpenFileDialog and let the user try again. Doing this in a single dialog is certainly possible, however, “where” else would you use this? It appears this dialog is “specific” to a “certain” type of file, why limit the dialog to the requirement we need. I would think a simple method that loops forever until the user selects a valid file or Cancels the OpenFileDialog would be an easier approach.
With that said, following your code is a little odd. The reason for your issue is that the code is reading the file into the InputData.DataTable regardless if the file FAILS having datapoints OR enough columns. Put a breakpoint on the line…
InputData.DataTable.Load(DataRead);
You will see that the DataTable is filled with the data even if the data has no “DataPoints.” After the above line of code executes the next few lines check to see if the DataTable has 2 or more columns of data. If there are not enough columns, then the code simply pops up a message box indicating this.
This appears straight forward, however, the InputData.DataTable STILL HAS THE DATA even if it was bad. Next time you call the above Load method, it will simply ADD the new table to the existing table. It will add the columns if needed and simply add the rows to the bottom of the existing DataTable. Try opening several BAD files then eventually open the good file and you will see many added columns and rows.
I will assume that you may be under the impression that when you call…
ev.Cancel = true;
That the code stops right there and goes back to the first line in the delegate…
int LineCounter = 0;
… this would not be true. The code continues after ev.Cancel = true; is executed.
This can be seen by the fact that you are getting extra columns and rows every time a BAD file is attempted to be opened. A simple solution is to simply create a “new” InputData object just before you call the load method. Something like…
InputData = new InputData();
InputData.DataTable.Load(DataRead);
This will fix the extra columns issue, however, IF the user selects a BAD file and the error message pops up and the user clicks the OK button to go back to the open file dialog… THEN… IF the user then clicks the open file dialogs “Cancel” button, the BAD file will still be displayed in the grid. I am confident you may not want this behavior.
Without going into detail about some of the other strange aspects of the posted code. I proffer one other possible simpler solution as described in the beginning. Granted, the code below uses multiple OpenFileDialogs, however the user still cannot escape until they pick a valid file or cancel the dialog.
Much of the code below is taken from the existing posted code however, it is structured differently. Initially some variables are created before we stat an endless loop. Specifically, the CsvConfiguration variable config has some added properties set that ignore some code crashing problems when reading the file. I am confident you will want to set up the CsvReader to handle these problems the way you want them to be handled.
Once inside the endless while loop, the code creates a new InputData object, initializes a new OpenFileDialog and sets its properties. Then the code displays the OpenFileDialog and when the dialog returns, the DialogResult result variable is set to the dialogs returned DialogResult.
If the dialog returns OK then the code checks to see if the file is an “empty” file. If the file is empty, a message box is displayed to inform the user, then we branch back up to the begging of the loop. If the dialog result is Cancel, then the code will return a “new” InputData object. The reason for the empty check is that an exception (No header record was found) will be throw on the line…
DataRead = new CsvDataReader(csv);
If the file is empty.
I am confident that there may be some CsvHelper property that I missed that would prevent this “empty” file exception. If there is some better way to check for this “empty” file or prevent the exception, I am open to suggestions.
If the file is NOT empty, we continue by opening the file and go ahead and read its data as intended using the CsvDataReader. The idea is that… IF the file reads correctly without errors and fits the requirements, then we will already have the InputData.DataTable set and all that is left to do is to set its FilePath property and return the InputData object.
Once we have the InputData.DataTable we can check the number of columns in the InputData.DataTable. If the number of columns is less than two (2), then pop up the error message box to the user and loop back to the begging of the while loop.
If the InputData.DataTable meets the two (2) or more columns requirement, then another check is made by looping through all the columns in the data table. If at least ONE (1) column name is “Date/Time” then we are done checking the requirements and simply set the InputData.FileName property and return the InputData object.
If none of the column names in the InputData.DataTable columns is named ”Date/Time,” then again we pop up the error message box and loop back to the begging of the while loop.
It should be noted that if the file fails the number of columns test or the column named Date/Time test… then as with your problem, the InputData.DataTable STILL HAS THE DATA. This is OK here since we will re-initialize a “new” InputData object when we loop back up to the begging of the while loop.
Lastly, you do not show the InputData Class, however it appears to have at least two (2) properties… 1) a string FilePath and 2) a DataTable named DataTable??? this looks odd and is ambiguous… I have renamed my InputData object’s DataTable property to DT. The same “ambiguity” applies to the InputData variable which I have changed to TempInputData.
Since the code may “potentially” create numerous InputData objects each time the user selects a BAD file, I have implemented the IDisposable interface in the InputData Class. This way we can use this Class in a using statement and properly dispose of the unused InputData objects the code creates. I hope I have implemented this correctly.
public class InputData : IDisposable {
public DataTable DT;
public string FilePath;
private bool isDisposed;
public InputData() {
DT = new DataTable();
FilePath = "";
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (isDisposed) {
return;
}
if (disposing) {
DT?.Dispose();
FilePath = null;
}
isDisposed = true;
}
}
private InputData GetInputDataFromSCV() {
InputData TempInputData;
OpenFileDialog OFDReader;
string initialDirectory = #"D:\Test\CSV";
DialogResult result;
CsvConfiguration config = new CsvConfiguration(CultureInfo.InvariantCulture) {
Delimiter = ";",
IgnoreBlankLines = true,
MissingFieldFound = null,
BadDataFound = null
};
CsvReader csv;
CsvDataReader DataRead;
StreamReader readertmp;
FileInfo fi;
while (true) {
using (TempInputData = new InputData()) {
using (OFDReader = new OpenFileDialog()) {
OFDReader.Filter = "CSV files|*.csv;";
OFDReader.InitialDirectory = initialDirectory;
result = OFDReader.ShowDialog();
if (result == DialogResult.OK) {
fi = new FileInfo(OFDReader.FileName);
if (fi.Length != 0) {
using (readertmp = new StreamReader(OFDReader.FileName)) {
csv = new CsvReader(readertmp, config);
DataRead = new CsvDataReader(csv);
TempInputData.DT.Load(DataRead);
if (TempInputData.DT.Columns.Count > 2) {
foreach (DataColumn column in TempInputData.DT.Columns) {
if (column.ColumnName == "Date/Time") {
TempInputData.FilePath = OFDReader.FileName;
return TempInputData;
}
}
// if we get here we know a column named "Date/Time" was NOT found
MessageBox.Show("Data has no DataPoints !", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else {
MessageBox.Show("Data has less than 2 columns?", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
else {
MessageBox.Show("File is empty!", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else {
if (result == DialogResult.Cancel) {
return new InputData();
}
}
}
}
}
}
I hope this makes sense and helps.
Im sorry for the inconvenience. Sometimes I really make it too complicated for myself. I have now solved it as follows:
if (result == DialogResult.Cancel)
{
if (inputDataHistory.Loadcount != 0)
{
TempInputData.FilePath = inputDataHistory.FilePathCache;
TempInputData.LineCounter = inputDataHistory.LinecounterCache;
var reader = new StreamReader(TempInputData.FilePath);
for (int i = 0; i < TempInputData.LineCounter; i++)
{
reader.ReadLine();
}
csv = new CsvReader(reader, config);
DataRead = new CsvDataReader(csv);
TempInputData.DT.Load(DataRead);
TempInputData.IsDisposed = true;
return TempInputData;
}
else
{
return new InputData();
}
I don't know if it is the most efficient solution but I read the key variables into another class before. These are used when canceling to re-read the file before.

How to complete aspx connection string from text file

I must use a text file "db.txt" which inherits the names of the Server and Database to make my connection string complete.
db.txt looks like this:
<Anfang>
SERVER==dbServer\SQLEXPRESS
DATABASE==studentweb
<Ende>
The connection string:
string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString;
Unfortunatly we are only allowed to use Classic ASPX.net (C# 2.0) and not the web.config.
I've searched a lot, but found nothing close to help me.
Somebody got an Idea how to make it work?
Here is something to get you going.
In a nutshell, I put the DBInfo file through a method that reads the file line by line. When I see the line <anfang> I know the next line will be important, and when I see the line <ende> I know it's the end, so I need to grab everything in between. Hence why I came up with the booleans areWeThereYet and isItDoneYet which I use to start and stop gathering data from the file.
In this snippet I use a Dictionary<string, string> to store and return the values but, you could use something different. At first I was going to create a custom class that would hold all the DB information but, since this is a school assignment, we'll go step by step and start by using what's already available.
using System;
using System.Collections.Generic;
namespace _41167195
{
class Program
{
static void Main(string[] args)
{
string pathToDBINfoFile = #"M:\StackOverflowQuestionsAndAnswers\41167195\41167195\sample\DBInfo.txt";//the path to the file holding the info
Dictionary<string, string> connStringValues = DoIt(pathToDBINfoFile);//Get the values from the file using a method that returns a dictionary
string serverValue = connStringValues["SERVER"];//just for you to see what the results are
string dbValue = connStringValues["DATABASE"];//just for you to see what the results are
//Now you can adjust the line below using the stuff you got from above.
//string constr = ConfigurationManager.ConnectionStrings["DRIVER={SQL Server}; SERVER=SERVER DATABASE=DB UID=;PWD=;LANGUAGE=Deutsch;Trusted_Connection=YES"].ConnectionString;
}
private static Dictionary<string, string> DoIt(string incomingDBInfoPath)
{
Dictionary<string, string> retVal = new Dictionary<string, string>();//initialize a dictionary, this will be our return value
using (System.IO.StreamReader sr = new System.IO.StreamReader(incomingDBInfoPath))
{
string currentLine = string.Empty;
bool areWeThereYet = false;
bool isItDoneYet = false;
while ((currentLine = sr.ReadLine()) != null)//while there is something to read
{
if (currentLine.ToLower() == "<anfang>")
{
areWeThereYet = true;
continue;//force the while to go into the next iteration
}
else if (currentLine.ToLower() == "<ende>")
{
isItDoneYet = true;
}
if (areWeThereYet && !isItDoneYet)
{
string[] bleh = currentLine.Split(new string[] { "==" }, StringSplitOptions.RemoveEmptyEntries);
retVal.Add(bleh[0], bleh[1]);//add the value to the dictionary
}
else if (isItDoneYet)
{
break;//we are done, get out of here
}
else
{
continue;//we don't need this line
}
}
}
return retVal;
}
}
}

When using MergeField FieldCodes in OpenXml SDK in C# why do field codes disappear or fragment?

I have been working successfully with the C# OpenXml SDK (Unofficial Microsoft Package 2.5 from NuGet) for some time now, but have recently noticed that the following line of code returns different results depending on what mood Microsoft Word appears to be in when the file gets saved:
var fields = document.Descendants<FieldCode>();
From what I can tell, when creating the document in the first place (using Word 2013 on Windows 8.1) if you use the Insert->QuickParts->Field and choose MergeField from the Field names left hand pane, and then provide a Field name in the field properties and click OK then the field code is correctly saved in the document as I would expect.
Then when using the aforementioned line of code I will receive a field code count of 1 field. If I subsequently edit this document (and even leave this field well alone) the subsequent saving could mean that this field code no longer is returned in my query.
Another case of the same curiousness is when I see the FieldCode nodes split across multiple items. So rather than seeing say:
" MERGEFIELD Author \\* MERGEFORMAT "
As the node name, I will see:
" MERGEFIELD Aut"
"hor \\* MERGEFORMAT"
Split as two FieldCode node values. I have no idea why this would be the case, but it certainly makes my ability to match nodes that much more exciting. Is this expected behaviour? A known bug? I don't really want to have to crack open the raw xml and edit this document to work until I understand what is going on. Many thanks all.
I came across this very problem myself, and found a solution that exists within OpenXML: a utility class called MarkupSimplifier which is part of the PowerTools for Open XML project. Using this class solved all the problems I was having that you describe.
The full article is located here.
Here are some pertinent exercepts :
Perhaps the most useful simplification that this performs is to merge adjacent runs with identical formatting.
It goes on to say:
Open XML applications, including Word, can arbitrarily split runs as necessary. If you, for instance, add a comment to a document, runs will be split at the location of the start and end of the comment. After MarkupSimplifier removes comments, it can merge runs, resulting in simpler markup.
An example of the utility class in use is:
SimplifyMarkupSettings settings = new SimplifyMarkupSettings
{
RemoveComments = true,
RemoveContentControls = true,
RemoveEndAndFootNotes = true,
RemoveFieldCodes = false,
RemoveLastRenderedPageBreak = true,
RemovePermissions = true,
RemoveProof = true,
RemoveRsidInfo = true,
RemoveSmartTags = true,
RemoveSoftHyphens = true,
ReplaceTabsWithSpaces = true,
};
MarkupSimplifier.SimplifyMarkup(wordDoc, settings);
I have used this many times with Word 2010 documents using VS2015 .Net Framework 4.5.2 and it has made my life much, much easier.
Update:
I have revisited this code and have found it clears upon runs on MERGEFIELDS but not IF FIELDS that reference mergefields e.g.
{if {MERGEFIELD When39} = "Y???" "Y" "N" }
I have no idea why this might be so, and examination of the underlying XML offers no hints.
Word will often split text runs with into multiple text runs for no reason I've ever understood. When searching, comparing, tidying etc. We preprocess the body with method which combines multiple runs into a single text run.
/// <summary>
/// Combines the identical runs.
/// </summary>
/// <param name="body">The body.</param>
public static void CombineIdenticalRuns(W.Body body)
{
List<W.Run> runsToRemove = new List<W.Run>();
foreach (W.Paragraph para in body.Descendants<W.Paragraph>())
{
List<W.Run> runs = para.Elements<W.Run>().ToList();
for (int i = runs.Count - 2; i >= 0; i--)
{
W.Text text1 = runs[i].GetFirstChild<W.Text>();
W.Text text2 = runs[i + 1].GetFirstChild<W.Text>();
if (text1 != null && text2 != null)
{
string rPr1 = "";
string rPr2 = "";
if (runs[i].RunProperties != null) rPr1 = runs[i].RunProperties.OuterXml;
if (runs[i + 1].RunProperties != null) rPr2 = runs[i + 1].RunProperties.OuterXml;
if (rPr1 == rPr2)
{
text1.Text += text2.Text;
runsToRemove.Add(runs[i + 1]);
}
}
}
}
foreach (W.Run run in runsToRemove)
{
run.Remove();
}
}
I tried to simplify the document with Powertools but the result was a corrupted word file. I make this routine for simplify only fieldcodes that has specifics names, works in all parts on the docs (maindocumentpart, headers and footers):
internal static void SimplifyFieldCodes(WordprocessingDocument document)
{
var masks = new string[] { Constants.VAR_MASK, Constants.INP_MASK, Constants.TBL_MASK, Constants.IMG_MASK, Constants.GRF_MASK };
SimplifyFieldCodesInElement(document.MainDocumentPart.RootElement, masks);
foreach (var headerPart in document.MainDocumentPart.HeaderParts)
{
SimplifyFieldCodesInElement(headerPart.Header, masks);
}
foreach (var footerPart in document.MainDocumentPart.FooterParts)
{
SimplifyFieldCodesInElement(footerPart.Footer, masks);
}
}
internal static void SimplifyFieldCodesInElement(OpenXmlElement element, string[] regexpMasks)
{
foreach (var run in element.Descendants<Run>()
.Select(item => (Run)item)
.ToList())
{
var fieldChar = run.Descendants<FieldChar>().FirstOrDefault();
if (fieldChar != null && fieldChar.FieldCharType == FieldCharValues.Begin)
{
string fieldContent = "";
List<Run> runsInFieldCode = new List<Run>();
var currentRun = run.NextSibling();
while ((currentRun is Run) && currentRun.Descendants<FieldCode>().FirstOrDefault() != null)
{
var currentRunFieldCode = currentRun.Descendants<FieldCode>().FirstOrDefault();
fieldContent += currentRunFieldCode.InnerText;
runsInFieldCode.Add((Run)currentRun);
currentRun = currentRun.NextSibling();
}
// If there is more than one Run for the FieldCode, and is one we must change, set the complete text in the first Run and remove the rest
if (runsInFieldCode.Count > 1)
{
// Check fielcode to know it's one that we must simplify (for not to change TOC, PAGEREF, etc.)
bool applyTransform = false;
foreach (string regexpMask in regexpMasks)
{
Regex regex = new Regex(regexpMask);
Match match = regex.Match(fieldContent);
if (match.Success)
{
applyTransform = true;
break;
}
}
if (applyTransform)
{
var currentRunFieldCode = runsInFieldCode[0].Descendants<FieldCode>().FirstOrDefault();
currentRunFieldCode.Text = fieldContent;
runsInFieldCode.RemoveAt(0);
foreach (Run runToRemove in runsInFieldCode)
{
runToRemove.Remove();
}
}
}
}
}
}
Hope this helps!!!

Accumulo createBatchScanner range not working as expected

I cant get a batch scanner to only scan for a specific row, when settings start and stop keys to the same thing I get no entry's back, when using an scanner I get this exception:
"java.lang.IllegalArgumentException: Start key must be less than end key in range (Test : [] 0 false, Test : [] 0 false)"...
I am writing in C# in Visual Studio 2010 and using Thrift (ver 0.9.1.1) and Accumulo's (ver 1.5.0) proxy.thrift code in the project.
Here is my code, everything "works" but I don't get any entries from client.nextK
class Program
{
static byte[] GetBytes(string str)
{
return Encoding.ASCII.GetBytes(str);
}
static string GetString(byte[] bytes)
{
return Encoding.ASCII.GetString(bytes);
}
static void Main(string[] args)
{
try
{
/** connect **/
TTransport transport = new TSocket("192.168.58.62", 42424);
transport = new TFramedTransport(transport);
TCompactProtocol protocol = new TCompactProtocol(transport);
transport.Open();
AccumuloProxy.Client client = new AccumuloProxy.Client(protocol);
Dictionary<string, string> passwd = new Dictionary<string,string>();
passwd.Add("password", "password");
var login = client.login("root", passwd);
/** connect end **/
/** Get all data from one "Row" **/
var bScanner = new BatchScanOptions();
Range range = new Range();
range.Start = new Key();
range.Start.Row = GetBytes("Test");
range.Stop = new Key();
range.Stop.Row = GetBytes("Test");
bScanner.Ranges = new List<Range>();
bScanner.Ranges.Add(range);
var scanId = client.createBatchScanner(login, "firstTable", bScanner);
var more = true;
while (more)
{
var scan = client.nextK(scanId, 10);
more = scan.More;
foreach (var entry in scan.Results)
{
Console.WriteLine("{0} {1}:{2} [{3}] {4}", GetString(entry.Key.Row), GetString(entry.Key.ColFamily), GetString(entry.Key.ColQualifier), GetString(entry.Key.ColVisibility), GetString(entry.Value));
}
}
client.closeScanner(scanId);
Console.WriteLine();
/** Get data end **/
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
The user manual for Accumulo 1.5, is showing this code snippet and that is the same as I'm doing (but in C#): (http://accumulo.apache.org/1.5/accumulo_user_manual.html#_basic_table)
Range r = new Range(userid, userid); // single row
Scanner s = conn.createScanner("userdata", auths);
s.setRange(r);
s.fetchColumnFamily(new Text("age"));
for(Entry<Key,Value> entry : s)
System.out.println(entry.getValue().toString());
The problem is likely your range. In the Java API, you can construct a Range for a single row, with:
Range r = new Range("myRow");
In the thrift Proxy API, you can only give Keys to the Range constructor, not just RowIDs (this is an option in the Java API, also, but it is the only option in the Proxy API). Keys represent a single entry, so scanning:
R1:CF1:CQ1:CV1 -> R1:CF1:CQ1:CV1
will only ever result a scan over that one exact entry (and possibly all versions of it, if you don't have the VersioningIterator configured for the table).
So, if you want to scan all entries in row "a", you don't scan like this:
"a":null:null:null(inclusive) -> "a":null:null:null(inclusive)
Rather, you scan like this for row == "a":
"a":null:null:null(inclusive) -> "a\0":null:null:null(exclusive)
Or this, for row startsWith "a":
"a":null:null:null(inclusive) -> "b":null:null:null(exclusive)
Have you already checked that possibility here?
https://issues.apache.org/jira/browse/ACCUMULO-1189
It's fixed in Accumulo 1.5, you use 1.4, so seems worth a look.

C# simple form index was outside the bounds of the array

I'm a student of programming and decided to make a simple program to practice.
It's a simple form, with name, date of birth, address etc, and it's being saved in a text file (I know there are easier ways, but I want to learn all of them and started with this one =) )
I have a button to search, by name, if the person is already saved and, if yes, it's supposed to fill the form with the data.
Here's an example of how it's saved:
38b7aa1f-0afb-4fe5-a8f6-40fe953eb1ca;Cindy;22/07/2005;111.111.111-11;22.222.222-2;33333-333;Testes;2112;05;Testando;Testadora;SP;cindy#gmail.com;(44)44444-4444;(55)55555-5555;True;True;Rose;26/05/1950;666.666.666-66;77.777.777-7
So, the name (Cindy) would be in and index[1] of an array.
The problem is this error: index was outside the bounds of the array
At this line: if (linha[1] == txtboxNome.Text)
I've searched on internet and kinda understood the problem, but still don't know how to fix it.
Can anybody help me, please?
How can I load my form properly?
Here's an print to help you "see" the program. Don't worry abou the layout, a few things get opacity 0 when running =)
http://i.imgur.com/jze16Pz.jpg
Thanks in advance =)
private void pesquisarNovoBtn_Click(object sender, RoutedEventArgs e)
{
var filePath = #"E:\Programação\WPF ConsultorioDentista\WPF ConsultorioDentista\bin\Debug\Pacientes.txt";
string[] resultado = null;
using (var abrirPacientes = System.IO.File.OpenText(filePath))
{
string lerPacientes = abrirPacientes.ReadLine();
while (lerPacientes != null)
{
var linha = lerPacientes.Split(';');
if (linha[1] == txtboxNome.Text)
{
resultado = linha;
break;
}
lerPacientes = abrirPacientes.ReadLine();
}
if (resultado == null)
{
MessageBox.Show("Paciente não encontrado.");
}
else
{
txtboxNome.Text = resultado[1];
txtboxData.Text = resultado[2];
txtboxCPF.Text = resultado[3];
txtboxRG.Text = resultado[4];
txtboxCEP.Text = resultado[5];
txtboxEndereco.Text = resultado[6];
txtboxNumero.Text = resultado[7];
txtboxCompl.Text = resultado[8];
txtboxBairro.Text = resultado[9];
txtboxCidade.Text = resultado[10];
txtboxUF.Text = resultado[11];
txtboxEmail.Text = resultado[12];
txtboxCel.Text = resultado[13];
txtboxTelRes.Text = resultado[14];
//checkBoxClinico.IsChecked = resultado[15];
//checkBoxOrto.IsChecked = resultado[16];
txtboxNomeResp.Text = resultado[17];
txtboxNascResp.Text = resultado[18];
txtboxCPFResp.Text = resultado[19];
txtboxRGResp.Text = resultado[20];
}
abrirPacientes.Close();
}
This is where you need to "Step Through" the application. Set a Breakpoint (F9) on the If STatement :
if (linha[1] == txtboxNome.Text)
{
resultado = linha;
break;
}
And mouse over to look at the values contained in the linha array.
Most likely you have a header in the first row of your file and it's not splitting.

Categories