How to limit the amount of parameters for concatenatenation? - c#

The idea of the program is to concatenate different parameters and put it all inside another parameter. How to let the end user decide if he wants to concatenate 2 or 3 parameters. Right now it is like if you don't put in 3 parameters it won't work. Nothing I came up with works.
namespace CombineParametersWinForm
{
public partial class Form1 : System.Windows.Forms.Form
{
//Class variable
Document revitDoc { get; set; }
public Form1(Document doc)
{
InitializeComponent();
this.revitDoc = doc;
//Create a list of the parameters you want your user to choose from
List<string> stringParameters = new List<string>
{
"Weight",
"Angle",
"Manufacturer"
};
//Add list to comboboxes on form
foreach (string parameterName in stringParameters)
{
comboBox1.Items.Insert(0, parameterName);
comboBox2.Items.Insert(0, parameterName);
comboBox3.Items.Insert(0, parameterName);
}
}
private void button1_Click(object sender, EventArgs e)
{
FilteredElementCollector collector = new FilteredElementCollector(revitDoc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting);
//Applying Filter
IList<Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
foreach (Element duct in ducts)
{
//Get Parameter values
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsValueString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsValueString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsValueString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
//do not need .ToString() when setting parameter
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}
Ideas. First is pretty long one.
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsValueString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsValueString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsValueString();
if (parameterValue1 != "" || parameterValue1 != null)
{
parameterValue1 = parameterValue11;
}
if (parameterValue2 != "" || parameterValue2 != null)
{
parameterValue1 = parameterValue22;
}
if (parameterValue3 != "" || parameterValue3 != null)
{
parameterValue3 = parameterValue33;
}
if (parameterValue1 == "" || parameterValue1 == null)
{
parameterValue11 = "";
}
if (parameterValue2 == "" || parameterValue2 == null)
{
parameterValue22 = "";
}
if (parameterValue3 == "" || parameterValue3 == null)
{
parameterValue33 = "";
}
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}
}
}
}
}
Second is a short one but still doesn't work
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsValueString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsValueString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsValueString();
List<string> listParam = new List<string> { parameterValue1, parameterValue2, parameterValue3 };
foreach (string s in listParam)
{
if (s != "" /*&& s != null*/)
{
List<string> listParamNotNull = new List<string> { s };
string newValue = String.Join(" ,", listParamNotNull);
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}

You are creating three separate Lists and wanting to do something against all of them combined, but actually doing against each of them individually, overwriting as you go.
Please take a closer look at your nested logic.
Something like this is likely more appropriate:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string parameterValue1 = "Value1";
string parameterValue2 = ""; // purposefully providing an empty value
string parameterValue3 = "Value3";
var listParamIn = new List<string> { parameterValue1, parameterValue2, parameterValue3 };
var listParamOut = new List<string>();
foreach (string s in listParamIn){
if (string.IsNullOrEmpty(s))
continue;
listParamOut.Add(s);
}
string newValue = String.Join(", ", listParamOut);
Console.WriteLine(newValue);
/* continue with your transaction
using (Transaction t = new Transaction(revitDoc, "Set Parameter name")){
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}
*/
}
}
Output:
Value1, Value3
See:
https://dotnetfiddle.net/mXdL5F

Related

Error in displaying the List of programs from database

