order the events within button_Click - c#

I am trying to get events to occur one at a time within my button_Click, but for some reason everything seems to wait to run until everything is complete. For instance image changes don't occur until everything else has occured.
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = Properties.Resources.running;
iTunesAppClass itunes = new iTunesAppClass();
IITLibraryPlaylist mainLibrary = itunes.LibraryPlaylist;
IITTrackCollection ittracks = mainLibrary.Tracks;
List<string> files = new List<string>();
List<string> musicfiles = new List<string>();
List<string> badfiles = new List<string>();
List<string> songlist = new List<string>();
int state = ((int)itunes.PlayerState);
string statestring = null;
if (state < 1) { statestring = "Stopped"; };
if (state == 1) { statestring = "Playing"; };
if (state == 1)
{
do
{
label5.Text = ("Pausing iTunes to maintain file integrity");
itunes.Pause();
state = (int)itunes.PlayerState;
}
while (state == 1);
}
if (state < 1) { statestring = "Stopped"; };
if (state == 1) { statestring = "Playing"; };
if (state != 1)
{
label5.Text = "Itunes is " + statestring;
}
string[] extensions = { "*.mp3", "*.mp4", "*.m4a", "*.m4v", "*.m4p", "*.m4b", "*.flac" };
string filepath = label4.Text;
foreach (string extension in extensions)
{
this.pictureBox1.Image = Properties.Resources.running;
try
{
files.AddRange(Directory.GetFiles(filepath, extension, SearchOption.AllDirectories));
}
catch (UnauthorizedAccessException) { }
}
foreach (string file in files)
{
try { string taglibfile = TagLib.File.Create(file).Tag.Title; musicfiles.Add(file); Console.WriteLine(taglibfile); }
catch { badfiles.Add(file); }
}
XDocument baddoc = new XDocument
(new XElement("Corrupt",
badfiles.Select(badfile =>
new XElement("File", badfile))));
baddoc.Save(label4.Text + "\\badfiles.xml");
// foreach(string musicfile in musicfiles)
//{ String Title = (TagLib.File.Create(musicfile).Tag.Title); }
this.pictureBox1.Image = Properties.Resources.skinitunes;
}

Related

How to prevent it from being added 2 times in listview

