Pass multiple data from one function to label in C# - c#

I have a function that retrieves multiple lines of data and I want to display them in a label. My function is as shown below.
public static string GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
}
return res;
}
So far I can only return a string which is the last line of the retrieved data. How can I retrieve all the records? I tries arraylist, but it seems that the AWS web application doesn't allow me to use arraylist. Can anyone please help me to solve this??

Return it as as a Enumberable,
List<String> Results ;
Your method would be
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = null;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
Results = new List<String>();
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}

Related

How can I return multiple tuple values as 1 string

This is what I want: A method that will concatenate all the returned values into one block. At the moment each result is sent as a single string. current results of my code that I would like concatinated
static async void NotifyEntriesByWorkSpace(Dictionary<string, List<TimeEntry>> EntriesByWorkspace, string strChatURL)
{
foreach (var entry in EntriesByWorkspace)
{
var timeEntry = entry.Value;
string prevStoryId = "";
string strTitle = "";
var minsLogged = 0;
foreach (var item in timeEntry)
{
Tuple<string, int, string> entryData = GetEntryData(prevStoryId, item);
prevStoryId = entryData.Item1;
minsLogged = minsLogged + entryData.Item2;
strTitle = entryData.Item3;
}
Console.WriteLine(strTitle + ": " + minsLogged + " min(s)");
await SendEntriesByWorkspaceMessage(strChatURL, strTitle, minsLogged);
}
}
static async Task SendEntriesByWorkspaceMessage(string strChatURL, string strTitle, int minsLogged)
{
await sendMessage(strChatURL, strTitle + ": " + minsLogged / 60 + " hour(s)" + " " + minsLogged % 60 + " min(s)");
}
static Tuple<string, int, string> GetEntryData(string prevStoryId, TimeEntry item)
{
var storyId = item.StoryID;
string prevStoryId_ = "";
string strTitle = "";
var minsLogged = 0;
strTitle = Workspaces.getWorkspaceFromCache(item.WorkspaceID).Title;
if (prevStoryId != storyId)
{
minsLogged = item.TimeInMinutes;
prevStoryId_ = storyId;
}
else
{
minsLogged = minsLogged + item.TimeInMinutes;
}
return Tuple.Create(prevStoryId_, minsLogged, strTitle);
}
static async void NotifyEntriesByWorkSpace(Dictionary<string, List<TimeEntry>> EntriesByWorkspace, string strChatURL)
{
string block = "";
foreach (var entry in EntriesByWorkspace)
{
var timeEntry = entry.Value;
string prevStoryId = "";
string strTitle = "";
var minsLogged = 0;
foreach (var item in timeEntry)
{
Tuple<string, int, string> entryData = GetEntryData(prevStoryId, item);
prevStoryId = entryData.Item1;
minsLogged = minsLogged + entryData.Item2;
strTitle = entryData.Item3;
}
Console.WriteLine(strTitle + ": " + minsLogged + " min(s)");
block += strTitle + ": " + minsLogged / 60 + " hour(s)" + " " + minsLogged % 60 + " min(s)\n";
}
await sendMessage(strChartUrl, block);
}
The idea is to instead of sendMessage() every entry, collect entries into a string then output it once the whole foreach loop completed.
The string is manually separated by \n, but some ideas like make a entriesList and then eventually String.Join("\n", entriesList) might result in more clear code flow. It depends on your liking.

How to get specific character in listbox

I have a listbox in which my selected products are stored like this ...
'Product name'.padright(30) 'price' 'quantity'
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
but when I read price of a product it selects price and quantity
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
I only want price in currentPriceString and quantity in quantityString
here is complete code of this method
private void ProductButton_Click(object sender, EventArgs e)
{
Button ProductButton = sender as Button;
DataAccess dataAccess = new DataAccess();
int ProductID = Convert.ToInt32(ProductButton.Tag);
Details details = dataAccess.ReadProductDetails(ProductID);
decimal price = details.Price;
string foundItem = CheckProductInListBox(details.Name);
if (!String.IsNullOrEmpty(foundItem))
{
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
decimal currentPriceValue;
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
int quantiy;
MessageBox.Show(currentPriceString);
if (Decimal.TryParse(currentPriceString, out currentPriceValue))
{
quantiy = Convert.ToInt16(quantityString);
currentPriceValue += price;
quantiy++;
string newItem = details.Name.PadRight(30) + currentPriceValue.ToString() + quantiy.ToString();
int index = listBox1.Items.IndexOf(foundItem);
listBox1.Items[index] = newItem;
}
else
{
MessageBox.Show("Error");
}
}
else
{
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
}
}
private string CheckProductInListBox(string name)
{
foreach (string item in listBox1.Items)
{
if (item.Contains(name))
{
return item;
}
}
return String.Empty;
}
On replacing (foundItem.Replace(details.Name.PadRight(33), "");), you are just removing the name part from the string, so the price and quantity will be there for sure.
You should can try this code,
// suppose your found text is like this,
//foundItem = "AMIT".PadRight(30) + "200" + " " + "1";
You can get price and quantity separately like below:
string currentPriceQuantityString = foundItem.Replace(details.Name.PadRight(30), "");
//currentPriceQuantityString => "200 1"
string[] strArray = currentPriceQuantityString.Split();
string currentPriceString = strArray[0]; //currentPriceString => "200"
string quantityString = strArray[1]; //quantityString => "1"
Side note:
I guess your line:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
..should be:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + "1" );