Here i am trying to show the list of programs from database in my list.cshtml. I am not able to get the list of programs.
Suggest me if there is any wrong in code. I am facing issue in cacheUtilities as ArgumentNullException. someone help me with the code issue to get the list of programs from database.
Controller Code
[HttpGet]
[Authorize(Roles = "Affiliate")]
public ActionResult GetTrainingPrograms(int? affiliateId, string searchStr, bool? active, string sort, int? start, int? limit)
{
int affId = UserData.AffiliateID;
if (affiliateId != null && affiliateId.Value > 0)
{
affId = affiliateId.Value;
}
string searchStrLower = string.Empty;
string queryStr = String.Concat(affId);
// The start point in the list of Training Programs
if (start != null)
{
queryStr = String.Concat(queryStr, "-", start.Value);
}
// To find Active or Inactive at the Current Time
if (active != null)
{
queryStr = String.Concat(queryStr, "-", active);
}
// Sort the List of Data
if (sort == null)
{
sort = "trainingProgramName";
}
queryStr = String.Concat(queryStr, "-", sort);
// limit on the page to Display
if (limit != null)
{
queryStr = String.Concat(queryStr, "-", limit.Value);
}
//The keywords used to find a Training Program
if (!string.IsNullOrEmpty(searchStr))
{
searchStrLower = searchStr.ToLower();
queryStr = String.Concat(queryStr, "-", searchStrLower);
}
logger.Debug("trainingProgramListKey: " + queryStr);
TrainingProgramList reloadData = CacheUtilities.Instance.GetTrainingProgramList(affiliateId);
logger.Debug("reloadData: " + reloadData + ", affId: " + affId + ", queryStr: " + queryStr);
string trainingProgramCacheKey = CbConstants.TrainingProgramCacheKey + queryStr;
TrainingProgramList trainingProgramList = null;
int totalCount = 0;
// Checks the List is null or not to Display
if (trainingProgramList != null)
{
logger.Debug("Cache miss for TrainingProgram list: " + trainingProgramCacheKey);
trainingProgramList = new TrainingProgramList();
trainingProgramList.AffiliateID = affId;
totalCount = TrainingProgramRepository.Instance.GetTrainingProgramsCount(affId, searchStrLower, active);
trainingProgramList.Entries = TrainingProgramRepository.Instance.GetTrainingPrograms(affId, searchStrLower, active, sort, start, limit);
HttpRuntime.Cache.Insert(trainingProgramCacheKey, trainingProgramList, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationOneDay);
}
CbJsonResponse response = new CbJsonResponse();
response.Data.Add(trainingProgramList);
response.Status = "success";
response.Meta.Add("total", Convert.ToString(totalCount));
return Json(response, "application/json", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
}
}
Repository Code:
public List<TrainingProgramListEntry> GetTrainingPrograms(int affiliateId, string searchStr, bool? active, string sort, int? start, int? limit)
{
using (var ctx = new CrossfitPortalEntities())
{
ctx.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
// Don't need proxies when explicitly loading.
ctx.Configuration.ProxyCreationEnabled = false;
var query = ctx.TrainingPrograms.Where(m => m.AffiliateID == affiliateId);
//The keywords used to find a Training Program
if (!string.IsNullOrEmpty(searchStr))
{
query = query.Where(m => m.Name.ToLower().Contains(searchStr));
}
if (active != null)
{
}
// The property on which to sort this list.
if (sort != null)
{
switch (sort)
{
case "TrainingProgram Name":
query = query.OrderBy(m => m.Name);
break;
}
}
//The number of Training Programs to display on this page.
if (limit != null)
{
logger.Debug("TrainingProgram query limit: " + limit.Value);
}
var entries = query.Select(m => new TrainingProgramListEntry
{
Name = m.Name,
ColorCode = m.ColorCode,
// The start point in the list of Training Programs
}).Skip((start != null) ? start.Value : 0).Take((limit != null) ? limit.Value : 10).ToList();
return entries;
}
}
CacheUtilites Code:
public TrainingProgramList GetTrainingProgramList(int? affiliateID)
{
string trainingProgramCacheKey = CbConstants.TrainingProgramCacheKey + affiliateID;
TrainingProgramList trainingprogram = (TrainingProgramList)HttpRuntime.Cache[trainingProgramCacheKey];
if (trainingprogram != null)
{
logger.Debug("Cache hit for AffProfile Entity: " + trainingProgramCacheKey);
}
else
{
logger.Debug("Cache miss for AffProfile Entity: " + trainingProgramCacheKey);
trainingprogram = TrainingProgramRepository.Instance.GetTrainingPrograms(AffiliateID);
HttpRuntime.Cache.Insert(trainingProgramCacheKey, trainingprogram, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationTwoHours);
}
return trainingprogram;
}

A prepared String is not being saved completely when not debugging

