C# TreeViewAdv get selected node's value - c#

I am using syncfusion's TreeViewAdv in multi column mode.
I am trying to get the selected node's value (from the first column) but I have not been successful.
Has anyone been able to do this?
Many thanks
Edit:
A quick update on how I am populating the control
private void RefreshOptions()
{
List<String> objects = Globals.ThisAddIn.utilities.ListRObjectsWithDetail();
StringBuilder name = new StringBuilder(100);
StringBuilder details = new StringBuilder(200);
Node dataRootNode = new Node();
Node dataParentNode = new Node();
Node dataChildNode1 = new Node();
Node dataChildNode2 = new Node();
Node dataChildNode3 = new Node();
Node functionsRootNode = new Node();
Node functionsParentNode = new Node();
int charLocation;
int indexChild;
int childLevel;
TreeModel _model = new TreeModel();
treeViewAdv1.Model = _model;
treeViewAdv1.BeginUpdate();
dataRootNode = new ColumnNode("Data / Values", "", "");
_model.Nodes.Add(dataRootNode);
functionsRootNode = new ColumnNode("Functions", "", "");
_model.Nodes.Add(functionsRootNode);
foreach (String obj in objects)
{
name.Clear();
details.Clear();
name.Append(obj.Trim());
charLocation = name.ToString().IndexOf(":");
details.Append(name.ToString().Substring(charLocation + 1).Trim());
name.Length = charLocation;
if (details.Length >=10 && details.ToString(0, 10) == "function (")
{
functionsParentNode = new ColumnNode(name.ToString(), "Function", details.ToString());
functionsRootNode.Nodes.Add(functionsParentNode);
}
else
{
indexChild = name.ToString().IndexOf("$");
if (indexChild > -1)
{
childLevel = name.ToString(0, indexChild).Split('.').Length - 1;
name.Remove(0, 1 + childLevel);
switch (indexChild)
{
case 1:
dataChildNode1 = new ColumnNode(name.ToString(), "Data / Value", details.ToString());
dataParentNode.Nodes.Add(dataChildNode1);
break;
case 2:
dataChildNode2 = new ColumnNode(name.ToString(), "Data / Value", details.ToString());
dataChildNode1.Nodes.Add(dataChildNode2);
break;
case 3:
dataChildNode3 = new ColumnNode(name.ToString(), "Data / Value", details.ToString());
dataChildNode2.Nodes.Add(dataChildNode3);
break;
}
}
else
{
dataParentNode = new ColumnNode(name.ToString(), "Data / Value", details.ToString());
dataRootNode.Nodes.Add(dataParentNode);
}
}
}
NodeTextBox ntb = new NodeTextBox();
ntb.DataPropertyName = "Text";
this.treeViewAdv1.NodeControls.Add(ntb);
treeViewAdv1.EndUpdate();
}
I spent some time looking at the TreeViewAdv sample project. Specifically I looked the "FolderBrowser.cs" winform which did have the below NodeMouseDoubleClick event. This correctly wrote the node tot he console.
private void _treeView_NodeMouseDoubleClick(object sender, TreeNodeAdvMouseEventArgs e)
{
Console.WriteLine(e.Node);
}
If I use exactly the same event then my e.Node = "" although my node is fully populated.

Related

CADES signature with Json data in C#