Efficient method to increase "code" by 1 - HtmlAgilityPack

I'm working on an app that extracts content from a game page (example), displays it to the user in a textbox and if the user wishes to do so, he/she can save it as a .txt file or .xsl (excel spreadsheet format).
But the main problem I'm facing right now is that you have to manually change the code to "extract" data about another in-game unit.
If you open the link you'll see that I'm currently extracting the "Weapons", "Used", "Survived" and "Casualties" from the Defender side (as for now), but only 1 type of unit (more like only 1 row of that table) is being "extracted", I'm looking for a way to search "tr[1]/td[2]/span[1]" through "tr[45]/td[2]/span[1]" (even if the example page only goes until tr[16]), or maybe a way to automate it to search until it finds no data (nothing) then it would stop.
Sorry for any text mistakes, I'm not a native speaker
private void btnStart_Click(object sender, RoutedEventArgs e)
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
HtmlNodeCollection nodes = brPage.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/table[2]");
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
brContentSaver cL = new brContentSaver();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = item.SelectSingleNode("tr[16]/td[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = item.SelectSingleNode("tr[16]/td[2]/span[1]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Survived = item.SelectSingleNode("tr[16]/td[3]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (cL.Survived == "0")
{
cL.Casualties = cL.Used;
} else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = item.SelectSingleNode("tr[16]/td[4]").InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
}
ContentList.Add(cL);
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
brContent.Text = result;
}
Sorry if this sounds silly, but I'm new to programming, especially in C#.
Edit 1: I noticed that "if (cL.Survived == "0")", I was just testing stuff some stuff way earlier and I forgot to change it, but hey, it works
Edit 2: If you are wondering I'm also using this:
public class brContentSaver
{
public string Weapons
{
get;
set;
}
public string Used
{
get;
set;
}
public string Survived
{
get;
set;
}
public string Casualties
{
get;
set;
}
}
I don't have much time to write this but hope it will help if you still need. I find Linq is more handy:
private static void Run()
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
var nodes = brPage.DocumentNode.Descendants("table").Where(_ => _.Attributes["class"] != null && _.Attributes["class"].Value != null && _.Attributes["class"].Value.Contains("battleReport"));
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
if (item.Descendants("th").Any(_ => _.InnerText.Equals("Weapons")))
{
//get all tr nodes except first one (header)
var trNodes = item.Descendants("tr").Skip(1);
foreach (var node in trNodes)
{
brContentSaver cL = new brContentSaver();
var tds = node.Descendants("td").ToArray();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = tds[0].InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
cL.Used = tds[1].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Used))
{
cL.Used = tds[1].InnerText;
}
cL.Survived = tds[2].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Survived))
{
cL.Casualties = cL.Used;
}
else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = tds[3].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("&nbsp ; *&nbsp ;", " ");
if (string.IsNullOrEmpty(cL.Casualties))
{
cL.Casualties = tds[3].InnerText;
}
}
ContentList.Add(cL);
}
}
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
var text = result;
}

Adding webpart to filter view by code is not working

