Custom attributes of checkboxlist - c#

I added some custom attributes to checkboxlist, but I wonder why I failed to retrieve the values of custom attributes. It will be something like this post jQuery - find control using custom attribute. But what I want is retrieve through auto postback and code behind.
int temp = 0;
foreach (DataRow rows1 in ds_ss_equipments_data.Tables[0].Rows)
{
cblEquip.Items.Add(new ListItem(rows1["name"].ToString() + " " + rows1["quota"].ToString() + " X " + rows1["price"].ToString(), rows1["id"].ToString()));
cblEquip.Items[temp].Attributes["price"] = rows1["price"].ToString();
cblEquip.Items[temp].Attributes["id"] = rows1["id"].ToString();
cblEquip.Items[temp].Attributes["quota"] = rows1["quota"].ToString();
temp += 1;
}
foreach (ListItem li in cblEquip.Items)
{
if (li.Selected)
{
equip += (Convert.ToDecimal(li.Attributes["price"]) * Convert.ToInt32(li.Attributes["quota"]));
}
}

The link provided by Tim will probably solve your problem. Just a note on your programming style. This temp variable looks very strange. Try this
foreach (DataRow rows1 in ds_ss_equipments_data.Tables[0].Rows)
{
var listItem = new ListItem(rows1["name"].ToString() + " " + ...)
listItem.Attributes["price"] = rows1["price"].ToString();
listItem.Attributes["id"] = rows1["id"].ToString();
listItem.Attributes["quota"] = rows1["quota"].ToString();
cblEquip.Items.Add(listItem);
}
It is easier an more comprehensible.
And replace this
rows1["name"].ToString() + " " + rows1["quota"].ToString() + " X " + rows1["price"].ToString()
By this
String.Format("{0} {1} X {2}", rows1["name"], rows1["quota"], rows1["price"])
Creating an item will look much prettier like this
string caption = String.Format(
"{0} {1} X {2}",
rows1["name"],
rows1["quota"],
rows1["price"]
);
var listItem = new ListItem(caption, rows1["id"].ToString())

Related

c# Interface type of Memory cards using Win32_DiskDrive object