I have below json data I need to apply CAdES-BES Signature with Automatic JSON Canonicalization. Please find my json data below. Helpful link from https://www.example-code.com/Csharp/itida_egypt_cades_bes_json_canonicalization.asp. I follow the steps but still digital signature is not applying. Its returns normal json data.
[HttpGet]
[Route("api/invoiceLines/")]
public IHttpActionResult getEInvoiceLines()
{
Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
crypt.VerboseLogging = true;
Chilkat.Cert cert = new Chilkat.Cert();
cert.VerboseLogging = true;
// Set the smart card PIN, which will be needed for signing.
cert.SmartCardPin = "1245345";
// There are many ways to load the certificate.
// This example was created for a customer using an ePass2003 USB token.
// Assuming the USB token is the only source of a hardware-based private key..
bool success = cert.LoadFromSmartcard(#"E"); //Is this Right way To load certificate ?
Chilkat.JsonObject cmsOptions = new Chilkat.JsonObject();
// Setting "DigestData" causes OID 1.2.840.113549.1.7.5 (digestData) to be used.
cmsOptions.UpdateBool("DigestData", true);
cmsOptions.UpdateBool("OmitAlgorithmIdNull", true);
// Indicate that we are passing normal JSON and we want Chilkat do automatically
// do the ITIDA JSON canonicalization:
cmsOptions.UpdateBool("CanonicalizeITIDA", true);
crypt.CmsOptions = cmsOptions.Emit();
// The CadesEnabled property applies to all methods that create CMS/PKCS7 signatures.
// To create a CAdES-BES signature, set this property equal to true.
crypt.CadesEnabled = true;
crypt.HashAlgorithm = "sha256";
Chilkat.JsonObject jsonSigningAttrs = new Chilkat.JsonObject();
jsonSigningAttrs.UpdateInt("contentType", 1);
jsonSigningAttrs.UpdateInt("signingTime", 1);
jsonSigningAttrs.UpdateInt("messageDigest", 1);
jsonSigningAttrs.UpdateInt("signingCertificateV2", 1);
crypt.SigningAttributes = jsonSigningAttrs.Emit();
// By default, all the certs in the chain of authentication are included in the signature.
// If desired, we can choose to only include the signing certificate:
crypt.IncludeCertChain = false;
EInvoiceModel.Example ds = new EInvoiceModel.Example();
//Start issuer details
ds.issuer = new EInvoiceModel.Issuer();
ds.issuer.type = "B";
ds.issuer.id = "113317713";
ds.issuer.name = "Issuer Company";
//Start issuer address details
ds.issuer.address = new EInvoiceModel.Address();
ds.issuer.address.branchID = "1";
ds.issuer.address.country = "EG";
ds.issuer.address.governate = "Cairo";
ds.issuer.address.regionCity = "Nasr City";
ds.issuer.address.street = "stree1";
ds.issuer.address.buildingNumber = "Bldg. 0";
ds.issuer.address.postalCode = "68030";
ds.issuer.address.floor = "1";
ds.issuer.address.room = "123";
ds.issuer.address.landmark = "7660 Melody Trail";
ds.issuer.address.additionalInformation = "beside Town Hall";
//Start Receiver details
ds.receiver = new EInvoiceModel.Receiver();
ds.receiver.type = "B";
ds.receiver.id = "3125617";
ds.receiver.name = "Receiver company";
//Start Receiver address datails
ds.receiver.address = new EInvoiceModel.AddressReceiver();
ds.receiver.address.country = "EG";
ds.receiver.address.governate = "Cairo";
ds.receiver.address.regionCity = "Nasr City";
ds.receiver.address.street = "stree1";
ds.receiver.address.buildingNumber = "Bldg. 0";
ds.receiver.address.postalCode = "68030";
ds.receiver.address.floor = "1";
ds.receiver.address.room = "123";
ds.receiver.address.landmark = "7660 Melody Trail";
ds.receiver.address.additionalInformation = "beside Town Hall";
//Document type & version
ds.documentType = "i";
ds.documentTypeVersion = "1.0";
DateTime d = new DateTime();
ds.dateTimeIssued = d; //Invoice date
ds.taxpayerActivityCode = "9478"; //needed info
ds.internalID = "WADIn1234"; //Internal Invoice number
ds.salesOrderReference = "So1234"; //So number //optional
ds.salesOrderDescription = "SO1234"; //So additional Info //optional
ds.proformaInvoiceNumber = "SoPro123"; //optional
//Invoiceline Start
ds.invoiceLines = new List<EInvoiceModel.InvoiceLine>
{
new EInvoiceModel.InvoiceLine
{
description = "Computer1",
itemType = "GPC",
itemCode = "10001774",
unitType = "EA",
quantity = 2,
internalCode = "IC0",
salesTotal = 23.99,
total = 2969.89,
valueDifference = 7.00,
totalTaxableFees = 817.42,
netTotal = 880.71,
itemsDiscount = 5.00,
unitValue = new EInvoiceModel.UnitValue
{
currencySold = "EUR",
amountEGP = 189.40,
amountSold = 10.00,
currencyExchangeRate = 18.94,
},
discount = new EInvoiceModel.Discount
{
rate = 7,
amount = 66.29
},
taxableItems = new List<EInvoiceModel.TaxableItem>
{
new EInvoiceModel.TaxableItem
{
taxType = "T1",
amount = 272.07,
subType = "T1",
rate = 12
}
}
}
}; //Invoice Lines End
//Items total Discount and Sales/NetAmount
ds.totalDiscountAmount = 76.29;
ds.totalSalesAmount = 1609.90;
ds.netAmount = 1533.61;
//Tax Total Start
ds.taxTotals = new List<EInvoiceModel.TaxTotal>
{
new EInvoiceModel.TaxTotal
{
taxType = "T1",
amount = 477.54,
}
};//Tax Total End
//Total Sales Amount & discounts
ds.totalAmount = 5191.50;
ds.extraDiscountAmount = 5.00;
ds.totalItemsDiscountAmount = 14.00;
string strResultJson = JsonConvert.SerializeObject(ds);
//System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\path.json", strResultJson);
// File.WriteAllText(#"ds.json", strResultJson);
// string jsonToSign = "{ ... }";
string jsonToSign = strResultJson;
// Create the CAdES-BES signature.
crypt.EncodingMode = "base64";
// Make sure we sign the utf-8 byte representation of the JSON string
crypt.Charset = "utf-8";
string sigBase64 = crypt.SignStringENC(jsonToSign);
// return Ok(ds);
return Ok(sigBase64);
}
public static string SerializeObject2(object obj, int indent = 0)
{
var sb = new StringBuilder();
if (obj != null)
{
string indentString = new string(' ', indent);
if (obj is string || obj.IsNumber())
{
sb.Append($"\"{obj}\"");
}
else if (obj.GetType().BaseType == typeof(Enum))
{
sb.Append($"\"{obj.ToString()}\"");
}
else if (obj is Array)
{
var elems = obj as IList;
sb.Append($"{indentString}- [{elems.Count}] :\n");
for (int i = 0; i < elems.Count; i++)
{
sb.Append(SerializeObject2(elems[i], indent + 4));
}
}
else
{
Type objType = (obj).GetType();
PropertyInfo[] props = objType.GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.GetIndexParameters().Length == 0)
{
object propValue = prop.GetValue(obj);
var elems = propValue as IList;
if (elems != null)
{
sb.Append($"\"{prop.Name.ToUpper()}\"");
foreach (var item in elems)
{
sb.Append($"\"{prop.Name.ToUpper()}\"");
sb.Append(SerializeObject2(item, indent + 4));
}
}
else
{
if (Assembly.GetExecutingAssembly().DefinedTypes.Select(p => p.Assembly).ToList().Contains(prop.PropertyType.Assembly))
{
sb.Append($"\"{prop.Name.ToUpper()}\"");
sb.Append(SerializeObject2(propValue, indent + 4));
}
else
{
sb.Append($"\"{prop.Name.ToUpper()}\"\"{propValue}\"");
}
}
}
else if (objType.GetProperty("Item") != null)
{
int count = -1;
if (objType.GetProperty("Count") != null &&
objType.GetProperty("Count").PropertyType == typeof(int))
{
count = (int)objType.GetProperty("Count").GetValue(obj, null);
}
for (int i = 0; i < count; i++)
{
object val = prop.GetValue(obj, new object[] { i });
sb.Append(SerializeObject2(val, indent + 4));
}
}
}
}
}
return sb.ToString();
}