I need to add a new page in a new doc library. That works fine. In the page I need to add a webpart to filter list data from a view bases on 3 columns from the view.
The following code is not throwing any exception but its not either filtering the data. There are 3 items in the list
// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
string pageUrl=AddSponsoringEventsDashboardPage(properties.Feature.Parent as SPWeb);
AddNavigationLink(properties.Feature.Parent as SPWeb, pageUrl);
}
private void AddNavigationLink(SPWeb currentUnsafeWeb, string url)
{
bool allowUnsafeUpdatesSetting = false;
try
{
// Cleanup all quick links
allowUnsafeUpdatesSetting = currentUnsafeWeb.AllowUnsafeUpdates;
currentUnsafeWeb.AllowUnsafeUpdates = true;
SPNavigationNodeCollection quickLaunchNodes = currentUnsafeWeb.Navigation.QuickLaunch;
foreach (SPNavigationNode node in quickLaunchNodes)
{
if (string.Compare(node.Title, "Lists") == 0)
{
SPNavigationNode dataNode = new SPNavigationNode("$Resources:SPNLSponsoring,Navigation_SponsoringEventsDashboard_Title", url, true);
node.Children.AddAsFirst(dataNode);
currentUnsafeWeb.Update();
break;
}
}
}
catch
{
throw;
}
finally
{
currentUnsafeWeb.AllowUnsafeUpdates = allowUnsafeUpdatesSetting;
}
}
private string AddSponsoringEventsDashboardPage(SPWeb currentWeb)
{
Logger.LogDebug("NLSponsoringSiteConfigSponsoringCentralEventReceiver", "AddSponsoringEventsDashboardPage(SPWeb currentWeb)", "BEGIN");
SPListTemplateType tempType = SPListTemplateType.DocumentLibrary;
Guid guid = currentWeb.Lists.Add("$Resources:SPNLSponsoring,SponsoringDashboardDocumentLibrary_Title",
"$Resources:SPNLSponsoring,SponsoringDashboardDocumentLibrary_Description", tempType);
SPList docLibrary = currentWeb.Lists[guid];
SPLimitedWebPartManager mgrPageManager = null;
SPFile pageDashboard = null;
string strurl;
try
{
pageDashboard = docLibrary.RootFolder.Files.Add(String.Format("{0}/{1}", docLibrary.RootFolder.ServerRelativeUrl, "sponsoringeventdashboard.aspx"), SPTemplateFileType.StandardPage);
pageDashboard.CheckOut();
#region Add Filter webpart
SimpleFormWebPart sfwp = new SimpleFormWebPart();
sfwp.Title = "Filter";
sfwp.Content = "<div onkeydown=\"javascript:if (event.keyCode == 13) _SFSUBMIT_\"><input type=\"text\" name=\"T1\"/>" +
"<input type=\"button\" value=\"Go\" onclick=\"javascript:_SFSUBMIT_\"/></div>";
string idWebPartFilter = pageDashboard.AddWebPartToPage(sfwp, Constants.WEBPART_ZONE_HEADER, 1, PartChromeType.Default);
#endregion
#region Add new view
SPList list = currentWeb.Lists[SponsoringCommon.Constants.LISTNAMES_SPONSORINGEVENTSNAME];
SPView oView = list.Views[SponsoringCommon.Constants.VIEWS_SPONSORINGEVENTS_DEFAULTLIST].Clone(SponsoringCommon.Constants.VIEWS_SPONSORINGEVENTS_DASHBOARD_NAME, 20, true, false);
oView.Query = "<Where>" +
"<Or>" +
" <Or>" +
" <Contains>" +
" <FieldRef Name=\"EventNumber\"/>" +
" <Value Type=\"Text\">{ParamEventNumber}</Value>" +
" </Contains>" +
" <Contains>" +
" <FieldRef Name=\"EventName\"/>" +
" <Value Type=\"Text\">{ParamEventName}</Value>" +
" </Contains>" +
"</Or>" +
"<Contains>" +
"<FieldRef Name=\"EventLocation\"/>" +
"<Value Type=\"Text\">{ParamEventLocation}</Value>" +
"</Contains>" +
"</Or>" +
" </Where>";
oView.Update();
#endregion
#region Add XSLT List View WebPart
string idWebPartSponsoringEvents = "ID_SponsoringEvents";
pageDashboard.AddXSLTListViewWebPartToPage(currentWeb,
SponsoringCommon.Constants.LISTNAMES_SPONSORINGEVENTS, idWebPartSponsoringEvents,
string.Empty, Constants.WEBPART_ZONE_HEADER, 2,
SponsoringCommon.Constants.VIEWS_SPONSORINGEVENTS_DASHBOARD_NAME, PartChromeType.Default, false);
mgrPageManager = pageDashboard.GetLimitedWebPartManager(PersonalizationScope.Shared);
XsltListViewWebPart lvwpOrganisation = mgrPageManager.WebParts[idWebPartSponsoringEvents] as XsltListViewWebPart;
lvwpOrganisation.ParameterBindings += "<ParameterBinding Name=\"ParamEventNumber\" Location=\"None\" DefaultValue=\"\" />" +
"<ParameterBinding Name=\"ParamEventName\" Location=\"None\" DefaultValue=\"\" />" +
"<ParameterBinding Name=\"ParamEventLocation\" Location=\"None\" DefaultValue=\"\" />";
mgrPageManager.SaveChanges(lvwpOrganisation);
#endregion
#region Add Connection
string[] colConsumerFields = { "EventNumber", "EventName", "EventLocation" };
string[] colProviderFields = { "T1", "T1", "T1" };
// connect filter to organisation-webpart
pageDashboard.ConnectWebPartsByRowToParameters(idWebPartSponsoringEvents,
Constants.WEBPART_CONNECTION_DFWPPARAMETERCONSUMERID,
colConsumerFields,
idWebPartFilter,
Constants.WEBPART_CONNECTION_SFWPROWPROVIDERID,
colProviderFields);
#endregion
pageDashboard.CheckIn(String.Empty);
strurl = pageDashboard.Url;
}
catch (Exception)
{
if (pageDashboard != null) pageDashboard.UndoCheckOut();
throw;
}
Logger.LogDebug("NLSponsoringSiteConfigSponsoringCentralEventReceiver", "AddSponsoringEventsDashboardPage(SPWeb currentUnsafeWeb)", "WebParts added. Start configuring connections.");
return strurl;
}
problem was ParameterBinding
I was not using the same name., it has to match.