I need to identify all drives and all logical partitions of each drive and I am having really troubles while dealing with memory cards (integrated reader in the laptop).
I am using this code
void GetFullInfoDiskDrives()
{
Global.LogMessage("************** GetFullInfoDiskDrives() Getting complete info from all disk drives ", 1);
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject info in searcher.Get())
{
// Lets print all the properties per disk
PropertyDataCollection properties = info.Properties;
// display the properties
Global.LogMessage("----------------- Properties for the disk " + info["Model"].ToString(),1);
foreach (PropertyData property in properties)
{
Global.LogMessage("[" + property.Name + "] = '" + property.Value +"'", 1);
foreach (QualifierData q in property.Qualifiers)
{
Global.LogMessage(" -" + q.Name + "- = '" + q.Value + "'", 1);
}
}
string s = "";
string s_model = info["Model"].ToString();
string s_interface = (info["InterfaceType"]==null? info["MediaType"].ToString():info["InterfaceType"].ToString());
string s_serialnumber = (info["SerialNumber"] == null ? "No serial number": info["SerialNumber"].ToString());
Global.LogMessage("Disk detected (Model: " + s_model + " | Interface: " + s_interface + " | Serial#: " + s_serialnumber,1);
foreach (ManagementObject o in info.GetRelated("Win32_DiskPartition"))
foreach (ManagementObject i in o.GetRelated("Win32_LogicalDisk"))
s += i["Name"] + " ";
Global.LogMessage("Logical disks: " + s,1);
}
}
The memory card doesn't seem to have a value for InterfaceType so I need to read MediaType instead. The same happens with the serial number, I don't know where to find it for a memory card.
Also, many values show its type (of value) in the value property such as
[Capabilities] = 'System.UInt16[]'
-CIMTYPE- = 'uint16'
How can I get the real value of this property?
I admit I am a bit lost and diving in the official documentation is not an easy task... :/
Could anybody put some light ?
Thanks!
Jose
After the good above suggestion from Rene, I tried to make it as dynamically as possible.
my goal is to cast the Property.value using the type from the value from the related QualifierData object.
My final working code is here. I am sure that there are more elegant ways to achieve it but this is the one I found. ;)
foreach (PropertyData property in properties){
foreach (QualifierData q in property.Qualifiers){
if (property.IsArray){
if (property.Value != null){
Type t = property.Value.GetType();
object o = property.Value;
dynamic foo = o;
if (IsPropertyExist(foo, "Length")){
string s1 = "";
for (int i = 0; i < foo.Length; i++)
s1 += "[" +foo[i] +"]";
Global.LogMessage("[" + property.Name + "] (" + q.Value + ") = " + s1 , 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;
}

Pass multiple data from one function to label in 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;
}

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

Implement a HierarchicalDataBoundControl for ASP.NET

I want to implement a Hierarchical data bound control for ASP.NET.
I used Implementing IHierarchy Support Into Your Custom Collection as a basis to create my hierarchical collection. I also created a HierarchicalDataSourceControl for the collection. Everything works: I can bind it to an ASP.NET TreeView and it renders the data correctly.
However, I'm stuck on the HierarchicalDataBoundControl. I found examples, but I am still too new at c# / .Net to understand them. I don't quite understand how to implement the examples:
Rendering a databound UL menu
nor
HierarchicalDataBoundControl Class
Does anyone have any tips, or better examples of implementing a control like this?
As another DataBound controls you have to override PerformDataBinding method as follows.
protected override void PerformDataBinding()
{
base.PerformDataBinding();
if (!IsBoundUsingDataSourceID && this.DataSource == null) return;
HierarchicalDataSourceView view = this.GetData(string.Empty);
if (view != null)
{
IHierarchicalEnumerable root = view.Select();
}
}
Whereas your control supports DataSource and HierarchialDataSource control in this case, should check if there is an assigned DataSource, get its DataSourceView to accomplish data binding. It's practicable through GetData method. Then call view's Select method to get the root collection.
Afterwards, you have to iterate through root collection that is an object of type IHierarchialEnumerable. It has a simple method called GetHierarchyData that gives an object which is an item of the collection and returns an associated IHierarchyData that describes a node. This methods is there, therefore in most times you don't know the actual type of item. IHierarchyData represents some information about a node and its children.
Lastly, you don't need to write a new DataSource control. If you are after creating a custom navigation control, it's better to write a new provider for SiteMapDataSource.
I faced similar problem and created my own raw html.
private void LoadCategory()
{
String s = "";
// Prepare your dataset DataSet ds
// Note That I have Category Table having C_NAME AND PC_NAME coloums, change it as per your column anme
ds.Relations.Add("rsParentChild", ds.Tables[0].Columns["C_NAME"], ds.Tables[0].Columns["PC_NAME"]);
s = s + "\n <table>";
s = s + "\n <tr>";
s = s + "\n <td class='br4'> ";
s = s + "\n <table>";
s = s + "\n <tr>";
s = s + "\n <td>";
s = s + "\n <ul id='qm0' class='qmmc'>";
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["PC_NAME"] == DBNull.Value)
{
s = s + "\n <li><a class='qmparent' href='#'>" + dr["C_NAME"].ToString() + "</a>";
s = s + "\n <ul>" + PopulateTree(dr) + "</ul>";
}
}
s = s + "\n <li class='qmclear'> </li></ul>";
s = s + "\n <script type='text/javascript'>qm_create(0,true,0,500,'all',false,false,false,false);</script>";
s = s + "\n </td>";
s = s + "\n </tr>";
s = s + "\n </table>";
s = s + "\n </td>";
s = s + "\n </tr>";
s = s + "\n </table>";
Literal1.Text = s;
}
private String PopulateTree(DataRow dr)
{
String s = "";
String ss;
foreach (DataRow row in dr.GetChildRows("rsParentChild"))
{
s = s + " <li>" + row["C_NAME"].ToString() + "\n";
ss = PopulateTree(row);
if (ss != "")
s = s + " <ul>" + ss + "</ul></li>\n\n";
}
return s;
}

Categories

Resources