How to build a wordlist - c#

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...

Related

Can you help me CopyFileDialog windows form

Hello I have created a program that contains a btnCopy associated with a copyfiledialog, I would like to know why when I press the btnCopy it copies me several files at the same time, I would like that it copies the files one after the other, can will you help me?
private void btnCopy_Click(object sender,EventArgs e)
{
string sourceDir = #"C:\Users\PORTABLEHP\Documents";
string destDir = #"C:\Users\PORTABLEHP\Documents\xgen";
try
{
string [] txtList = Directory.GetFiles(sourceDir,"*.txt");
foreach (string f in txtList)
{
try
{
string fName = f.Substring(sourceDir.Length + 1);
string [] files = new string[sourceDir.Length];
progressBar1.Value = 1;
progressBar1.Minimum = 0;
progressBar1.Maximum = files.Length;
for(int i = 1;i < files.Length; i++)
{
progressBar1.PerformStep();
File.Copy(Path.Combine(sourceDir,fName),
Path.Combine(destDir,fName), true);
}
}
catch(IOException copyerror)
{
MessageBox.Show(copyerror.Message)
}
,
Try this:
using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;
public partial class Form1 : Form
{
// other code
private void button1_Click(object sender, EventArgs e)
{
string sourceDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string destDir = Path.Combine(sourceDir, "xgen");
string[] txtList =
Directory.GetFiles(sourceDir, "*.txt");
progressBar1.Value = 1;
progressBar1.Minimum = 0;
progressBar1.Maximum = txtList.Length;
try
{
foreach (string f in txtList)
{
string fName = Path.GetFileName(f); //f.Substring(sourceDir.Length + 1);
string destFile = Path.Combine(destDir, fName);
FileSystem.CopyFile(
f, destFile, UIOption.AllDialogs, UICancelOption.ThrowException);
progressBar1.PerformStep();
}
}
catch (IOException copyerror)
{
MessageBox.Show(copyerror.Message);
}
}
}
Note that you need to add a reference to Microsoft.VisualBasic to gain access to FileSystem.CopyFile() which copies with the standard windows UI.

Why when searching for a string in a file it's not finding it?

I did a simple program that will search in a specific files types fro a strings but it's not finding it.
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;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace Search_Text_In_Files
{
public partial class Form1 : Form
{
StreamWriter w = new StreamWriter(#"e:\textresults.txt");
public Form1()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
bool result = false;
public List<string> FindLines(string DirName, string TextToSearch)
{
int counter = 0;
List<string> findLines = new List<string>();
DirectoryInfo di = new DirectoryInfo(DirName);
List<FileInfo> l = new List<FileInfo>();
CountFiles(di, l);
int totalFiles = l.Count;
int countFiles = 0;
if (di != null && di.Exists)
{
if (CheckFileForAccess(DirName) == true)
{
foreach (FileInfo fi in l)
{
backgroundWorker1.ReportProgress((int)((double)countFiles / totalFiles * 100.0), fi.Name);
countFiles++;
System.Threading.Thread.Sleep(1);
if (string.Compare(fi.Extension, ".cs", true) == 0)
{
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains(TextToSearch))
{
counter++;
findLines.Add(s);
result = true;
backgroundWorker1.ReportProgress(0, fi.FullName);
}
}
}
}
}
}
}
return findLines;
}
private void CountFiles(DirectoryInfo di, List<FileInfo> l)
{
try
{
l.AddRange(di.EnumerateFiles());
}
catch
{
}
try
{
IEnumerable<DirectoryInfo> subDirs = di.EnumerateDirectories();
if (subDirs.Count() > 0)
{
foreach (DirectoryInfo dir in subDirs)
CountFiles(dir, l);
}
}
catch
{
string err = "";
}
}
private bool CheckForAccess(string PathName)
{
if (File.Exists(PathName) == true)
return CheckFileForAccess(PathName);
if (Directory.Exists(PathName) == true)
return CheckFolderForAccess(PathName);
return false;
}
private bool CheckFileForAccess(string FileName)
{
FileSecurity fs = new FileSecurity(FileName, AccessControlSections.Access);
if (fs == null)
return false;
AuthorizationRuleCollection TheseRules = fs.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckFolderForAccess(string FolderName)
{
DirectoryInfo di = new DirectoryInfo(FolderName);
if (di == null)
return false;
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.Access);
if (acl == null)
return false;
AuthorizationRuleCollection TheseRules = acl.GetAccessRules(true, true, typeof(NTAccount));
if (TheseRules == null)
return false;
return CheckACL(TheseRules);
}
private bool CheckACL(AuthorizationRuleCollection TheseRules)
{
foreach (FileSystemAccessRule ThisRule in TheseRules)
{
if ((ThisRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
{
if (ThisRule.AccessControlType == AccessControlType.Deny)
return false;
}
}
return true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
FindLines(#"d:\c-sharp", "FileShellExtension");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label2.Text = e.UserState.ToString();
if (result == true)
{
listView1.Items.Add(e.UserState.ToString());
result = false;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
}
else if (e.Error != null)
{
}
else
{
}
}
}
}
In this case i'm looking for the string "FileShellExtension" in the directory d:\c-sharp and only in files ending with cs for example form1.cs
And the only result i'm getting is in this program it's finding the line as result since the string "FileShellExtension" is exist here.
FindLines(#"d:\c-sharp", "FileShellExtension");
In another project i have the string "FileShellExtension" in a form1 like this:
NameSpace FileShellExtension
But it did not find it.
What i want it to do first to pass over the result of the string being found in this program the searching program it should not be a result.
Second why it didn't find the string as part of the: NameSpace FileShellExtension ?
I suggest changing current FindLines signature into
public static IEnumerable<String> FindLines(String dirName, String textToSearch) {
if (null == dirName)
throw new ArgumentNullException("dirName");
else if (null == textToSearch)
throw new ArgumentNullException("textToSearch");
//TODO: put a right mask instead of *.txt
var files = Directory
.EnumerateFiles(dirName, "*.txt", SearchOption.AllDirectories)
.Where(file => true); //TODO: put right condition on file (now all accepted)
return files
.SelectMany(file => File.ReadLines(file))
.Where(line => line.Contains(textToSearch));
}
Then (when you've debugged the routine) you can materialize the result while adding a background worker or whatever:
public static List<String> FindLinesToList(String dirName, String textToSearch) {
List<String> result = new List<String>();
foreach (var item in FindLines(dirName, textToSearch)) {
backgroundWorker1.ReportProgress(...)
countFiles++;
...
result.Add(item);
}
}
It's far easier to debug, e.g. you can change
var files = Directory
...
into
var files = new String[#"C:\MyFile.txt"];
and test if search in the file is correct.

How do i loop for the next 25 results next page using facebook api?

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#

Field is never assigned to, and will always have its default value null (CS0649)

I've been searching for answers everywhere and I can't seem to solve mine. Anyone know a solution for this? I'm getting the following errors:
Line 25: Field 'Champion_Item_List_Downloader.MainForm.championsList' is never assigned to, and will always have its default value null (CS0649)
Line 26: Field 'Champion_Item_List_Downloader.MainForm.rolesList' is never assigned to, and will always have its default value null (CS0649)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.ComponentModel;
namespace Champion_Item_List_Downloader
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
const string listFile = "Lists.txt";
private System.Collections.Generic.List<string> championsList;
private System.Collections.Generic.List<string> rolesList;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
loadList(listFile);
}
public void loadList(string file){
try {
using (StreamReader r = new StreamReader(file))
{
string line;
bool isChamp = false;
while ((line = r.ReadLine()) != null)
{
if (line == #"[Champions]") {
isChamp = true;
}
if(line != #"[Champions]" && line != #"[Types]" && line != "")
{
if(isChamp == true){
championsList.Add(line);
} else {
rolesList.Add(line);
}
}
}
}
} catch (Exception) {
}
}
public void loadStringList(string file, List<string> list){
try {
using (StreamReader r = new StreamReader(file))
{
string line;
while ((line = r.ReadLine()) != null)
{
list.Add(line);
}
}
} catch (Exception) {
}
}
void Btn_DownloadClick(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
progressBar.Maximum = championsList.Count * rolesList.Count;
int count = 0;
progressBar.Value = 0;
string fileName = "";
string url = "";
string path = "";
foreach (string c in championsList)
{
foreach (string r in rolesList)
{
try {
fileName = c + #"_" + r + #"_scrape.json";
url = #"http://www.lolflavor.com/champions/" + c + #"/Recommended/" + fileName;
path = #"Champions\" + c + #"\Recommended\";
Directory.CreateDirectory(path);
webClient.DownloadFile(new Uri(url), path + fileName);
count++;
progressBar.Value = count;
} catch (Exception) {
}
}
}
progressBar.Value = progressBar.Maximum;
MessageBox.Show("Download completed!\n" + count.ToString() + " item lists successfully downloaded.");
}
void MainFormLoad(object sender, System.EventArgs e)
{
throw new NotImplementedException();
}
}
}
You have not initialized your lists anywhere.
Try initializing them where they are declared:
private System.Collections.Generic.List<string> championsList = new System.Collections.Generic.List<string>();
private System.Collections.Generic.List<string> rolesList = new System.Collections.Generic.List<string>();
Or within the constructor:
private System.Collections.Generic.List<string> championsList;
private System.Collections.Generic.List<string> rolesList;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
// loadList uses these lists so they should be initialized before the call to loadList to avoid a NullReferenceException.
championsList = new System.Collections.Generic.List<string>();
rolesList = new System.Collections.Generic.List<string>();
loadList(listFile);
}
Or lazily at the time they are needed:
private System.Collections.Generic.List<string> championsList;
private System.Collections.Generic.List<string> rolesList;
public void loadList(string file){
if (championsList == null) championsList = new System.Collections.Generic.List<string>();
if (rolesList == null) rolesList = new System.Collections.Generic.List<string>();
try {
using (StreamReader r = new StreamReader(file))
{
...
}
} catch (Exception) {
}
}
void Btn_DownloadClick(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
if (championsList == null) championsList = new System.Collections.Generic.List<string>();
if (rolesList == null) rolesList = new System.Collections.Generic.List<string>();
progressBar.Maximum = championsList.Count * rolesList.Count;
int count = 0;
progressBar.Value = 0;
string fileName = "";
string url = "";
string path = "";
foreach (string c in championsList)
{
foreach (string r in rolesList)
{
...
}
}
progressBar.Value = progressBar.Maximum;
MessageBox.Show("Download completed!\n" + count.ToString() + " item lists successfully downloaded.");
}
P.S. because you already have using System.Collections.Generic declared, you could write it more simply as:
private List<string> championsList = new List<string>();
private List<string> rolesList = new List<string>();
There is never a call to championsList = new System.Collections.Generic.List<string>().
Thus it's never initialized

A generic error occurred in GDI+ ExternalException Was caught cant figure out why

The error is on the line:
for (int x = 0; x < myList.Count(); x++)
The x++is painted with green.
Im using backgroundoworker and I used this code same code in another form before without a backgroundworker and it worked good. Now in the other form im using a click button event to show() this form and I want to use a progressBar1 to show the progress of the backgroundowrker work.
I used now try and catch inside this for loop and it went to the catch point and showed me the error. The full exception message is:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at mws.Animation_Radar_Preview.backGroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\Animation_Radar_Preview.cs:line 163
gifImages isnt null.
This is the full code of this form:
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;
using DannyGeneral;
using unfreez_wrapper;
namespace mws
{
public partial class Animation_Radar_Preview : Form
{
int mtpStart;
int mtpEnd;
Picturebox1_Fullscreen pb1;
string radar_images_download_directory;
string tempRadarPngToGifDirectory;
int numberOfFiles;
UnFreezWrapper unfreez;
string path_exe;
List<string> myList;
string previewDirectory;
int animatedGifSpeed;
bool loop;
string nameOfStartFile;
string nameOfEndFile;
string previewFileName;
BackgroundWorker backGroundWorker1;
Image img;
private MemoryStream _memSt = null;
public Animation_Radar_Preview()
{
InitializeComponent();
mtpStart = Picturebox1_Fullscreen.mtp1Start;
mtpEnd = Picturebox1_Fullscreen.mtp1End;
animatedGifSpeed = Picturebox1_Fullscreen.animatedSpeed;
loop = Picturebox1_Fullscreen.looping;
pb1 = new Picturebox1_Fullscreen();
radar_images_download_directory = Options_DB.Get_Radar_Images_Download_Directory();
path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
previewDirectory = path_exe + "\\" + "previewDirectory";
if (Directory.Exists(previewDirectory))
{
}
else
{
Directory.CreateDirectory(previewDirectory);
}
previewFileName = previewDirectory + "\\" + "preview.gif";
loop = false;
animatedGifSpeed = 0;
unfreez = new UnFreezWrapper();
backGroundWorker1 = new BackgroundWorker();
backGroundWorker1.WorkerSupportsCancellation = true;
this.backGroundWorker1.WorkerReportsProgress = true;
backGroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backGroundWorker1_ProgressChanged);
backGroundWorker1.DoWork += new DoWorkEventHandler(backGroundWorker1_DoWork);
backGroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backGroundWorker1_RunWorkerCompleted);
backGroundWorker1.RunWorkerAsync();
progressBar1.Value = 0;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result1;
result1 = new DialogResult();
SaveFileDialog sd = new SaveFileDialog();
sd.Title = "Select a folder to save the animated gif to";
sd.InitialDirectory = "c:\\";
sd.FileName = null;
sd.Filter = "Gif File|*.gif;*.jpg|Gif|*.gif";
sd.FilterIndex = 1;
sd.RestoreDirectory = true;
result1 = sd.ShowDialog();
string file1 = sd.FileName;
if (result1 == DialogResult.OK)
{
File.Move(previewFileName, file1);
}
}
public void pictureBoxImage(string pbImage)
{
Image img2 = null;
try
{
using (img = Image.FromFile(pbImage))
{
//get the old image thats loaded from the _memSt memorystream
//and dispose it
Image i = this.pictureBox1.Image;
this.pictureBox1.Image = null;
if (i != null)
i.Dispose();
//grab the old stream
MemoryStream m = _memSt;
//save the new image to this stream
_memSt = new MemoryStream();
img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif);
if (m != null)
m.Dispose();
//create our image to display
img2 = Image.FromStream(_memSt);
}
if (img2 != null)
pictureBox1.Image = img2;
label2.Text = numberOfFiles.ToString();
label6.Text = nameOfStartFile.ToString();
label4.Text = nameOfEndFile.ToString();
//File.Delete(pbImage);
}
catch(Exception err)
{
Logger.Write("Animation Error >>> " + err);
}
}
private void backGroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backGroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<string> myGifList;
Image gifImages = null;
//button1.Enabled = false;
Animation_Radar_Preview ap = new Animation_Radar_Preview();
//ap.FormClosing += new FormClosingEventHandler(ap_FormClosing);
FileInfo[] fi;
DirectoryInfo dir1 = new DirectoryInfo(radar_images_download_directory);
fi = dir1.GetFiles("*.png");
myList = new List<string>();
myGifList = new List<string>();
for (int i = mtpStart; i < mtpEnd; i++)
{
myList.Add(fi[i].FullName);
}
for (int x = 0; x < myList.Count(); x++)
{
try
{
gifImages = Image.FromFile(myList[x]);
gifImages.Save(tempRadarPngToGifDirectory + "\\" + x.ToString("D6") + ".Gif", System.Drawing.Imaging.ImageFormat.Gif);
}
catch (Exception ex)
{
MessageBox.Show(x.ToString() + "\r\n" + (gifImages == null).ToString() + "\r\n" + ex.Message);
}
}
myGifList = new List<string>();
dir1 = new DirectoryInfo(tempRadarPngToGifDirectory);
fi = dir1.GetFiles("*.gif");
nameOfStartFile = fi[0].Name;
for (int i = 0; i < fi.Length; i++)
{
myGifList.Add(fi[i].FullName);
//backGroundWorker1.ReportProgress(i);
nameOfEndFile = fi[i].Name.Length.ToString();
}
numberOfFiles = myGifList.Count();
unfreez.MakeGIF(myGifList, previewFileName, animatedGifSpeed, loop);
/*this.Invoke((MethodInvoker)delegate
{
pictureBoxImage(previewFileName);
});*/
}
private void backGroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pictureBoxImage(previewFileName);
}
}
}
I'm not entirely sure what is going wrong, especially as you say this same code worked previously — but it is not clear whether it worked with the same set of images.
Anyhow, the documentation for the Save method says that an ExternalException will be thrown in one of two situations:
Image was saved with the wrong format.
Image is saved to the file it was created from.
It cannot be that you are saving over the file because you are changing its extension, so it must be the wrong format. What this actually means is not clear. Perhaps one of the source images is using capabilities of the PNG format that cannot be converted to GIF, e.g. alpha channel transparency.
If I may take a moment to make some other suggestions too:
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
The empty 'success' case is not required if you invert the logic:
if (!Directory.Exists(tempRadarPngToGifDirectory)
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
Code that manipulates file paths such as the following:
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
You should consider using the Path class as this will handle the edge cases better and make more portable code:
tempRadarPngToGifDirectory = Path.Combine(path_exe, "tempRadarPngToGifDirectory");

Categories

Resources