Get string data Xpath

I need help to get data from the site. I use geckofx in my application. I want it to retrieve text data from the xpath location after loading the page
XPathResult xpathResult = geckoWebBrowser1.Document.EvaluateXPath("/html/body/table[3]/tbody/tr[1]/td[2]/a[1]");
IEnumerable<GeckoNode> foundNodes = xpathResult.GetNodes();
How to download data as text?
It looks like you are struggling to retrieve the text from the GeckoFX objects.
Here are a few calls and operations that should get you started:
//get by XPath
XPathResult xpathResult = _browser.Document.EvaluateXPath("//*[#id]/div/p[2]");
var foundNodes = xpathResult.GetNodes();
foreach (var node in foundNodes)
{
var x = node.TextContent; // get text text contained by this node (including children)
GeckoHtmlElement element = node as GeckoHtmlElement; //cast to access.. inner/outerHtml
string inner = element.InnerHtml;
string outer = element.OuterHtml;
//iterate child nodes
foreach (var child in node.ChildNodes)
{
}
}
//get by id
GeckoHtmlElement htmlElementById = _browser.Document.GetHtmlElementById("mw-content-text");
//get by tag
GeckoElementCollection byTag = _browser.Document.GetElementsByTagName("input");
foreach (var ele in byTag)
{
var y = ele.GetAttribute("value");
}
//get by class
var byClass = _browser.Document.GetElementsByClassName("input");
foreach (var node in byClass)
{
//...
}
//cast to a different object
var username = ((GeckoInputElement)_browser.Document.GetHtmlElementById("yourUsername")).Value;
//create new object from DomObject
var button = new GeckoButtonElement(_browser.Document.GetElementById("myBtn").DomObject);
public string extract(string xpath, string type)
{
string result = string.Empty;
GeckoHtmlElement elm = null;
GeckoWebBrowser wb = geckoWebBrowser1;//(GeckoWebBrowser)GetCurrentWB();
if (wb != null)
{
elm = GetElement(wb, xpath);
if (elm != null)
//UpdateUrlAbsolute(wb.Document, elm);
if (elm != null)
{
switch (type)
{
case "html":
result = elm.OuterHtml;
break;
case "text":
if (elm.GetType().Name == "GeckoTextAreaElement")
{
result = ((GeckoTextAreaElement)elm).Value;
}
else
{
result = elm.TextContent.Trim();
}
break;
case "value":
result = ((GeckoInputElement)elm).Value;
break;
default:
result = extractData(elm, type);
break;
}
}
}
return result;
}
private string extractData(GeckoHtmlElement ele, string attribute)
{
var result = string.Empty;
if (ele != null)
{
var tmp = ele.GetAttribute(attribute);
/*if (tmp == null)
{
tmp = extractData(ele.Parent, attribute);
}*/
if (tmp != null)
result = tmp.Trim();
}
return result;
}
private object GetCurrentWB()
{
if (tabControl1.SelectedTab != null)
{
if(tabControl1.SelectedTab.Controls.Count > 0)
//if (tabControl1.SelectedTab.Controls.Count > 0)
{
Control ctr = tabControl1.SelectedTab.Controls[0];
if (ctr != null)
{
return ctr as object;
}
}
}
return null;
}
private GeckoHtmlElement GetElement(GeckoWebBrowser wb, string xpath)
{
GeckoHtmlElement elm = null;
if (xpath.StartsWith("/"))
{
if (xpath.Contains("#class") || xpath.Contains("#data-type"))
{
var html = GetHtmlFromGeckoDocument(wb.Document);
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var node = doc.DocumentNode.SelectSingleNode(xpath);
if (node != null)
{
var currentXpath = "/" + node.XPath;
elm = (GeckoHtmlElement)wb.Document.EvaluateXPath(currentXpath).GetNodes().FirstOrDefault();
}
}
else
{
elm = (GeckoHtmlElement)wb.Document.EvaluateXPath(xpath).GetNodes().FirstOrDefault();
}
}
else
{
elm = (GeckoHtmlElement)wb.Document.GetElementById(xpath);
}
return elm;
}
private string GetHtmlFromGeckoDocument(GeckoDocument doc)
{
var result = string.Empty;
GeckoHtmlElement element = null;
var geckoDomElement = doc.DocumentElement;
if (geckoDomElement is GeckoHtmlElement)
{
element = (GeckoHtmlElement)geckoDomElement;
result = element.InnerHtml;
}
return result;
}
private void button5_Click(object sender, EventArgs e)
{
var text = extract("/html/body/table[3]/tbody/tr[1]/td[2]/a[2]", "text");
MessageBox.Show(text);
}
I also insert the code from which I used a little longer code but it also works. maybe someone will need it. The creator of the code is Đinh Công Thắng, Web Automation App,
Regards

