How to complete aspx connection string from text file - c#

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;
}
}
}

Related

How to check if Parse(args) is true or false

I have code that is not throwing any error. I have used NDesk option set and added 2 string Parameters. I can see it has pulled correct names in args. But when I uses parse(args) it is not throwing an error. So I am assuming it is working.
I am trying to check if p(args) is true or false. But I can not use bool expressions to List<string>.
Any help how I can accomplish that. I want execute function if parse has correct arguments.
My code is like this
private static Regex fileNamePattern = new Regex(#"^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}[.]pdf$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//missing method name
{
string inputFile;
string outputFile;
var p = new OptionSet() {
{"i"," pdf file",v=>inputFile=v},{"o","index file with kws",v=>outputFile=v},
};
Console.WriteLine($"args length: {args.Length}");
Console.WriteLine($"args 0: {args[0]}");
Console.WriteLine($"args 1: {args[1]}");
p.Parse(args); //I would like to use this if(parse(args))
{
}
//
}
private static void UpdateImportIndexFile(string inputFile, string outputFile)
{
using (var dip = File.CreateText(outputFile))
{
var match = fileNamePattern.Match(Path.GetFileName(MainFilePath));
if (match.Success)
{
//create text file (outputfile);
}
}
}
Since p is an instance of a class and the parse method does not support a return to emulate in a sense the functionality of a TryParse wrap your parse in a try block
try{
val = p.Parse(args);
}catch(OptionException e){
//if false
}
For more information http://www.ndesk.org/doc/ndesk-options/NDesk.Options/OptionSet.html#M:NDesk.Options.OptionSet.Parse(System.Collections.Generic.IEnumerable{System.String})

How to write and read list<> from text files in C#

English is not my native language and I am newbie, so don't laugh at me.
I want to create a class in C# that help me to save data to file and read them easily. It works like this:
RealObject john = new RealObject("John");
john.AddCharacter("Full Name", "Something John");
john.AddCharacter("Grade", new List<double> { 9.9, 8.8, 7.7 });
await john.SaveToFileAsync("Test.ini");
RealObject student = new RealObject("John");
await student.ReadFromFileAsync("Test.ini");
Type valueType = student.GetCharacter("Grade").Type;
List<double> johnGrade = (List<double>) student.GetCharacter("Grade").Value;
The file "Test.ini" looks like this:
S_Obj_John
Name System.String Something John
Grade System.Collections.Generic.List`1[System.Double] 9.9;8.8;7.7
E_Obj_John
I have some questions:
Question 1. Can you give me some libraries that do this job for me, please?
Question 2. My code is too redundant, how can I optimize it?
2.1 Saving code: I have to write similar functions: ByteListToString, IntListToString, DoubleListToString,...
private static string ListToString(Type listType, object listValue)
{
string typeString = GetBaseTypeOfList(listType);
if (typeString == null)
{
return null;
}
switch (typeString)
{
case "Byte":
return ByteListToString(listValue);
..........
default:
return null;
}
}
private static string ByteListToString(object listValue)
{
List<byte> values = (List<byte>) listValue;
string text = "";
for (int i = 0; i < values.Count; i++)
{
if (i > 0)
{
text += ARRAY_SEPARATING_SYMBOL;
}
text += values[i].ToString();
}
return text;
}
2.2 Reading code: I have to write similar functions: StringToByteList, StringToIntList, StringToDoubleList,...
public static object StringToList(Type listType, string listValueString)
{
string typeString = GetBaseTypeOfList(listType);
if (typeString == null)
{
return null;
}
switch (typeString)
{
case "Byte":
return StringToByteList(listValueString);
..........
default:
return null;
}
}
private static List<byte> StringToByteList(string listValueString)
{
var valuesString = listValueString.Split(ARRAY_SEPARATING_SYMBOL);
List<byte> values = new List<byte>(valuesString.Length);
foreach (var v in valuesString)
{
byte tmp;
if (byte.TryParse(v, out tmp))
{
values.Add(tmp);
}
}
return values;
}
Thank you for your help
There are two ways two common ways to "serialize" data, which is a fancy way of taking an object and turning it into a string. Then on the other side you can "deserialize" that string and turn it back into an object. Many folks like JSON because it is really simple, XML is still used and can be useful for complex structures but for simple classes JSON is really nice.
I would check out https://www.json.org/ and explore, libraries exist that will serialize and deserialize for you which is nice. Trying to do it with string manipulation is not recommended as most people (including me) will mess it up.
The idea though is to start and end with objects, so take an object and serialize it to save it to the file. Then read that object (really just a string or line of text in the file) and deserialize it back into an object.

How can I simulate user input from a console?

Im doing some challenges in HackerRank. I usually use a windows Form project in visualstudio to do the debug, but realize I lost lot of time input the test cases. So I want suggestion of a way I can easy simulate the console.ReadLine()
Usually the challenges have the cases describe with something like this:
5
1 2 1 3 2
3 2
And then is read like: using three ReadLine
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
string[] squares_temp = Console.ReadLine().Split(' ');
int[] squares = Array.ConvertAll(squares_temp,Int32.Parse);
string[] tokens_d = Console.ReadLine().Split(' ');
int d = Convert.ToInt32(tokens_d[0]);
int m = Convert.ToInt32(tokens_d[1]);
// your code goes here
}
Right now I was thinking in create a file testCase.txt and use StreamReader.
using (StreamReader sr = new StreamReader("testCase.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
This way I can replace Console.ReadLine() with sr.ReadLine(), but this need have a text editor open, delete old case, copy the new one and save the file each time.
So is there a way I can use a Textbox, so only need copy/paste in the textbox and use streamReader or something similar to read from the textbox?
You can use the StringReader class to read from a string rather than a file.
the solution you accepted! doesn't really emulate the Console.ReadLine(), so you can't paste it directly to HackerRank.
I solved it this way:
.
.
Just paste this class above the static Main method or anywhere inside the main class to hide the original System.Console
class Console
{
public static Queue<string> TestData = new Queue<string>();
public static void SetTestData(string testData)
{
TestData = new Queue<string>(testData.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(x=>x.TrimStart()));
}
public static void SetTestDataFromFile(string path)
{
TestData = new Queue<string>(File.ReadAllLines(path));
}
public static string ReadLine()
{
return TestData.Dequeue();
}
public static void WriteLine(object value = null)
{
System.Console.WriteLine(value);
}
public static void Write(object value = null)
{
System.Console.WriteLine(value);
}
}
and use it this way.
//Paste the Console class here.
static void HackersRankProblem(String[] args)
{
Console.SetTestData(#"
6
6 12 8 10 20 16
");
int n = int.Parse(Console.ReadLine());
string arrStr = Console.ReadLine();
.
.
.
}
Now your code will look the same! and you can test as many data as you want without changing your code.
Note: If you need more complexes Write or WriteLine methods, just add them and send them to the original System.Console(..args)
Just set Application Arguments: <input.txt
and provide in input.txt your input text.
Be careful to save the file with ANSI encoding.

How to read and create new user by every 4th line

So, I read a text file. It looks like this:
TEACHER - TEACHER/STUDENT
adamsmith - ID
Adam Smith - Name
B1u2d3a4 - Password
STUDENT
marywilson
Mary Wilson
s1Zeged
TEACHER
sz12gee3
George Johnson
George1234
STUDENT
sophieb
Sophie Black
SophieB12
And so on, there are all the users.
The user class:
class User
{
private string myID;
private string myName;
private string myPW;
private bool isTeacher;
public string ID
{
get
{
return myID;
}
set
{
myID = value;
}
}
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public string PW
{
get
{
return myPW;
}
set
{
PW = value;
}
}
public bool teacher
{
get
{
return teacher;
}
set
{
isTeacher = value;
}
}
public override string ToString()
{
return myName;
}
}
The Form1_Load method:
private void Form1_Load(object sender, EventArgs e)
{
List<User> users = new List<User>();
string line;
using (StreamReader sr = new StreamReader("danet.txt"))
{
while ((line=sr.ReadLine())!=null)
{
User user = new User();
user.ID=line;
user.Name=sr.ReadLine();
user.PW=sr.ReadLine();
if(sr.ReadLine=="TEACHER")
{
teacher=true;
}
else
{
teacher=false;
}
users.Add(user);
}
}
}
I want to read the text and store the informations. By this method I get 4 times more user than I should. I was thinking of using for and a couple of things, but I didn't get to a solution.
New answer
Your reader assumes the every fourth line is the user-id, it is not, the absolute first line is a STUDENT/TEACHER line. Either this is a typo, or you have to change your format.
Your PW property will cause a StackOverflowException,
public string PW
{
get
{
return myPW;
}
set
{
PW = value;
}
}
Change the setter to myPW = value;, or just convert them to auto-properties.
Your teacher property has the same error, but on the getter.
You have also missed the () on one of your ReadLine's, but let's just assume this is a typo.
Not using a text-file, but just a string so I'm using a StringReader instead, but it's the same concept.
string stuff =
#"adamsmith
Adam Smith
B1u2d3a4
STUDENT
marywilson
Mary Wilson
s1Zeged
TEACHER
sz12gee3
George Johnson
George1234
STUDENT
sophieb
Sophie Black
SophieB12
STUDENT";
public void Main(string[] args)
{
string line;
var users = new List<User>();
using (var sr = new StringReader(stuff))
{
while ((line = sr.ReadLine()) != null)
{
User user = new User();
user.ID = line;
user.Name = sr.ReadLine();
user.PW = sr.ReadLine();
user.teacher = sr.ReadLine() == "TEACHER";
users.Add(user);
}
}
}
Old answer
There is nothing inherently erroneous with you code. But since you have not provided an actual example of what your "danet.txt" looks like, one must assume the error lies within the data itself.
Your "parser" (if you want to call it that) is not forgiving, i.e. if there is an empty line in your source file or if you just mess up one line (say forget putting in a password or ID) then everything would get offset – but as far as your "parser" is concerned, nothing is wrong.
By default formats which depend on "line positions" or "line offset" are prone to break, especially if the file itself is created by hand versus being auto-generated.
Why not use a denoted format instead? Such as XML, JSON or even just INI. C# can handle either of these, either built in or by external libraries (see the links).
There will never be any way for your "line-by-line" parser to not break if the user makes a faulty input, that is unless you have very strict formats for IDs, names, passwords and "student/teachers". and then validate them, using regular expressions (or similar). But that would defeat the purpose of a simple "line-by-line" format. And by then, you might as well go with a more "complex" format.
while ((line=sr.ReadLine())!=null)
{
User user = new User();
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 1:
user.ID = line;
break;
case 2:
user.Name=sr.ReadLine();
break;
....
}
}
}

Editing record in delimited file using FileHelper

I have a simple Delimited log file. I`m using FileHelper library to parse the file using the following code:
LogLine record;
FileHelperAsyncEngine<LogLines> engine = new FileHelperAsyncEngine<LogLines>();
engine.BeginReadFile(#"C:\logs\Log.log");
while (engine.ReadNext() != null)
{
record = engine.LastRecord;
//record.Reported = true; <---I want to be able to edit this!
// Your Code Here
}
Is there any way I can edit this record?
Will something like this be fine for you?
This will modify second element of that file; could not find method similar to seek for that class.
public static void WriteExample()
{
FileHelperEngine engine = new FileHelperEngine(typeof(SampleType));
// to Read use:
SampleType[] res = engine.ReadFile("source.txt") as SampleType[];
res[1].Field1 = "test";
res[1].Field2 = 9;
// to Write use:
engine.WriteFile("source2.txt", res);
}

Categories