I ama getting data from news website with webrequest and show my listview. When user click button , first of all I am getting all news and show my listview, after e.g 15 min user click button again. I am checking my news list if news is exits, I am showing messagebox "There is no fresh news". but if there is a news put all news list in listview again. For example. first lisview count is 75 . and there is 2 fresh news, normally my listview should 77. but listview shows 152. Where is my mistake. can you help me ?
my button click event
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
foreach (var item in list)
{
listView1.Items.Add(item);
}
}
this is my class
public static Dictionary<string, Hurriyet> HurriyetHaberList = new Dictionary<string, Hurriyet>();
public List<ListViewItem> GetTagsHurriyet()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://www.hurriyet.com.tr/rss/gundem");
XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");
if (el != null)
{
el.ParentNode.RemoveChild(el);
}
XmlNode Haberler = el.SelectSingleNode("channel");
List<ListViewItem> listViewItems = new List<ListViewItem>();
bool degismiMi = false;
foreach (XmlNode haber in Haberler.SelectNodes("item"))
{
Hurriyet h = new Hurriyet();
ListViewItem li = new ListViewItem();
//li.Text = haber.SelectSingleNode("title").InnerText;
h.Title = haber.SelectSingleNode("title").InnerText;
if (haber.SelectSingleNode("description").InnerText.Contains(">"))
{
var str1 = haber.SelectSingleNode("description").InnerText.IndexOf(">");
var str2 = haber.SelectSingleNode("description").InnerText.Substring(str1 + 4);
//li.SubItems.Add(str2);
}
else
{
//li.SubItems.Add(haber.SelectSingleNode("description").InnerText);
h.Description = haber.SelectSingleNode("description").InnerText;
}
h.Link = haber.SelectSingleNode("link").InnerText;
//li.SubItems.Add(haber.SelectSingleNode("link").InnerText);
var format = DateTime.Parse(haber.SelectSingleNode("pubDate").InnerText.ToString());
//li.SubItems.Add(format.ToString());
h.PubDate = format;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(haber.SelectSingleNode("link").InnerText);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string final_response = stream.ReadToEnd();
string begenningKeyword = "<meta name=\"keywords\" content=\"";
var tags = final_response.IndexOf(begenningKeyword);
var final_response2 = final_response.Substring(tags + begenningKeyword.Length);
var tagsBol = final_response2.IndexOf("\" />");
var lastTags = final_response2.Substring(0, tagsBol);
int yer1;
if (lastTags != string.Empty)
{
h.Tags = lastTags;
//li.SubItems.Add(lastTags);
}
else
{
yer1 = final_response.IndexOf("tagsContainer");
if (yer1 == -1)
{
continue;
}
else
{
yer1 = final_response.IndexOf("tagsContainer");
int yer2 = final_response.IndexOf("</div>", yer1);
var tagDiv = final_response.Substring(yer1, yer2 - yer1);
List<string> listele = new List<string>();
for (int i = 0; i < tagDiv.Length; i++)
{
var firstSpan = tagDiv.IndexOf("<span>");
var firstSpan2 = tagDiv.IndexOf("<span itemprop=\"keywords\">");
if (firstSpan != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan);
var lastSpan = tagDiv.Substring(firstSpan, secondSpan - firstSpan);
var remo = lastSpan.Replace("<span>", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else if (firstSpan2 != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan2);
var lastSpan = tagDiv.Substring(firstSpan2, secondSpan - firstSpan2);
var remo = lastSpan.Replace("<span itemprop=\"keywords\">", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else
break;
}
string c = string.Empty;
foreach (var item in listele)
{
c += item + ",";
}
//li.SubItems.Add(c.Substring(0, c.Length - 1));
h.Tags = c.Substring(0, c.Length - 1);
}
}
if (HurriyetHaberList.ContainsKey(haber.SelectSingleNode("link").InnerText) == false)
{
HurriyetHaberList.Add(haber.SelectSingleNode("link").InnerText, h);
degismiMi = true;
//listViewItems.Insert(0,li);
}
}
if (!degismiMi)
{
MessageBox.Show("Haberlerde değişiklik olmadı");
}
else
{
listViewItems.Clear();
foreach (var item in HurriyetHaberList.OrderByDescending(x => x.Value.PubDate).ToList())
{
ListViewItem lstItem = new ListViewItem();
lstItem.Text = item.Value.Title;
lstItem.SubItems.Add(item.Value.Description);
lstItem.SubItems.Add(item.Value.Link);
lstItem.SubItems.Add(item.Value.PubDate.ToString());
lstItem.SubItems.Add(item.Value.Tags);
listViewItems.Add(lstItem);
}
}
return listViewItems;
}
Screenshot
The problem is that your code
hurriyet.GetTagsHurriyet();
Delivers all 77 Items and this result is than added to your list Control with the below code
foreach (var item in list)
{
listView1.Items.Add(item);
}
You need to clear your listView1 or make sure that the method GetTagsHurriyet() only returns new items.
So either do the following:
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
listView1.Items.Clear(); //<-- added line
foreach (var item in list)
{
listView1.Items.Add(item);
}
}
Or in your GetTagsHurriyet() method only fill the list if your dictionary says it is new:
if (HurriyetHaberList.ContainsKey(haber.SelectSingleNode("link").InnerText) == false)
{
HurriyetHaberList.Add(haber.SelectSingleNode("link").InnerText, h);
degismiMi = true;
//listViewItems.Insert(0,li);
//add items to listViewItems here and drop the code below
}
Edit:
Based on the comment below:
Something like this:
(Didnt test the code, removed some comments to make it smaller also changed some stuff here and there)
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
if (!list.Any())
MessageBox.Show("Haberlerde değişiklik olmadı");
else
{
foreach (var item in list)
listView1.Items.Add(item);
}
}
public static Dictionary<string, Hurriyet> HurriyetHaberList = new Dictionary<string, Hurriyet>();
public List<ListViewItem> GetTagsHurriyet()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://www.hurriyet.com.tr/rss/gundem");
XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");
if (el != null)
el.ParentNode.RemoveChild(el);
XmlNode Haberler = el.SelectSingleNode("channel");
List<Hurriyet> newHurriyets = new List<Hurriyet>();
bool degismiMi = false;
foreach (XmlNode haber in Haberler.SelectNodes("item"))
{
var link = haber.SelectSingleNode("link").InnerText;
if (HurriyetHaberList.ContainsKey(link))
continue;
Hurriyet h = new Hurriyet();
h.Title = haber.SelectSingleNode("title").InnerText;
if (!haber.SelectSingleNode("description").InnerText.Contains(">"))
h.Description = haber.SelectSingleNode("description").InnerText;
h.Link = link;
var format = DateTime.Parse(haber.SelectSingleNode("pubDate").InnerText.ToString());
h.PubDate = format;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string final_response = stream.ReadToEnd();
string begenningKeyword = "<meta name=\"keywords\" content=\"";
var tags = final_response.IndexOf(begenningKeyword);
var final_response2 = final_response.Substring(tags + begenningKeyword.Length);
var tagsBol = final_response2.IndexOf("\" />");
var lastTags = final_response2.Substring(0, tagsBol);
int yer1;
if (!string.IsNullOrEmpty(lastTags))
h.Tags = lastTags;
else
{
yer1 = final_response.IndexOf("tagsContainer");
if (yer1 == -1)
continue;
yer1 = final_response.IndexOf("tagsContainer");
int yer2 = final_response.IndexOf("</div>", yer1);
var tagDiv = final_response.Substring(yer1, yer2 - yer1);
List<string> listele = new List<string>();
for (int i = 0; i < tagDiv.Length; i++)
{
var firstSpan = tagDiv.IndexOf("<span>");
var firstSpan2 = tagDiv.IndexOf("<span itemprop=\"keywords\">");
if (firstSpan != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan);
var lastSpan = tagDiv.Substring(firstSpan, secondSpan - firstSpan);
var remo = lastSpan.Replace("<span>", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else if (firstSpan2 != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan2);
var lastSpan = tagDiv.Substring(firstSpan2, secondSpan - firstSpan2);
var remo = lastSpan.Replace("<span itemprop=\"keywords\">", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else
break;
}
h.Tags = string.Join(",", listele);
}
}
HurriyetHaberList.Add(link, h);
newHurriyets.Add(h);
}
List<ListViewItem> listViewItems = new List<ListViewItem>();
foreach (var item in newHurriyets.OrderByDescending(x => x.PubDate))
{
ListViewItem lstItem = new ListViewItem();
lstItem.Text = item.Title;
lstItem.SubItems.Add(item.Description);
lstItem.SubItems.Add(item.Link);
lstItem.SubItems.Add(item.PubDate.ToString());
lstItem.SubItems.Add(item.Tags);
listViewItems.Add(lstItem);
}
return listViewItems;
}
You can clear items before filling:
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
listView1.Items.Clear(); // Clear items
foreach (var item in list)
{
listView1.Items.Add(item);
}
}
otherwise you would have to check if listView1 does not have item you want to add (not by reference, maybe some property?). This case however will not handle deleting items
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
foreach (var item in list)
{
if(!IsItemPresent(item)) // You should implement this method somehow
listView1.Items.Add(item);
}
}
listView1 should clear before u add new items. becose their was old data.
put this code listView1.Clear(); before start loop.
listView1.Clear();
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
listView1.Clear();
foreach (var item in list)
{
listView1.Items.Add(item);
}
}