I have a Program which should save permanently values to a .txt file. When I debug it by putting a breakpoint into the code it works fine. But when letting it work for a while it only saves the last value caught instead of the last 3.
The method ExecuteStrategy is being executed every minute.
Here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Bot_V1._0
{
public class SaveAllMinuteBarsStrategy : IStrategy
{
public Guid StrategyGuid { get; set; }
//private static string[] Data = new string[8];
private string DataDax { get; set; }
private string DataDow { get; set; }
private string DataOil { get; set; }
private string DataGold { get; set; }
private string DataSpy { get; set; }
private string DataEsd { get; set; }
private string DataEgp { get; set; }
private string DataUpy { get; set; }
private string xPath = #"G:\TradingBot\Saved Candles folder";
private DateTime firstEnter;
const char LF = '\n';
public SaveAllMinuteBarsStrategy (Guid StrategyCGuid)
{
this.StrategyGuid = StrategyGuid;
}
public List<ShareAndTimeRange> InitStrategy (Guid stratGuid)
{
firstEnter = DateTime.Now;
var Dax = new ShareAndTimeRange("DAX", 1, stratGuid, null, false);
var Dow = new ShareAndTimeRange("DOW", 1, stratGuid, null, false);
var Oil = new ShareAndTimeRange("OIL", 1, stratGuid, null, false);
var Gold = new ShareAndTimeRange("GOLD", 1, stratGuid, null, false);
var Spy = new ShareAndTimeRange("SPY", 1, stratGuid, null, false);
var Esd = new ShareAndTimeRange("EUR/USD", 1, stratGuid, null, false);
var Egb = new ShareAndTimeRange("EUR/GBP", 1, stratGuid, null, false);
var Ujp = new ShareAndTimeRange("USD/JPY", 1, stratGuid, null, false);
var ElementList = new List<ShareAndTimeRange>();
ElementList.Add(Dax);
ElementList.Add(Dow);
ElementList.Add(Oil);
ElementList.Add(Gold);
ElementList.Add(Spy);
ElementList.Add(Esd);
ElementList.Add(Egb);
ElementList.Add(Ujp);
return ElementList;
}
public void ExecuteStrategy(ShareAndTimeRange Share)
{
SaveDataHourly(Share);
}
private void SaveDataHourly(ShareAndTimeRange Share)
{
if (Share.Candle == null)
return;
var PreparedString = Share.Candle.Time.ToString("yyyyMMdd HHmmss") + ";";
PreparedString = PreparedString + Share.Candle.Open + ";" + Share.Candle.High + ";";
PreparedString = PreparedString + Share.Candle.Low + ";" + Share.Candle.Close;
PreparedString = PreparedString + LF;
switch (Share.ShareName)
{
case ("DAX"):
{
DataDax = DataDax + PreparedString;
//Data[0] = Data[0] +
bool reset = HDMYSaving(Share, DataDax);
if (reset)
DataDax = "";
break;
}
case ("DOW"):
{
DataDow = DataDow + PreparedString;
bool reset = HDMYSaving(Share, DataDow);
if (reset)
DataDow = "";
break;
}
case ("OIL"):
{
DataOil = DataOil + PreparedString;
bool reset = HDMYSaving(Share, DataOil);
if (reset)
DataOil = "";
break;
}
case ("GOLD"):
{
DataGold = DataGold + PreparedString;
bool reset = HDMYSaving(Share, DataGold);
if (reset)
DataGold = "";
break;
}
case ("SPY"):
{
DataSpy = DataSpy + PreparedString;
bool reset = HDMYSaving(Share, DataSpy);
if (reset)
DataSpy = "";
break;
}
case ("EUR/USD"):
{
DataEsd = DataEsd + PreparedString;
bool reset = HDMYSaving(Share, DataEsd);
if (reset)
DataEsd = "";
break;
}
case ("EUR/GBP"):
{
DataEgp = DataEgp + PreparedString;
bool reset = HDMYSaving(Share, DataEgp);
if (reset)
DataEgp = "";
break;
}
case ("USD/JPY"):
{
DataUpy = DataUpy + PreparedString;
bool reset = HDMYSaving(Share, DataUpy);
if (reset)
DataUpy = "";
break;
}
}
}
private void SavePersistentData (string FolderName , string FileName, string Share )
{
if (!System.IO.File.Exists(FolderName))
{
Directory.CreateDirectory(FolderName);
}
string fullPath = System.IO.Path.Combine(FolderName, FileName);
if (!System.IO.File.Exists(fullPath))
{
FileStream fs = File.Create(fullPath);
fs.Dispose();
}
using (StreamWriter sw = new StreamWriter(fullPath, false))
{
sw.Write(Share);
sw.Dispose();
}
//System.IO.File.WriteAllText(fullPath, Share);
}
private void SavePersistent (string ReadFolder , string WriteFolder , string WriteFolderFile)
{
DirectoryInfo ParDir = new DirectoryInfo(ReadFolder);
string dat = "";
foreach (var item in ParDir.GetFiles())
{
var elem = System.IO.Path.Combine(ReadFolder, item.Name);
dat += System.IO.File.ReadAllText(elem);
}
SavePersistentData(WriteFolder, WriteFolderFile, dat);
foreach (var item in ParDir.GetFiles())
{
var del = System.IO.Path.Combine(ReadFolder, item.Name);
File.Delete(del);
}
}
private bool HDMYSaving(ShareAndTimeRange Share, string Values)
{
if (Share.Candle == null)
return false;
bool toReset = false;
string SharePath = System.IO.Path.Combine(xPath, Share.ShareName);//c:\TradingBot\Saved Candles folder\"Sharename"\
string HourPath = System.IO.Path.Combine(SharePath, "Hour Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Hour Data
int res;
int resuzt = Math.DivRem(Share.Candle.Time.Minute,3,out res);
if ( res == 0) //0 Share.Candle.Time.Minute == 0
{
DateTime DateToWriteH = Share.Candle.Time;
string HourFilePath = DateToWriteH.ToString("yyyyMMddHHmm") + ".txt";
SavePersistentData(HourPath, HourFilePath, Values);
toReset = true;
}
DateTime DateToWriteD = Share.Candle.Time.AddDays(-1);
string DayPath = System.IO.Path.Combine(SharePath, "Day Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Day Data
string DayFilePath = System.IO.Path.Combine(DayPath, DateToWriteD.ToString("yyyyMMdd") + ".txt");
if (Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(DayFilePath))
{
SavePersistent(HourPath, DayPath, DateToWriteD.ToString("yyyyMMdd") + ".txt");
}
DateTime DateToWriteM = Share.Candle.Time.AddMonths(-1);
string MonthPath = System.IO.Path.Combine(SharePath, "Month Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Month Data
string MonthFilePath = System.IO.Path.Combine(MonthPath, DateToWriteM.ToString("yyyyMM") + ".txt");
if (Share.Candle.Time.Day == 1 && Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(MonthFilePath))
{
SavePersistent(DayPath, MonthPath, DateToWriteM.ToString("yyyyMM") + ".txt");
}
DateTime DateToWriteY = Share.Candle.Time.AddYears(-1);
string YearPath = System.IO.Path.Combine(SharePath, "Year Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Year Data
string YearFilePath = System.IO.Path.Combine(YearPath, DateToWriteY.ToString("yyyy") + ".txt");
if (Share.Candle.Time.Month == 1 && Share.Candle.Time.Day == 1 && Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(YearFilePath))
{
SavePersistent(MonthPath, YearPath, DateToWriteY.ToString("yyyy") + ".txt");
}
return toReset;
}
}
Is there a problem having a lot of Events which are fired every 2 seconds or every minute?
Thanks!!
i found the problem. It was on another Class. The Fault was firing an event every time the program colleted a new value, but the program schould wait for the other "WebsTakenInCare".
Here is the Code before:
if (DataList.Count() == WebsTakenInCare)
{
FinalizedData = ShortenUpData(DataList);
DataList.Clear();
}
BuildCandles(FinalizedData);
and after changing:
if (DataList.Count() == WebsTakenInCare)
{
FinalizedData = ShortenUpData(DataList);
DataList.Clear();
BuildCandles(FinalizedData);
}
else
return;
regards!

Accessing string from an html template class

I'm trying to access a certain variable from another class, however I'm not able to do so. I have two buttons - the first button sets token to an html template file. The second should generate the file. The first button calls the class. The second button should call the string from the class for generation.
My first button is as follows:
private void btnTemplate_Click(object sender, EventArgs e)
{
if ((txtTitle.Text == "") && (txtSku.Text == "") && (txtPrice.Text == "") && (txtDesc.Text == "") && (txtImg.Text == ""))
{
MessageBox.Show("No row selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
OpenFileDialog SetData = new OpenFileDialog();
SetData.Filter = "HTML|*.html;";
GlobalVar.setPath = "C:\\genHtml.html";
var result = SetData.ShowDialog();
DataSet ds = new DataSet();
if (result == DialogResult.OK)
{
string fileName = SetData.FileName;
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);
}
}
}
My second button:
private void btnGenerate_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(GlobalVar.setPath);
}
catch
{
MessageBox.Show("Please select a template first", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I get an error with the string output. How can I call string 'output' for the second button?
My class is as follows:
class HtmlTemplate
{
private string _html;
public HtmlTemplate(string templatePath)
{
using (var reader = new StreamReader(templatePath))
_html = reader.ReadToEnd();
}
public string Render(object values)
{
string output = _html;
foreach (var p in values.GetType().GetProperties())
output = output.Replace("[" + p.Name + "]", (p.GetValue(values, null) as string) ?? string.Empty);
return output;
}
}
There is not enough context to be sure, but in the case of the second button it looks like output is not declared as a variable or possibly not assigned a (correct) value.
File.WriteAllText(#GlobalVar.setPath, output);
could become
var template = new HtmlTemplate(#SetData.FileName);
File.WriteAllText(#GlobalVar.setPath, template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
or alternatively
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);

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());

Categories