I'm not sure what the problem is here. My program can read the "text" and put it in the Title without any problems, but it crashes and doesn't change the size or color before it does so. I tried asking my classmates for help regarding this, but they say all my code looks correct.
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 RetrieveCustomizedForm
{
public partial class Form1 : Form
{
const char DELIM = ',';
string recordIn;
string[] fields;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
const string FILENAME = "C:\\Exercise5\\Data.txt";
stuff stuff1 = new stuff();
FileStream inFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
recordIn = reader.ReadLine();
reader.Close();
inFile.Close();
while (recordIn != null)
{
fields = recordIn.Split(DELIM);
stuff1.color = fields[0];
stuff1.size = fields[1];
stuff1.text = fields[2];
if (fields[0] == "red")
{
this.BackColor = System.Drawing.Color.Red;
}
if (fields[0] == "blue")
{
this.BackColor = System.Drawing.Color.Blue;
}
if (fields[0] == "yellow")
{
this.BackColor = System.Drawing.Color.Yellow;
}
if (fields[1] == "large")
{
this.Size = new System.Drawing.Size(500, 500);
}
if (fields[1] == "small")
{
this.Size = new System.Drawing.Size(300, 300);
}
this.Text = fields[2];
}
}
class stuff
{
public string color { get; set; }
public string size { get; set; }
public string text { get; set; }
}
}
}
fields : might be empty, end of the file?
Any file open error? trying to open it again while it is already opened in background?
Some more information might be helpful. Like The others have said, what are the values of fields[0]-[2]? What errors are you receiving? It looks to me like one error you will receive is that your index is outside the bounds of the fields array...Give us some more info and we can better help you.
try it this way
using (FileStream infile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(infile))
{
string recordIn = reader.ReadLine();
while (recordIn != null)
{
fields = recordIn.Split(DELIM);
stuff1.color = fields[0];
stuff1.size = fields[1];
stuff1.text = fields[2];
if (fields[0] == "red")
{
this.BackColor = System.Drawing.Color.Red;
}
if (fields[0] == "blue")
{
this.BackColor = System.Drawing.Color.Blue;
}
if (fields[0] == "yellow")
{
this.BackColor = System.Drawing.Color.Yellow;
}
if (fields[1] == "large")
{
this.Size = new System.Drawing.Size(500, 500);
}
if (fields[1] == "small")
{
this.Size = new System.Drawing.Size(300, 300);
}
this.Text = fields[2];
}
}
}
Related
I'm new to C#, and trying to make user login window.
Currently I'm trying to search from txt file and it works fine if I enter correct username. But the issue is when wrong username is entered- it stucks in loop.
Actually the way I'm reading the string from textbox is wrong, Its not allowing me to enter new string before again comparing it from file if I enter wrong username. It keeps comparing the old value or null value
Can anyone guide how this is done?
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
if (lines[us] == usernam)
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?",
"Retry",
MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
username.Clear();
}
}
}
while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
if (lines[us] == usernam)
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
The problem lies in your while loop. Imagine line = "incorrectUsername" on the first iteration of your file. You're assigning "incorrectUserName" to line[0] then line[1] then line[2] etc... and it never stops. You just keep assigning an invalid username into an array then comparing the entered username against that value. What you want to do is ditch the "lines" array, and simply compare the username against the line:
if (line.Equals(username))
{
//Go to new form
}
In this simple case you don't need to use StreamReader, this is a simpler approach:
string myUserName = "Admin";
string[] lines = File.ReadAllLines(usersTextFile, Encoding.UTF8);
bool found = false;
if (lines != null)
{
foreach (var l in lines)
{
if (string.IsNullOrEmpty(l))
continue;
if (l.ToLower() == myUserName.ToLower())
{
found = true;
break;
}
}
}
if (found)
MessageBox.Show("Welcome " + myUserName + "!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
else
MessageBox.Show("User not found!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Error);
My complete code is:
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 Employees_1
{
public partial class Form2 : Form
{
string pathuser = #"//192.168.1.10/Shared-Public/testfile.txt";
int check = 0;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// string username = username.Text;
}
private void button1_Click(object sender, EventArgs e)
{
//string usernam = username.Text;
// MessageBox.Show(usernam);
while (check != 1)
{
userpass();
}
this.Close();
}
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
if (lines[us] == usernam)
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?", "Retry", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
//DialogResult result = MessageBox.Show("Invalid Username or Password", "Error", MessageBoxButtons.OK);
// MessageBox.Show("Invalid Username or Password");
username.Clear();
}
}
}
/* string[] lines = File.ReadAllLines(pathuser, Encoding.UTF8);
bool found = false;
string usernam = username.Text;
if (lines != null)
{
foreach (var l in lines)
{
if (string.IsNullOrEmpty(l))
continue;
if (l.ToLower() == usernam.ToLower())
{
found = true;
break;
}
}
}
if (found)
MessageBox.Show("Welcome " + usernam + "!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
else
MessageBox.Show("User not found!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
*/
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Facebook;
using System.Net;
using System.IO;
namespace WebSite_Login_And_Browsing
{
class Posts
{
public string PostId { get; set; }
public string PostStory { get; set; }
public string PostMessage { get; set; }
public string PostPicture { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
class FacebookPosts
{
static string accesstoken;
//static string token = "2f89d691b5f39";
static string token = "1186840401345424|GoJRCpM";
static string mytoken = "CAACEdEose0cBACPu39NSSalHCGFGDGRKZAvwiTuzG8PHlNRJwbyMVugovDxgL7CT3a1QbRuVDZALXxWU0ntwSrDyq75LIIuzFpBtx47cJYCY2OiA21lpTRKt2bB0t5HrsQYIXHXhmU7GnavWZCzqN8yeuv5NWXxTIOfVCZAZArjYNiPWhZBqZAZAO03s6FKNIulm4kjzXvp4QKiahAlcyaZBg";
static string mytokenaslip = "CAACEdEose0cBABmWuBI9p9dpPxEsMJoFZAG3kScx61kZAImNBgt52kVrd8WWPRpwjWP8nCPX69zdLuFyVQHzxYfMk85ZBZC4BIajVWXNLo7OI7yaCbNIwqkcdwpabQVFZBRWt0rzTQrQr6ZBij45XnrQyEUqFKP4gADeO4Fl9yRaZAZCOFtV3b84sWUFEgwaKbZAPY4BCljVjWQZDZD";
public static void RetrievePosts()
{
try
{
var client = new FacebookClient(mytokenaslip);
dynamic result = client.Get("/me/posts");
List<Posts> postsList = new List<Posts>();
//all the posts and their information (like pictures and links) is strored in result.data not in result
for (int i = 0; i < result.data.Count; i++)
{
Posts posts = new Posts();
posts.PostId = result.data[i].id;
if (object.ReferenceEquals(result.data[i].story, null))
posts.PostStory = "this story is null";
else
posts.PostStory = result.data[i].story;
if (object.ReferenceEquals(result.data[i].message, null))
posts.PostMessage = "this message is null";
else
posts.PostMessage = result.data[i].message;
posts.PostPicture = result.data[i].picture;
posts.UserId = result.data[i].from.id;
posts.UserName = result.data[i].from.name;
postsList.Add(posts);
}
}
catch (Exception err)
{
//throw;
string myerr = err.ToString();
}
}
}
}
I'm getting 25 results in the List postsList
How do i loop now asgain to get the next page with the next 25 results and add it to postsList and loop over and over again untill there are no more results ?
What i want to do is to delete automatic every 50 minutes the last old 25 posts.
In my other class in my project i'm posting automatic to my wall a post every minute. After 50 minutes i want to delete the last old 25 posts so on my wall will be all the time with 25 posts only.
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 mshtml;
using HtmlAgilityPack;
using System.Net;
using System.IO;
namespace WebSite_Login_And_Browsing
{
public partial class Facebook_Post : Form
{
WebBrowser wb = new WebBrowser();
int postsCounter = 0;
StreamWriter w = new StreamWriter(#"e:\posts.txt");
WebBrowser webBrowser1;
public Facebook_Post()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("https://www.facebook.com/");
label4.Text = DateTime.Now.ToString();
w.WriteLine(label4.Text.ToString());
w.WriteLine(Environment.NewLine);
label5.Visible = false;
label2.Visible = false;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (e.Url.AbsoluteUri != webBrowser1.Url.AbsoluteUri)
{
return;
}
wb = webBrowser1;
foreach (HtmlElement he in wb.Document.All.GetElementsByName("xhpc_message"))
{
he.SetAttribute("value", RandomString(10));
}
var elems = wb.Document.GetElementsByTagName("button");
foreach (HtmlElement elem in elems)
{
if (elem.InnerText == "Post")
{
elem.InvokeMember("click");
}
}
sent = true;
postsCounter += 1;
label2.Text = postsCounter.ToString();
label2.Visible = true;
timer1.Enabled = true;
webBrowser1.Dispose();
if (postsCounter == 720)
{
w.WriteLine(postsCounter.ToString());
w.WriteLine(Environment.NewLine);
label5.Text = DateTime.Now.ToString();
label5.Visible = true;
w.WriteLine(label5.Text.ToString());
w.Close();
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> results = new List<string>();
HtmlElementCollection elems = wb.Document.GetElementsByTagName("INPUT");
foreach (HtmlElement elem in elems)
{
String nameStr = elem.GetAttribute("value");
results.Add(nameStr);
}
}
bool sent = false;
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
try
{
count += 1;
if (sent == true && count >= 60)
{
count = 0;
timer1.Enabled = false;
webBrowser1 = new WebBrowser();
if (webBrowser1.IsBusy == false)
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
webBrowser1.Navigate("https://www.facebook.com/");
}
sent = false;
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
}
private StringBuilder builder;
private static Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int size)
{
try
{
builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
}
catch(Exception err)
{
string myerr = err.ToString();
}
return builder.ToString();
}
}
}
I believe this is what you're looking for:
var client = new FacebookClient(mytokenaslip);
//1-25
dynamic result = client.Get("/me/posts", new { limit = "25", offset = "0"});
//26-50
dynamic result = client.Get("/me/posts", new { limit = "25", offset = "25"});
You can also chose to get more than 25 posts at once.
//51-100
dynamic result = client.Get("/me/posts", new { limit = "50", offset = "50"});
You can use a "recursive function" to get all entries, and the "next" parameter in the API result includes the API call for the next batch of results: https://developers.facebook.com/docs/graph-api/using-graph-api#paging
Be careful though, you may hit an API limit if you try to do this too fast and if there are too many results. Also, since you want to delete old entries and deleting one entry is one API call, you should try with a timeout after each call just to make sure not to hit a limit.
Make sure you learn and understand how recursive functions work, here´s one of countless threads about that: Help with Creating a Recursive Function C#
Okay. I have been working on a speech recognition program. I want to make it when you say something like "search the web for images of cats" it will open the browser and search for images of cats. I made a textbox to receive the inputs of the user's speech, but I have been stumped to find out how to retrieve the text from the textbox and send it to the web.
Where textbox1.text = speech; is where the speech is converted to text.
Heres my code so far:
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.Speech.Recognition;
using System.Speech.Synthesis;
using System.IO;
using System.Xml;
using System.Threading;
using System.Net;
namespace Jarvis
{
public partial class Form1 : Form
{
SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
SpeechSynthesizer JARVIS = new SpeechSynthesizer();
string QEvent;
string ProcWindow;
string BrowseDirectory;
string Temperature;
string Condition;
string Humidity;
string WindSpeed;
string Town;
string TFCond;
string TFHigh;
string TFLow;
double timer = 10;
int count = 1;
Random rnd = new Random();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_recognizer.SetInputToDefaultAudioDevice();
_recognizer.LoadGrammar(new DictationGrammar());
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(#"C:\Users\Jeremy\Documents\Visual Studio 2012\Projects\Jarvis\Jarvis\commands.txt")))));
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(#"C:\Users\Jeremy\Documents\Visual Studio 2012\Projects\Jarvis\Jarvis\greetings.txt")))));
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(#"C:\Users\Jeremy\Documents\Visual Studio 2012\Projects\Jarvis\Jarvis\programs.txt")))));
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(#"C:\Users\Jeremy\Documents\Visual Studio 2012\Projects\Jarvis\Jarvis\social.txt")))));
_recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(_recognizer_SpeechRecognized);
_recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
void _recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
var game = 0;
int ranNum = rnd.Next(1, 10);
int ranNumm = rnd.Next(1, 15);
bool wh = false;
bool sleep = false;
string speech = e.Result.Text;
textBox1.Text = speech;
if (textBox1.Text == url)
{
}
switch (speech)
{
//GREETINGS
case "hello":
case "hey":
case "hey jarvis":
if (ranNum < 6) { JARVIS.Speak("Hello sir"); }
else if (ranNum > 5) { JARVIS.Speak("Hi"); }
break;
}
}
private void ShutdownTimer_Tick(object sender, EventArgs e)
{
if (timer == 0)
{
lblTimer.Visible = false;
ComputerTermination();
ShutdownTimer.Enabled = false;
}
else if (QEvent == "abort")
{
timer = 10;
lblTimer.Visible = false;
ShutdownTimer.Enabled = false;
}
else
{
timer = timer - .01;
lblTimer.Text = timer.ToString();
}
}
private void ComputerTermination()
{
switch (QEvent)
{
case "shutdown":
System.Diagnostics.Process.Start("shutdown", "-s");
break;
case "logoff":
System.Diagnostics.Process.Start("shutdown", "-l");
break;
case "restart":
System.Diagnostics.Process.Start("shutdown", "-r");
break;
}
}
private void StopWindow()
{
System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName(ProcWindow);
foreach (System.Diagnostics.Process proc in procs)
{
proc.CloseMainWindow();
}
}
private void LoadDirectory()
{
lstCommands.Items.Clear();
switch (QEvent)
{
case "music directory":
string[] files = Directory.GetFiles(BrowseDirectory, ".mp3", SearchOption.AllDirectories);
foreach (string file in files) {lstCommands.Items.Add(file.Replace(BrowseDirectory, ""));}
break;
case "video directory":
files = Directory.GetFiles(BrowseDirectory, "*", SearchOption.AllDirectories);
foreach (string file in files) {lstCommands.Items.Add(file.Replace(BrowseDirectory, ""));}
break;
case "picture directory":
files = Directory.GetFiles(BrowseDirectory, "*", SearchOption.AllDirectories);
foreach (string file in files) {lstCommands.Items.Add(file.Replace(BrowseDirectory, ""));}
break;
case "load directory":
files = Directory.GetFiles(BrowseDirectory, "*", SearchOption.AllDirectories);
foreach (string file in files) {lstCommands.Items.Add(file.Replace(BrowseDirectory + "\\", ""));}
break;
}
}
private void lstCommands_SelectedIndexChanged(object sender, EventArgs e)
{
Object open = BrowseDirectory + lstCommands.SelectedItem;
try
{ System.Diagnostics.Process.Start(open.ToString()); }
catch { open = BrowseDirectory + "\\" + lstCommands.SelectedItem; System.Diagnostics.Process.Start(open.ToString()); }
}
private void GetWeather()
{
string query = String.Format("http://weather.yahooapis.com/forecastrss?w=2434216");
XmlDocument wData = new XmlDocument();
wData.Load(query);
XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
XmlNodeList nodes = wData.SelectNodes("/rss/channel/item/yweather:forecast", manager);
Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value;
Condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["text"].Value;
Humidity = channel.SelectSingleNode("yweather:atmosphere", manager).Attributes["humidity"].Value;
WindSpeed = channel.SelectSingleNode("yweather:wind", manager).Attributes["speed"].Value;
Town = channel.SelectSingleNode("yweather:location", manager).Attributes["city"].Value;
TFCond = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["text"].Value;
TFHigh = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["high"].Value;
TFLow = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["low"].Value;
}
}
}
Why do you need to retrieve the text from the textbox, when you have the text
string speech = e.Result.Text;
already? All you need to do is URLEncode the string (sample function here) and open a browser window with the URL.
Use Google image search API developer, get image url, declare xml document, make variables.
https://developers.google.com/image-search/v1/devguide
using (PrintDialog printDialog1 = new PrintDialog())
{
if (printDialog1.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(saveAs.ToString());
info.Arguments = "\"" + printDialog1.PrinterSettings.PrinterName + "\"";
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
info.Verb = "PrintTo";
System.Diagnostics.Process.Start(info);
}
}
The above code works fine. I just don't know how to change the code so that I can preview the Word document first.
Okay, so I worked on this last night after getting home and I believe I figured it out. It's NOT perfect but, it does get you moving in the right direction. BTW, I created a simple WinForms app for this, and you will need to edit the code to suit your needs.
The code:
namespace WindowsFormsApplication1
{
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Drawing.Printing.PrintDocument doc = new System.Drawing.Printing.PrintDocument();
PrintPreviewDialog dlg = new PrintPreviewDialog();
dlg.Document = doc;
doc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.PrintPage);
dlg.ShowDialog();
}
private void PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
try
{
string fileName = #"C:\Users\brmoore\Desktop\New Text Document.txt";
StreamReader sr = new StreamReader(fileName);
string thisIsATest = sr.ReadToEnd();
sr.Close();
System.Drawing.Font printFont = new System.Drawing.Font("Arial", 14);
e.Graphics.DrawString(thisIsATest, printFont, Brushes.Black, 100, 100);
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
}
}
So now I want to make Estonian wordlist ~about 20m unique words in lowercase. To get input for wordlist, corpus of Estonian can be used. Corpus files are in Text Encoding Initiative (TEI) format. I tried using regex to find the words.
This is what I made: it's inefficient, mcv is all messed up, it brakes if hashset of words can't fit in memory, it's not aware of inputs encoding - so probably letters like š make problems, it does not show estimated completion time, some controls have default names and some don't, it does not use multitasking (not sure if it should), it uses some weird fixes and lots of locking interface so that it would appear not 'frozen'. At least its so short, that you hardly notice there are no comments.
Upside is, that it can almost read words without many mistakes, from .tei, .txt, .csv, smgl, xhtml or any a like format inputs.
Now you know what I want to do, how I have tried doing it (with what problems), and again I'm just trying to find out how to do it (with minimal manual labor).
Image example:
Code example & Gui:
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.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
namespace Reader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void listView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void listView1_DragDrop(object sender, DragEventArgs e)
{
setguiLock(true);
this.loading.Visible = true;
ignorechecking = true;
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
Dictionary<String, ListViewGroup> listviewgroups = new Dictionary<string,ListViewGroup>();
int filenamesi = 0;
foreach (string file in files)
{
progresslabel.Text = string.Format("Progress: \t[ {0} / {1} ]", filenamesi++, files.Length);
Application.DoEvents();
if (File.Exists(file))
{
FileInfo ff = new System.IO.FileInfo(file);
if (!listviewgroups.ContainsKey(ff.DirectoryName))
{
listviewgroups.Add(ff.DirectoryName, new ListViewGroup(ff.DirectoryName, HorizontalAlignment.Left));
listView1.Groups.Add(listviewgroups[ff.DirectoryName]);
}
ListViewItem item = new ListViewItem(ff.Name);
listviewgroups[ff.DirectoryName].Items.Add(item);
item.Checked = true;
item.SubItems.Add("" +((int)ff.Length/1024)+" KB");
// item.Group.Header = ff.DirectoryName;
// listviewgroups[ff.DirectoryName].Items.Add(item);
listView1.Items.Add(item);
}
}
setguiLock(false);
ignorechecking = false;
this.loading.Visible = false;
updatechecked();
}
private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
updatechecked();
}
private bool ignorechecking = false;
private void updatechecked(){
if (ignorechecking)
return;
long size = 0;
int count = 0;
foreach (ListViewItem item in this.listView1.Items)
{
if (item.Checked)
{
count++;
size += Int32.Parse(item.SubItems[1].Text.Split(" ".ToArray())[0]);
}
}
this.text1.Text = ""+count;
this.text2.Text = ""+size + " KB";
}
private void putHashset(HashSet<string> d, string filename)
{
StringBuilder sb = new StringBuilder();
foreach (string key in d)
sb.Append(key).Append("\n");
File.WriteAllText(filename, sb.ToString());
}
private HashSet<string> getHashset(string filename)
{
return new HashSet<string>(new Regex("\\n+").Split(File.ReadAllText(filename)));
}
private void removefilefromlistview(string fullfilename) {
foreach (ListViewItem item in this.listView1.Items)
{
String file = item.Group.Header + "\\" + item.SubItems[0].Text;
if (fullfilename.CompareTo(file) == 0)
{
item.Checked = false;
this.listView1.Items.Remove(item);
}
}
}
private void starter(object sender, EventArgs e)
{
HashSet<string> filenames = new HashSet<string>();
StringBuilder data = null;
setguiLock(true);
this.time2.Text = "";
this.time1.Text = String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now);
foreach (ListViewItem item in this.listView1.Items) {
if (item.Checked) {
String file = item.Group.Header + "\\" + item.SubItems[0].Text;
if (File.Exists(file))
filenames.Add(file);
}
}
string outputfile = output.Text;
HashSet<string> words = null;
if (File.Exists(output.Text))
words = getHashset(outputfile);
else
words = new HashSet<string>();
int filenamesnr = filenames.Count;
int filenamesi = 0;
foreach (String str in filenames){
progresslabel.Text = string.Format("Progress: \t[ {0} / {1} ]", filenamesi++, filenamesnr);
Application.DoEvents();
data = new StringBuilder(System.IO.File.ReadAllText(str, Encoding.UTF7).ToLower());
data = data.Replace("ä", "ä");
data = data.Replace("ö", "ö");
data = data.Replace("ü", "ü");
data = data.Replace("õ", "õ");
String sdata = new Regex(#"<(.|\n)*?>|%[a-zA-Z0-9]+?;|&[#a-zA-Z0-9]+?;").Replace(data.ToString(), "");
foreach (string word in new Regex("[^A-Za-zšžõäöüŠŽÕÄÖÜ]+").Split(sdata))
if(word.Length>1)
words.Add(word);
removefilefromlistview(str);
}
progresslabel.Text = "Progress:";
putHashset(words, outputfile);
foreach (ListViewItem item in this.listView1.Items)
if (item.Checked)
{
item.Checked = false;
listView1.Items.Remove(item);
}
this.time2.Text = String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now);
setguiLock(false);
}
private void setguiLock(bool value){
if(value){
this.Enabled = false;
this.button1.Enabled = false;
this.listView1.Enabled = false;
this.output.Enabled = false;
this.openoutput.Enabled = false;
this.progresslabel.Visible = true;
this.Enabled = true;
}else{
this.Enabled = false;
this.openoutput.Enabled = true;
this.output.Enabled = true;
this.listView1.Enabled = true;
this.button1.Enabled = true;
this.progresslabel.Visible = false;
this.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (!File.Exists(output.Text))
File.WriteAllText(output.Text, " ");
System.Diagnostics.Process.Start(output.Text);
}
}
}
You need to get the right tool for the job. The quantity of data and markup in a linguistic corpus like this means you need a proper XML-aware indexing solution. Examples include eXist, XAIRA, CQP...