Create Pivot Table Filters With EPPLUS

I am using EPPLUS excel library. Do you have an idea how to create pivot table with report filters, row label and values ? Some simple example will be excellent.
Here is a simple example. Note that EEPlus does not have the ability to do page filters so you will have to use (in order of difficulty) VBA, Excel Interop, or XML manipulation (I used XML below). You can put this code into a unit test of the EPPlus source download for easy testing:
const string FORMATCURRENCY = "#,###;[Red](#,###)";
var file = new FileInfo(#"c:\temp\temp.xlsx");
if (file.Exists)
file.Delete();
var pck = new ExcelPackage(file);
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("newsheet");
//The data
worksheet.Cells["A20"].Value = "Col1";
worksheet.Cells["A21"].Value = "sdf";
worksheet.Cells["A22"].Value = "wer";
worksheet.Cells["A23"].Value = "ghgh";
worksheet.Cells["A24"].Value = "sdf";
worksheet.Cells["A25"].Value = "wer";
worksheet.Cells["A26"].Value = "ghgh";
worksheet.Cells["A27"].Value = "sdf";
worksheet.Cells["A28"].Value = "wer";
worksheet.Cells["A29"].Value = "ghgh";
worksheet.Cells["B20"].Value = "Col2";
worksheet.Cells["B21"].Value = "Group A";
worksheet.Cells["B22"].Value = "Group B";
worksheet.Cells["B23"].Value = "Group A";
worksheet.Cells["B24"].Value = "Group C";
worksheet.Cells["B25"].Value = "Group A";
worksheet.Cells["B26"].Value = "Group B";
worksheet.Cells["B27"].Value = "Group C";
worksheet.Cells["B28"].Value = "Group C";
worksheet.Cells["B29"].Value = "Group A";
worksheet.Cells["C20"].Value = "Col3";
worksheet.Cells["C21"].Value = 453;
worksheet.Cells["C22"].Value = 634;
worksheet.Cells["C23"].Value = 274;
worksheet.Cells["C24"].Value = 453;
worksheet.Cells["C25"].Value = 634;
worksheet.Cells["C26"].Value = 274;
worksheet.Cells["C27"].Value = 453;
worksheet.Cells["C28"].Value = 634;
worksheet.Cells["C29"].Value = 274;
worksheet.Cells["D20"].Value = "Col4";
worksheet.Cells["D21"].Value = 686468;
worksheet.Cells["D22"].Value = 996440;
worksheet.Cells["D23"].Value = 185780;
worksheet.Cells["D24"].Value = 686468;
worksheet.Cells["D25"].Value = 996440;
worksheet.Cells["D26"].Value = 185780;
worksheet.Cells["D27"].Value = 686468;
worksheet.Cells["D28"].Value = 996440;
worksheet.Cells["D29"].Value = 185780;
//The pivot table
var pivotTable = worksheet.PivotTables.Add(worksheet.Cells["A4"], worksheet.Cells["A20:D29"], "test");
//The label row field
pivotTable.RowFields.Add(pivotTable.Fields["Col1"]);
pivotTable.DataOnRows = false;
//The data fields
var field = pivotTable.DataFields.Add(pivotTable.Fields["Col3"]);
field.Name = "Sum of Col2";
field.Function = DataFieldFunctions.Sum;
field.Format = FORMATCURRENCY;
field = pivotTable.DataFields.Add(pivotTable.Fields["Col4"]);
field.Name = "Sum of Col3";
field.Function = DataFieldFunctions.Sum;
field.Format = FORMATCURRENCY;
//The page field
pivotTable.PageFields.Add(pivotTable.Fields["Col2"]);
var xdCacheDefinition = pivotTable.CacheDefinition.CacheDefinitionXml;
var xeCacheFields = xdCacheDefinition.FirstChild["cacheFields"];
if (xeCacheFields == null)
return;
//To filter, add items to the Cache Definition via XML
var count = 0;
var assetfieldidx = -1;
foreach (XmlElement cField in xeCacheFields)
{
var att = cField.Attributes["name"];
if (att != null && att.Value == "Col2" )
{
assetfieldidx = count;
var sharedItems = cField.GetElementsByTagName("sharedItems")[0] as XmlElement;
if(sharedItems == null)
continue;
//set the collection attributes
sharedItems.RemoveAllAttributes();
att = xdCacheDefinition.CreateAttribute("count");
att.Value = "3";
sharedItems.Attributes.Append(att);
//create and add the item
var item = xdCacheDefinition.CreateElement("s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = "Group A";
item.Attributes.Append(att);
sharedItems.AppendChild(item);
item = xdCacheDefinition.CreateElement("s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = "Group B";
item.Attributes.Append(att);
sharedItems.AppendChild(item);
item = xdCacheDefinition.CreateElement("s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = "Group C";
item.Attributes.Append(att);
sharedItems.AppendChild(item);
break;
}
count++;
}
//Now go back to the main pivot table xml and add the cross references to complete filtering
var xdPivotTable = pivotTable.PivotTableXml;
var xdPivotFields = xdPivotTable.FirstChild["pivotFields"];
if (xdPivotFields == null)
return;
count = 0;
foreach (XmlElement pField in xdPivotFields)
{
//Find the asset type field
if (count == assetfieldidx)
{
var att = xdPivotTable.CreateAttribute("multipleItemSelectionAllowed");
att.Value = "1";
pField.Attributes.Append(att);
var items = pField.GetElementsByTagName("items")[0] as XmlElement;
items.RemoveAll();
att = xdPivotTable.CreateAttribute("count");
att.Value = "4";
items.Attributes.Append(att);
pField.AppendChild(items);
//Add the classes to the fields item collection
for (var i = 0; i < 3; i++)
{
var item = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("x");
att.Value = i.ToString(CultureInfo.InvariantCulture);
item.Attributes.Append(att);
//Turn of the Cash class in the fielder
if (i == 1)
{
att = xdPivotTable.CreateAttribute("h");
att.Value = "1";
item.Attributes.Append(att);
}
items.AppendChild(item);
}
//Add the default
var defaultitem = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("t");
att.Value = "default";
defaultitem.Attributes.Append(att);
items.AppendChild(defaultitem);
break;
}
count++;
}
pck.Save();
Sorry for all the edit but I have been working on this for a little while when I stumbled on this question. I created an extension method just for applying a filter. Give it the field name (it assumes there is a header line contining the column names), the filters you want to apply, and the worksheet containing the data or it will just the Pivot Table worksheet if no data worksheet is passed in. It have done basic testing so you should QA:
public static bool FilterField(this ExcelPivotTable pivotTable, string pageFieldName, IEnumerable<object> filters, ExcelWorksheet dataWorksheet = null)
{
//set the worksheet
var ws = dataWorksheet ?? pivotTable.WorkSheet;
//Set the cache definitions and cache fields
var xdCacheDefinition = pivotTable.CacheDefinition.CacheDefinitionXml;
var xeCacheFields = xdCacheDefinition.FirstChild["cacheFields"];
if (xeCacheFields == null)
return false;
//Go the field list in the definitions, note the field idx and valuesfor
var count = 0;
var fieldIndex = -1;
List<object> fieldValues = null;
foreach (XmlElement cField in xeCacheFields)
{
var att = cField.Attributes["name"];
if (att != null && att.Value.Equals(pageFieldName, StringComparison.OrdinalIgnoreCase))
{
//store the field data
fieldIndex = count;
var dataddress = new ExcelAddress(pivotTable.CacheDefinition.SourceRange.Address);
var valueHeader = ws
.Cells[dataddress.Start.Row, dataddress.Start.Column, dataddress.Start.Row, dataddress.End.Column]
.FirstOrDefault(cell => cell.Value.ToString().Equals(pageFieldName, StringComparison.OrdinalIgnoreCase));
if (valueHeader == null)
return false;
//Get the range minus the header row
var valueObject = valueHeader.Offset(1, 0, dataddress.End.Row - dataddress.Start.Row, 1).Value;
var values = (object[,])valueObject;
fieldValues = values
.Cast<object>()
.Distinct()
.ToList();
//kick back if the types are mixed
if (fieldValues.FirstOrDefault(v => v is string) != null && fieldValues.FirstOrDefault(v => !(v is string)) != null)
throw new NotImplementedException("Filter function does not (yet) support mixed parameter types");
//fill in the shared items for the field
var sharedItems = cField.GetElementsByTagName("sharedItems")[0] as XmlElement;
if (sharedItems == null)
continue;
//Reset the collection attributes
sharedItems.RemoveAllAttributes();
//Handle numerics - assume all or nothing
var isNumeric = fieldValues.FirstOrDefault(v => v is string) == null;
if (isNumeric)
{
att = xdCacheDefinition.CreateAttribute("containsSemiMixedTypes");
att.Value = "0";
sharedItems.Attributes.Append(att);
att = xdCacheDefinition.CreateAttribute("containsString");
att.Value = "0";
sharedItems.Attributes.Append(att);
att = xdCacheDefinition.CreateAttribute("containsNumber");
att.Value = "1";
sharedItems.Attributes.Append(att);
att = xdCacheDefinition.CreateAttribute("containsInteger");
att.Value = fieldValues.Any(v => !(v is int || v is long)) ? "0" : "1";
sharedItems.Attributes.Append(att);
}
//add the count
att = xdCacheDefinition.CreateAttribute("count");
att.Value = fieldValues.Count.ToString(CultureInfo.InvariantCulture);
sharedItems.Attributes.Append(att);
//create and add the item
foreach (var fieldvalue in fieldValues)
{
var item = xdCacheDefinition.CreateElement(isNumeric ? "n" : "s", sharedItems.NamespaceURI);
att = xdCacheDefinition.CreateAttribute("v");
att.Value = fieldvalue.ToString();
item.Attributes.Append(att);
sharedItems.AppendChild(item);
}
break;
}
count++;
}
if (fieldIndex == -1 || fieldValues == null)
return false;
//Now go back to the main pivot table xml and add the cross references to complete filtering
var xdPivotTable = pivotTable.PivotTableXml;
var xdPivotFields = xdPivotTable.FirstChild["pivotFields"];
if (xdPivotFields == null)
return false;
var filtervalues = filters.ToList();
count = 0;
foreach (XmlElement pField in xdPivotFields)
{
//Find the asset type field
if (count == fieldIndex)
{
var att = xdPivotTable.CreateAttribute("multipleItemSelectionAllowed");
att.Value = "1";
pField.Attributes.Append(att);
var items = pField.GetElementsByTagName("items")[0] as XmlElement;
if (items == null)
return false;
items.RemoveAll();
att = xdPivotTable.CreateAttribute("count");
att.Value = (fieldValues.Count + 1).ToString(CultureInfo.InvariantCulture);
items.Attributes.Append(att);
pField.AppendChild(items);
//Add the classes to the fields item collection
for (var i = 0; i < fieldValues.Count; i++)
{
var item = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("x");
att.Value = i.ToString(CultureInfo.InvariantCulture);
item.Attributes.Append(att);
if (filtervalues.Contains(fieldValues[i]))
{
att = xdPivotTable.CreateAttribute("h");
att.Value = "1";
item.Attributes.Append(att);
}
items.AppendChild(item);
}
//Add the default
var defaultitem = xdPivotTable.CreateElement("item", items.NamespaceURI);
att = xdPivotTable.CreateAttribute("t");
att.Value = "default";
defaultitem.Attributes.Append(att);
items.AppendChild(defaultitem);
break;
}
count++;
}
return true;
}
To use it in the above example, you would do something like this:
pivotTable.FilterField("Col2", new List<string> { "Group B" });

Dynamic Report building Refresh() is not changing data

I am trying to View a report dynamically from code behind. But when the parameters are changed from dynamic textboxes added in the page. in the report refresh() the data is not changed.
I call sqlDS() and reportBuild() in the !IsPostback.
This method is for defining the sqlDatasource:
protected void sqlDS()
{
string conString, prName = "";
int counter = 0;
Reporting rep = new Reporting();
rep = rep.searchReport(repID_HF.Value);
Reporting repFold = new Reporting();
repFold = repFold.searchFolder(foldID_HF.Value);
if (repFold.FolderName.Split('(')[1] == "Web Reports)")
{
conString = dbSql.connectionStringAll;
prName = dbSql.providerName;
}
else
{
conString = db.connectionStringAll;
prName = db.providerName;
}
SqlDataSource1.ConnectionString = conString;
SqlDataSource1.ProviderName = prName;
string sqlString = System.IO.File.ReadAllText(Server.MapPath("~/Reports/SQLs/" + rep.SqlFile));
sqlString.Replace(System.Environment.NewLine, " ");
SqlDataSource1.SelectCommand = sqlString;
SqlDataSource1.CancelSelectOnNullParameter = false;
Reporting repParam = new Reporting();
allPs = repParam.getAllParamRep(rep.RepID);
foreach (Reporting itemParam in allPs)
{
if (itemParam.ParamType == "Date")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Text")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Menu")
{
counter++;
}
}
}
This method is for declaring the report properties:
protected void reportBuild()
{
Reporting rep2 = new Reporting();
rep2 = rep2.searchReport(repID_HF.Value);
ReportViewer1.LocalReport.ReportPath = "Reports/RDLC/" + rep2.RdlcFile;
this.ReportViewer1.LocalReport.ReportEmbeddedResource = rep2.RdlcFile;
ReportParameter[] paramss = new ReportParameter[SqlDataSource1.SelectParameters.Count];
for (int i = 0; i < SqlDataSource1.SelectParameters.Count; i++)
{
paramss[i] = new ReportParameter(SqlDataSource1.SelectParameters[i].Name.Split(':')[1], SqlDataSource1.SelectParameters[i].DefaultValue);
}
ReportDataSource rds = new ReportDataSource(rep2.DatasetName.Split('.')[0], SqlDataSource1);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
//paramss[0] = new ReportParameter("TDATE", SqlDataSource1.SelectParameters[0].DefaultValue);
//paramss[1] = new ReportParameter("CUST_NUM", SqlDataSource1.SelectParameters[1].DefaultValue);
ReportViewer1.LocalReport.SetParameters(paramss);
ReportViewer1.LocalReport.Refresh();
}
In the reportViewer refresh method i try to set the new parameters according to the dynamic textboxes added in the page:
protected void ReportViewer1_ReportRefresh(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (Control txt in Panel1.Controls)
{
if (txt is TextBox)
{
txts.Add(txt);
}
}
foreach (TextBox txtbox in txts)
{
Reporting repP = new Reporting();
repP = repP.searchParam(txtbox.Attributes["pID"].ToString());
if (repP.ParamType == "Date")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
else if (repP.ParamType == "Text")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
}
//Reporting r = new Reporting();
//r = r.searchReport(repID_HF.Value);
//Reporting rep = new Reporting();
//rep = rep.searchReport(repID_HF.Value);
//ReportDataSource rds = new ReportDataSource(rep.DatasetName.Split('.')[0], SqlDataSource1);
//this.ReportViewer1.Reset();
//ReportViewer1.LocalReport.DataSources.Clear();
//ReportViewer1.LocalReport.DataSources.Add(rds);
ReportParameterInfoCollection x = ReportViewer1.LocalReport.GetParameters();
//Response.Redirect(Request.RawUrl);
ReportViewer1.LocalReport.Refresh();
}
I tried debugging and found every thing is working correctly the SQL parameters changed, the Report Parameters also is changed.
so why the data in the report is not changed? Plz help me
I got a better and easier way to solve this problem using this link
http://www.igregor.net/post/2007/12/Adding-Controls-to-an-ASPNET-form-Dynamically.aspx
And you can use array of strings to pass attributes.

Create A treenode with List

I have a table in this structure
ListA labelName
1 Colorado
1 Wyoming
1 Illinois
2 New York
2 Ohio
I am trying to create a tree where if LISTA = 1, it goes under one node called "header one" and Colorado, Wyoming, Illinois as its Leaf and samething with value "2"... by doing this I am getting 3 "Header one" nodes instead of having all those three nodes under one...
SqlCommand cmd = con.CreateCommand();
comd.CommandText = "SELECT * FROM myTable";
con.Open();
SqlDataReader reader = comd.ExecuteReader();
while (reader.Read())
{
City MyData = new City();
MyData.ListA = reader["ListA"].ToString().Trim();
MyData.labelName = reader["labelName"].ToString().Trim();
giveData.Add(MyData);
}
int count = 1;
List<TreeNode> myNode = new List<TreeNode>();
foreach (City MyData in giveData)
{
// 1st foreach
if (MyData.ListA != "1")
{
TreeNode treeNode = new TreeNode();
treeNode.id = count++;
treeNode.name = "Header One";
treeNode.leaf = false;
List<TreeNode> Level1 = new List<TreeNode>();
foreach (City labelName in giveData)
{
if (labelName.ListA == "1")
{// 2nd foreach
TreeNode node1 = new TreeNode();
node1.id = count++;
node1.name = labelName.labelName;
node1.leaf = true;
Level1.Add(node1);
}
}
treeNode.children = Level1;
myNode.Add(treeNode);
}
else if (MyData.ListA != "2")
{
TreeNode treeNode = new TreeNode();
treeNode.id = count++;
treeNode.name = "Header Two";
treeNode.leaf = false;
List<TreeNode> Level1 = new List<TreeNode>();
foreach (City labelName in giveData)
{
if (labelName.ListA == "2")
{// 2nd foreach
TreeNode node1 = new TreeNode();
node1.id = count++;
node1.name = labelName.labelName;
node1.leaf = true;
Level1.Add(node1);
}
}
treeNode.children = Level1;
myNode.Add(treeNode);
}
}
return JsonConvert.SerializeObject(myNode);
What would be the best way to handle this
What you need to do is group the data on ListA.
var groups = giveData.GroupBy(state => state.ListA);
foreach(var group in groups)
{
//add header to treeview
string header = group.Key;
foreach(var state in group)
{
//add this state as a child of the group you just added
}
}
I'd also suggest creating a lookup to help you map the ListA number to it's textual representation:
var headerLookup = new Dictionary<string, string>()
{
{"1", "Header One"},
{"2", "Header Two"},
{"3", "Header Three"}
};
This will allow you to do the following:
string headerText = headerLookup[group.Key];

Categories