String list remove

I have this code:
List<string> lineList = new List<string>();
foreach (var line in theFinalList)
{
if (line.PartDescription != "")
lineList.Add(line.PartDescription + " " + line.PartNumber + "\n");
else
lineList.Add("N/A " + line.PartNumber + "\n");
//
//This is what I am trying to fix:
if (lineList.Contains("FID") || lineList.Contains("EXCLUDE"))
// REMOVE THE item in the lineList
}
I am trying to go through theFinalList in a foreach loop and add each line to a new list called lineList.
Once added, I want to remove any entries from that list that contain the text "FID" or "EXCLUDE".
I am having trouble removing the entry, can someone help me?
why add them when you want to remove them right after:
lineList = theFinalList.Select( line =>
{
if (line.PartDescription != "")
return line.PartDescription + " " + line.PartNumber + "\n";
else
return "N/A " + line.PartNumber + "\n";
})
.Where(x => !(x.Contains("FID") || x.Contains("EXCLUDE")))
.ToList();
The following code sample iterates through the lineList and removes lines that contain FID or EXCLUDE.
for(int i = lineList.Count - 1; i >= 0; i--)
{
if (lineList[i].Contains("FID") || lineList[i].Contains("EXCLUDE"))
lineList.RemoveAt(i);
}
It is important to traverse a list in reverse order when deleting items.
You can't remove the items in your theFinalList list while you are iterating over theFinalList in a foreach loop. In this case, you may get System.InvalidOperationException with the message “Collection was modified; enumeration operation may not execute.”
you have to do something like this:
List<string> removals = new List<string>();
foreach (string s in theFinalList)
{
//do stuff with (s);
removals.Add(s);
}
foreach (string s in removals)
{
theFinalList.Remove(s);
}
try
foreach (var line in theFinalList)
{
string T = "";
if (line.PartDescription != "")
T = line.PartDescription + " " + line.PartNumber + "\n";
else
T = "N/A " + line.PartNumber + "\n";
if (!(T.Contains("FID") || T.Contains("EXCLUDE"))
lineList.Add (T);
}
I think its more logical approach
Regex exclude = new Regex("FID|EXCLUDE");
foreach (var line in theFinalList.Where(
ln => !exclude.Match(ln.PartDescription).Success &&
!exclude.Match(ln.PartNumber ).Success))){
string partDescription = "N/A";
if(!string.IsNullOrWhiteSpace(line.PartDescription)){
partDescription = line.PartDescription;
}
lineList.Add(partDescription + " " + line.PartNumber + "\n");
}
edit regex for your needs (ignore case maybe or multiline, probably compiled too) and feel free to replace "\n" with Environment.NewLine
Try this:
var excludingTexts = new [] { "FID", "EXCLUDE" }
lineList = lineList.Where(y => !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))).ToList();
Or you can rewrite it as:
var excludingTexts = new [] { "FID", "EXCLUDE" }
List<string> lineList = (from line in theFinalList
where !excludingTexts.Any(x => line.PartDescription.Contains(x) || line.PartNumber.Contains(x))
select line.PartDescription != "" ?
line.PartDescription + " " + line.PartNumber + "\n" :
"N/A " + line.PartNumber + "\n"
).ToList();

Categories

Resources