"An error occurred while updating the entries."

I get this error from my code:
{"An error occurred while updating the entries. See the inner exception for details."}
I see the inner exception and:
{"Parameter value '99999,999' is out of range."}
but when i upload only one archive he is fine, and when i upload more than one archive he throws the exception.
This is my code:
private void ProcessarCEP(int i,FileInfo file,string [] Lines)
{
string vNomeArquivo = string.Empty;
DBCEPEntities DBCEP = new DBCEPEntities();
DirectoryInfo info = new DirectoryInfo(file.DirectoryName);
FileInfo[] files = info.GetFiles("*.txt", SearchOption.AllDirectories);
int vTamanhoBase = DBCEP.CAD_CEP.Where(t => t.UF == file.Name.Substring(15,2)).Count();
for (int a = vTamanhoBase; a < i + vTamanhoBase; a++)
{
if (a >= Lines.Count()) break;
CAD_CEP CEP = new CAD_CEP();
string[] Registros = Lines[a].Split('#');
CEP.CEP = Convert.ToDecimal(Registros[7]);
CEP.UF = Registros[1];
CEP.LOGRADOURO = Registros[8];
CEP.ENDERECO = Registros[5];
if (Registros[2] != string.Empty)
{
decimal CodLocal = Convert.ToDecimal(Registros[2]);
var local = DBCEP.CAD_CIDADE.Where(c => c.CODLOCAL == CodLocal).FirstOrDefault();
CEP.LOCAL = local.LOCAL;
}
if (Registros[3] != string.Empty)
{
decimal CodBairro = Convert.ToDecimal(Registros[3]);
var bairro = DBCEP.CAD_BAIRRO.Where(c => c.CODBAIRRO == CodBairro).FirstOrDefault();
CEP.BAIRRO = bairro.BAIRRO;
}
vNomeArquivo = ConfigurationManager.AppSettings["NomeArquivoSequencia"].ToString();
if (files.Where(f => f.Name.ToUpper() == vNomeArquivo.ToUpper()).Count() > 0)
{
if (Registros[0] != string.Empty)
{
string[] LinesSec = File.ReadAllLines(files.Where(f => f.Name.ToUpper().StartsWith(vNomeArquivo.ToUpper())).FirstOrDefault().FullName.ToString(), Encoding.Default);
string vLinhaSec = LinesSec.Where(l => l.StartsWith(Registros[0] + "#")).FirstOrDefault();
if (vLinhaSec != null)
{
string[] vLinhaSplit = vLinhaSec.Split('#');
if (vLinhaSplit[1] != string.Empty)
{
CEP.DE = Convert.ToDecimal(vLinhaSplit[1]);
}
if (vLinhaSplit[2] != string.Empty)
{
CEP.ATE = Convert.ToDecimal(vLinhaSplit[2]);
}
CEP.FL_PAR_IMPAR = vLinhaSplit[3];
}
Registros = null;
LinesSec = null;
}
}
DBCEP.CAD_CEP.Add(CEP);
}
DBCEP.SaveChanges();
vTamanhoBase = DBCEP.CAD_CEP.Where(t => t.UF == file.Name.Substring(15, 2)).Count();
DBCEP.Dispose();
GC.WaitForPendingFinalizers();
GC.Collect();
if (Lines.Count() <= i + vTamanhoBase)
{
if(vTamanhoBase != Lines.Count())
{
ProcessarCEP(Lines.Count() - i, file, Lines);
}
}
else
{
if(vTamanhoBase != Lines.Count())
{
ProcessarCEP(i, file, Lines);
}
}
}

Is that necessary to dispose objects inside static functions?

Ok i am having a major problem atm.
My software is using extremely high amount of ram. I am using a lot of HtmlAgilityPack.HtmlDocument objects with big size pages sources.
However all of the objects are used inside static functions and HtmlAgilityPack.HtmlDocument isn't IDisposable
So do i need to set every variable explicitly to null ?
Even if they are inside static functions ?
For example do i need to set these variables to null at the end of the function below
The variables i am asking : lstDrwList ? Or since it is inside it will get disposed automatically ?
Should i call explicitly garbage collector ?
C# .net 4.5 WPF application
private static void func_CheckWaitingToProcessPages(Object state)
{
ParallelOptions myOptions = new ParallelOptions();
myOptions.MaxDegreeOfParallelism = PublicSettings.ir_How_Many_Tasks_For_Per_Pages_Process;
List<DataRow> lstDrwList = new List<DataRow>();
using (DataTable dtMyTable = DbConnection.db_Select_DataTable(srSelectTopProcessPagesQuery))
{
foreach (DataRow drw in dtMyTable.Rows)
{
lstDrwList.Add(drw);
}
}
Parallel.ForEach(lstDrwList, myOptions, drw =>
{
process_Given_Page(drw);
});
}
The problem is found issue is how to fix
Here the problem this happens in 10 seconds i used visual studio profiler
Here the full class that causes this huge memory leak issue
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace doktora_tez_projesi_crawler_program
{
public static class PagesProcessor
{
private static Timer _timer;
private static int howManySeconds = 10;
public static void func_StartCrawlingWaitingUrls()
{
PublicStaticFunctions.AddMsgToEvents("Checking waiting to process crawled urls process started every " + howManySeconds + " seconds!");
_timer = new Timer(func_CheckWaitingToProcessPages, null, PublicSettings.irTimers_Delayed_Start_MiliSeconds, howManySeconds * 1000);
}
private static string srSelectTopProcessPagesQuery = " select top 100 cl_IdUrl,cl_RooSiteId,cl_CrawlSource,cl_CrawlOrgUrl from tblCrawlUrls " +
" where cl_PageProcessed=0 and cl_TotalCrawlTimes > 0 " +
" order by cl_LastProcessDate asc";
private static void func_CheckWaitingToProcessPages(Object state)
{
ParallelOptions myOptions = new ParallelOptions();
myOptions.MaxDegreeOfParallelism = PublicSettings.ir_How_Many_Tasks_For_Per_Pages_Process;
List<DataRow> lstDrwList = new List<DataRow>();
using (DataTable dtMyTable = DbConnection.db_Select_DataTable(srSelectTopProcessPagesQuery))
{
foreach (DataRow drw in dtMyTable.Rows)
{
lstDrwList.Add(drw);
}
}
Parallel.ForEach(lstDrwList, myOptions, drw =>
{
process_Given_Page(drw);
});
}
private class csProductFeatures
{
public string srProductRootSiteId = "null", srProductTitle = "null", srProductCode = "null", srProductImageLink = "null";
public string srProductDetailedExplanation = "null", srProductFeatures = "null", srCrawledOrgUrl = "null", srProductIdCode = "null";
public bool blPossibleProductPage = false, blFreeCargo = false, blProductPage = true;
public List<string> lstProductCategories = new List<string>();
public int irProductPrice = 0;
public List<csProductComments> lstProductComments = new List<csProductComments>();
public List<KeyValuePair<string, string>> lstProductFeatures = new List<KeyValuePair<string, string>>();
}
private class csProductComments
{
public string srCommentTitle = "null", srCommentPros = "null", srCommentCons = "null";
public int irCommentScore = 0; //0 = negative 5=full star
}
private static void process_Given_Page(DataRow drw)
{
csProductFeatures temp_ProductFeatures = new csProductFeatures();
temp_ProductFeatures.srProductRootSiteId = drw["cl_RooSiteId"].ToString();
temp_ProductFeatures.srCrawledOrgUrl = drw["cl_CrawlOrgUrl"].ToString();
HtmlDocument hdMyDoc = new HtmlDocument();//nulled
hdMyDoc.LoadHtml(drw["cl_CrawlSource"].ToString());
bool blBreakLoop = false;
foreach (var vrVariable in PublicVariables.dicRootSites[temp_ProductFeatures.srProductRootSiteId].lstRootSiteIdentifiers)
{
if (vrVariable.srHtmlObjectType != "link")
{
HtmlNodeCollection hdNodes;
if (vrVariable.blSelectMultipleNodes == false)
hdNodes = hdMyDoc.DocumentNode.SelectNodes(string.Format("//{0}[#{1}='{2}']", vrVariable.srHtmlObjectType,
vrVariable.srHtmlObjectTypeIdentifier, vrVariable.srHtmlObjectTypeName));
else
hdNodes = hdMyDoc.DocumentNode.SelectNodes(string.Format("//{0}[#{1}='{2}']//{3}", vrVariable.srHtmlObjectType,
vrVariable.srHtmlObjectTypeIdentifier, vrVariable.srHtmlObjectTypeName, vrVariable.srHtmlSubIdentifierType));
if (hdNodes == null && vrVariable.srIndetifierType == "ProductTitle")
{
blBreakLoop = true;
temp_ProductFeatures.blProductPage = false;
continue;
}
if (blBreakLoop == true)
break;
if (hdNodes == null)
continue;
string sr_Node_Required_Val = "null";
if (hdNodes[0].InnerText != null)
sr_Node_Required_Val = hdNodes[0].InnerText;
string srLinkVal = "null";
if (vrVariable.srHtmlObjectType == "a" && hdNodes[0].Attributes != null)
{
if (hdNodes[0].Attributes["href"] != null)
{
srLinkVal = PublicStaticFunctions.Return_Absolute_Url(hdNodes[0].Attributes["href"].Value, temp_ProductFeatures.srCrawledOrgUrl);
}
}
if (vrVariable.blGetValue == true)
{
if (hdNodes[0].Attributes != null)
if (hdNodes[0].Attributes["value"] != null)
sr_Node_Required_Val = hdNodes[0].Attributes["value"].Value;
}
sr_Node_Required_Val = sr_Node_Required_Val.Trim();
switch (vrVariable.srIndetifierType)
{
case "ProductPage":
temp_ProductFeatures.blPossibleProductPage = true;
break;
case "ProductTitle":
temp_ProductFeatures.srProductTitle = sr_Node_Required_Val;
break;
case "ProductCode":
temp_ProductFeatures.srProductCode = sr_Node_Required_Val;
break;
case "ProductCargo":
temp_ProductFeatures.blFreeCargo = true;
break;
case "ProductCategories":
temp_ProductFeatures.lstProductCategories = func_Return_Product_Categories(hdNodes);
break;
case "ProductPrice":
temp_ProductFeatures.irProductPrice = func_Return_Product_Price(sr_Node_Required_Val, temp_ProductFeatures.srProductRootSiteId);
break;
case "ProductImage":
temp_ProductFeatures.srProductImageLink = srLinkVal;
break;
case "ProductIdCode":
temp_ProductFeatures.srProductIdCode = sr_Node_Required_Val;
break;
}
}
if (vrVariable.srHtmlObjectType == "link")
{
string srLinkToFetch = vrVariable.srHtmlObjectTypeIdentifier;
if (vrVariable.blUsesProductIdCode == true)
{
srLinkToFetch = string.Format(srLinkToFetch, temp_ProductFeatures.srProductIdCode);
}
string srFetchResult = CrawlGivenUrl.func_fetch_Page(srLinkToFetch);
string srResultToAssign = "null";
if (srFetchResult == PublicSettings.srCrawlFailedMessage)
{
srResultToAssign = srFetchResult;
}
else
{
HtmlDocument temp_HdDocument = new HtmlDocument();//nulled
temp_HdDocument.LoadHtml(srFetchResult);
if (temp_HdDocument.DocumentNode != null)
if (temp_HdDocument.DocumentNode.InnerText != null)
srResultToAssign = temp_HdDocument.DocumentNode.InnerText;
temp_HdDocument = null;
}
switch (vrVariable.srIndetifierType)
{
case "ProductExplanation":
temp_ProductFeatures.srProductDetailedExplanation = srResultToAssign;
break;
case "ProductFeatures":
temp_ProductFeatures.lstProductFeatures = func_Return_Product_Features(temp_ProductFeatures.srProductRootSiteId, srFetchResult, temp_ProductFeatures.srCrawledOrgUrl);
break;
}
}
}
if (temp_ProductFeatures.blProductPage == true)
{
string asdas = "";
}
hdMyDoc = null;
}
private static List<string> func_Return_Product_Categories(HtmlNodeCollection hdNodeCollection)
{
List<string> lstCategories = new List<string> { };
foreach (HtmlNode hdNode in hdNodeCollection)
{
if (hdNode.InnerText != null)
{
lstCategories.Add(hdNode.InnerText);
}
}
return lstCategories;
}
private static int func_Return_Product_Price(string srPriceText, string srRootSiteId)
{
int irPrice = 0;
srPriceText = srPriceText.Replace(PublicVariables.dicRootSites[srRootSiteId].srPriceDelimeter, "");
if (srPriceText.Contains(PublicVariables.dicRootSites[srRootSiteId].srPriceIgnoreDelimeter) == true)
{
srPriceText = srPriceText.Substring(0, srPriceText.IndexOf(PublicVariables.dicRootSites[srRootSiteId].srPriceIgnoreDelimeter));
}
Int32.TryParse(srPriceText, out irPrice);
return irPrice;
}
private static List<KeyValuePair<string, string>> func_Return_Product_Features(string srRootSiteId, string srPageSource, string srCrawlUrl)
{
List<KeyValuePair<string, string>> lstFoundFeatures = new List<KeyValuePair<string, string>>();
if (srPageSource == PublicSettings.srCrawlFailedMessage)
return lstFoundFeatures;
HtmlDocument temp_HdDocument = new HtmlDocument();//nulled
temp_HdDocument.LoadHtml(srPageSource);
List<string> lstFeatureTitles = new List<string>();
List<string> lstFeatureDescriptions = new List<string>();
foreach (var vrVariable in PublicVariables.dicRootSites[srRootSiteId].lstRootSitesFeaturesIdentifiers)
{
if (vrVariable.blPerFeatureIdentifier == true)
{
HtmlNodeCollection hdNodes = temp_HdDocument.DocumentNode.SelectNodes(string.Format("//{0}[#{1}='{2}']", vrVariable.srHtmlObjectType,
vrVariable.srHtmlObjectIdentifier, vrVariable.srHtmlObjectIdentifierName));
if (hdNodes != null)
foreach (var vrNewVariable in PublicVariables.dicRootSites[srRootSiteId].lstRootSitesFeaturesIdentifiers)
{
if (vrNewVariable.blPerFeatureIdentifier == false)
{
foreach (HtmlNode hdTempNode in hdNodes)
{
var vrTempNewNode = hdTempNode.SelectSingleNode(string.Format("//{0}[#{1}='{2}']", vrVariable.srHtmlObjectType,
vrVariable.srHtmlObjectIdentifier, vrVariable.srHtmlObjectIdentifierName));
if (vrTempNewNode != null)
if (vrTempNewNode.InnerText != null)
{
string srNodeFeature = vrTempNewNode.InnerText.Trim();
switch (vrVariable.srWhichFeatureIdentifier)
{
case "FeatureTitle":
lstFeatureTitles.Add(srNodeFeature);
break;
case "FeatureDescription":
lstFeatureDescriptions.Add(srNodeFeature);
break;
}
}
}
}
}
break;
}
}
temp_HdDocument = null;
if (lstFeatureDescriptions.Count != lstFeatureTitles.Count)
{
ErrorLogger.LogError("found features count not equal to features description count crawled url: " + srCrawlUrl);
return lstFoundFeatures;
}
for (int i = 0; i < lstFeatureDescriptions.Count; i++)
{
KeyValuePair<string, string> myKeyValPair = new KeyValuePair<string, string>(lstFeatureTitles[i], lstFeatureDescriptions[i]);
lstFoundFeatures.Add(myKeyValPair);
}
return lstFoundFeatures;
}
}
}
No, you don't need to set variables to null in both static and instance methods. The variables inside a method (even inside static method) are on the stack space of the method, so generally they will go out of scope at the end of method execution and will be targeted for garbage collection. And Generally explicitly calling the garbage collector isn't a good practice.

Add to an arraylist from different arraylist index

I have two array lists one in which I read in values from an XML, and then I add a specific tag to a listbox. From the listbox I transfer over the tag to another listbox, but the problem I am having is when trying to get the values of the selected item in the listbox in array1 to move over to array2.
How can I do this and make sure all things saved in the current index of arraylist1 move to arraylist2?
//Initialisation
int moduleCount = 0;
bool isFull = false;
ArrayList chosen= new ArrayList();
ArrayList module = new ArrayList();
String name;
String code;
String info;
String semester;
String tSlot;
String lSlot;
String preReq;
string xmlDirectory = Directory.GetCurrentDirectory();
public Form1()
{
InitializeComponent();
createBox();
//List<Array> a=new List<Array>();
// Console.WriteLine(module.ToString());
// getXML();
}
private void createBox()
{
String workingDir = Directory.GetCurrentDirectory();
XmlTextReader textReader = new XmlTextReader(workingDir + #"\XML.xml");
textReader.Read();
XmlNodeType type;
while (textReader.Read())
{
textReader.MoveToElement();
type = textReader.NodeType;
if (type == XmlNodeType.Element)
{
if (textReader.Name == "Code")
{
textReader.Read();
code = textReader.Value;
Console.WriteLine(code);
}
if (textReader.Name == "Name")
{
textReader.Read();
name = textReader.Value;
//selectionBox.Items.Add(name);
Console.WriteLine(name);
}
if (textReader.Name == "Semester")
{
textReader.Read();
semester = textReader.Value;
Console.WriteLine(semester);
}
if (textReader.Name == "Prerequisite")
{
textReader.Read();
preReq = textReader.Value;
Console.WriteLine(code);
}
if (textReader.Name == "LectureSlot")
{
textReader.Read();
lSlot = textReader.Value;
Console.WriteLine(lSlot);
}
if (textReader.Name == "TutorialSlot")
{
textReader.Read();
tSlot = textReader.Value;
Console.WriteLine(tSlot);
}
if (textReader.Name == "Info")
{
textReader.Read();
info = textReader.Value;
Console.WriteLine(info);
module.Add(new Modules(code, name, semester, tSlot, lSlot, info, preReq));
}
}
//Console.WriteLine(module);
}
foreach (object o in module)
{
Modules m = (Modules)o;
//String hold = m.mName;
selectionBox.Items.Add(m.mName);
}
textReader.Close();
//button event handler to move from one listbox to the other
if (selectionBox.SelectedItem != null)
{
chosenBox.Items.Add(selectionBox.SelectedItem);
selectionBox.Items.Remove(selectionBox.SelectedItem);
chosen.Add(selectionBox.SelectedItem);
errorLabel.Text = "";
moduleCount++;
if (moduleCount >= 8)
{
isFull = true;
errorLabel.Text = "You have selected 8 Modules please fill the fields and submit";
selectionBox.Enabled = false;
}
}
else
{
errorLabel.Text = "Please select a module";
}
numberChosen.Text = String.Format(moduleCount.ToString());
//Write to XML
foreach (object o in chosen)
{
Modules m = (Modules)o;
if (m.mPreReq != "None")
{
MessageBox.Show("You must chose module " + m.mPreReq);
//errorLabel.Text = "You must chose module " + m.mPreReq;
errorLabel.Text = "There is a prereq course";
req = true;
}
}
Ok it seems like you need to relate m.mName that you add to selectionBox to the actual Module you added to the module ArrayList so that you can add the members of that module to the chosen ArrayList later on. Something like:
if (selectionBox.SelectedItem != null)
{
chosenBox.Items.Add(selectionBox.SelectedItem);
selectionBox.Items.Remove(selectionBox.SelectedItem);
foreach (Module m in module)
{
if (m.Name.Equals(selectionBox.SelectedItem)
{
chosen.Add(m.Info);
chosen.Add(m.Code);
...
break;
}
}
errorLabel.Text = "";
moduleCount++;
if (moduleCount >= 8)
{
isFull = true;
errorLabel.Text = "You have selected 8 Modules please fill the fields and submit";
selectionBox.Enabled = false;
}
else
{
errorLabel.Text = "Please select a module";
}
}
numberChosen.Text = String.Format(moduleCount.ToString());

Read File and display contents

I want that when I click the button "List all Customers", the code should read the Customer.csv file and display the information on the form called "List All Customers".
How can I do that?
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
int count = 0;
using (StreamReader sr = File.OpenText(#"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
Customer tempCust = new Customer();
tempCust.customerName = lineHolder[0];
tempCust.customerAddress = lineHolder[1];
tempCust.customerZip = Convert.ToInt32(lineHolder[2]);
myCustArray[count] = tempCust;
count++;
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
I'm not sure what kind of control you want to display this data in but your method could just return a list of Customer, then you can add to a ListBox, ListView or DataGrid
public static IEnumerable<Customer> LoadCustomers(string filename)
{
if (File.Exists(filename))
{
foreach (var line in File.ReadAllLines(filename).Where(l => l.Contains(',')))
{
var splitLine = line.Split(',');
if (splitLine.Count() >= 3)
{
yield return new Customer
{
customerName = splitLine[0].Trim(),
customerAddress = splitLine[1].Trim(),
customerZip = Convert.ToInt32(splitLine[2].Trim())
};
}
}
}
}
ListBox
listBox1.DisplayMember = "customerName";
listBox1.Items.AddRange(LoadCustomers(#"G:\Customers.csv").ToArray());
First, take advantage of the list object:
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
var retList = new List<Customer>();
using (StreamReader sr = File.OpenText(#"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
retlist.add(new Customer(){
customerName = linerHolder[0],
customerAddress = lineHolder[1],
customerZip = Convert.ToInt32(lineHolder[2])
});
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
just wrap it up in a class, call if from the controller and populate up the results. Depending on how often you will be updating this data, you might look into caching it, so you don't have to run this process every X seconds for each user.

Categories