I am currently having hard time with Treeview loading. My application has a central panel where multiple user controls are loaded. Each one got a treeview of 5 parent nodes (Groups) owning tens of children nodes (Persons) with a total of 50 nodes.
Same function load the treeview (see down here) :
First loop is adding the Groups and the second loop (into the first) adds the Persons.
That function takes about 10 seconds to load 50 nodes. Which is an eternity in my world.
Don't know what to do to enhance this one. Please have a look at this function.
public static List<TreeNode> ArbreCommun(Guid idUser)
{
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
List<TreeNode> ArbreParent = new List<TreeNode>();
using (bdd_compactEntities contexte = new bdd_compactEntities())
{
if (contexte.Groupe.Count() > 0)
foreach (Groupe grpItem in contexte.Groupe)
{
if (grpItem.g_nom == "Tous")
{
TreeNode Tous = new TreeNode();
Tous.Text = grpItem.g_nom + " (" + contexte.Personne.Count() + ")";
Tous.Tag = grpItem.id;
Tous.ToolTipText = "ID groupe = " + grpItem.id;
Tous.ImageKey = "group";
Tous.SelectedImageKey = "group";
foreach (Personne pers in FonctionsYou.ChargementPersonnesTous())
{
TreeNode PersonneNode = new TreeNode();
PersonneNode.Text = pers.p_nom + " " + pers.p_prenom;
PersonneNode.Tag = pers.id;
PersonneNode.ToolTipText = "ID personne = " + pers.id;
if (FonctionsYou.HasGroupe(idUser, FonctionsYou.GetGroupeIdPers(pers.id)))
{
if (FonctionsYou.CheckDisponibiliteAthlete(pers.id))
{
PersonneNode.ForeColor = Color.Blue;
PersonneNode.ImageKey = "dispo";
PersonneNode.SelectedImageKey = "dispo";
}
else
{
PersonneNode.ForeColor = Color.Red;
PersonneNode.ImageKey = "blesse";
PersonneNode.SelectedImageKey = "blesse";
}
}
Tous.Nodes.Add(PersonneNode);
}
ArbreParent.Add(Tous);
}
else
{
TreeNode GroupeNode = new TreeNode();
GroupeNode.Text = grpItem.g_nom + " (" + grpItem.Personne.Count() + ")";
GroupeNode.Tag = grpItem.id;
GroupeNode.ToolTipText = "ID groupe = " + grpItem.id;
GroupeNode.ImageKey = "group";
GroupeNode.SelectedImageKey = "group";
if (FonctionsYou.HasGroupe(idUser, grpItem.id))
{
GroupeNode.ForeColor = Color.Green;
}
foreach (Personne pers in contexte.Personne.Where(x => x.Groupe_id == grpItem.id))
{
TreeNode PersonneNode = new TreeNode();
PersonneNode.Text = pers.p_nom + " " + pers.p_prenom;
PersonneNode.Tag = pers.id;
PersonneNode.ToolTipText = "ID personne = " + pers.id;
if (FonctionsYou.HasGroupe(idUser, FonctionsYou.GetGroupeIdPers(pers.id)))
{
if (FonctionsYou.CheckDisponibiliteAthlete(pers.id))
{
PersonneNode.ForeColor = Color.Blue;
PersonneNode.ImageKey = "dispo";
PersonneNode.SelectedImageKey = "dispo";
}
else
{
PersonneNode.ForeColor = Color.Red;
PersonneNode.ImageKey = "blesse";
PersonneNode.SelectedImageKey = "blesse";
}
}
GroupeNode.Nodes.Add(PersonneNode);
}
ArbreParent.Add(GroupeNode);
}
}
}
stopWatch.Stop();
MessageBox.Show(stopWatch.ElapsedMilliseconds + " ms");
return ArbreParent;
}
By the way, here is my calling method :
List<TreeNode> _itemsNodes = FonctionsYou.ArbreCommun(userConnecte.uid);
treeview_arbre.ImageList = FonctionsYou.GetImageListTV();
// Display a wait cursor while the TreeNodes are being created.
Cursor.Current = Cursors.WaitCursor;
// Suppress repainting the TreeView until all the objects have been created.
treeview_arbre.BeginUpdate();
foreach (TreeNode node in _itemsNodes)
{
treeview_arbre.Nodes.Add(node);
}
// Reset the cursor to the default for all controls.
Cursor.Current = Cursors.Default;
// Begin repainting the TreeView.
treeview_arbre.EndUpdate();
Related
I have an API that loops through addresses and cleanses them. I am testing it with about 40k addresses, and it takes several hours to loop through thousands of them. Sometimes it throws an error and closes out the application and I have to start it over. Is there a way that I can write in error handling into the catch, that if there is an error, it will just log it, but continue running the app?
I am using VS 2019, C#, Windows Forms.
public class Elements
{
public string streetaddress1 { get; set; }
public string streetaddress2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public string country { get; set; }
}
void Output(string strDebugText)
{
try
{
System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
txtResponse.SelectionStart = txtResponse.TextLength;
txtResponse.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
private void btnMultiple_Click(object sender, EventArgs e)
{
//Loads address that need to be cleansed
string filePath = #"C:data.csv";
List<Elements> addresses = new List<Elements>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split(',');
Elements newElement = new Elements();
newElement.streetaddress1 = entries[0];
newElement.streetaddress2 = entries[1];
newElement.city = entries[2];
newElement.state = entries[3];
newElement.zip = entries[4];
addresses.Add(newElement);
}
foreach (var Element in addresses)
{
Output($"{ Element.streetaddress1 } { Element.city} { Element.state } { Element.zip } " +
$"{ Element.country }");
var venvMulti = new AreaLookup.VertexEnvelope();
var clientMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqMulti = new AreaLookup.TaxAreaRequestType();
var reqresMulti = new AreaLookup.TaxAreaResultType();
var resMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLMulti;
string outputXMLMulti;
var TALMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateMulti = new DateTime();
var resTypeMulti = new AreaLookup.TaxAreaLookupResultType();
var postalMulti = new AreaLookup.PostalAddressType();
string StrNoteMulti = "";
int i, y;
var x = default(int);
postalMulti.MainDivision = Element.state;
postalMulti.City = Element.city;
postalMulti.PostalCode = Element.zip;
postalMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateMulti = Conversions.ToDate("2020-12-11");
TALMulti.asOfDate = TALasofDateMulti;
TALMulti.Item = postalMulti;
reqMulti.TaxAreaLookup = TALMulti;
var LITMulti = new AreaLookup.LoginType();
venvMulti.Login = new AreaLookup.LoginType();
venvMulti.Login.UserName = "****";
venvMulti.Login.Password = "****";
venvMulti.Item = reqMulti;
inputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(inputXMLMulti);
try
{
clientMulti.LookupTaxAreas90(ref venvMulti);
resMulti = (AreaLookup.TaxAreaResponseType)venvMulti.Item;
outputXMLMulti = (string)SerializeObjectToString(venvMulti);
Output(outputXMLMulti);
var loopTo = resMulti.TaxAreaResult.Length - 1;
}
catch (NullReferenceException)
{
Console.WriteLine("Null");
}
reqMulti = default;
reqresMulti = default;
resMulti = default;
void debugOutputCleansedMulti(string strDebugTextCleansedMulti)
{
try
{
System.Diagnostics.Debug.Write(strDebugTextCleansedMulti + Environment.NewLine);
txtCleansed.Text = txtCleansed.Text + strDebugTextCleansedMulti + Environment.NewLine;
txtCleansed.SelectionStart = txtCleansed.TextLength;
txtCleansed.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
debugOutputCleansedMulti("Address Cleanse Started: ");
var venvCleansedMulti = new AreaLookup.VertexEnvelope();
var clientCleansedMulti = new AreaLookup.LookupTaxAreasWS90Client();
var reqCleansedMulti = new AreaLookup.TaxAreaRequestType();
var reqresCleansedMulti = new AreaLookup.TaxAreaResultType();
var resCleansedMulti = new AreaLookup.TaxAreaResponseType();
string inputXMLCleansedMulti;
string outputXMLCleansedMulti;
var TALCleansedMulti = new AreaLookup.TaxAreaLookupType();
var TALasofDateCleansedMulti = new DateTime();
var resTypeCleansedMulti = new AreaLookup.TaxAreaLookupResultType();
var postalCleansedMulti = new AreaLookup.PostalAddressType();
string StrNoteCleansedMulti = "";
int a, b;
var c = default(int);
postalCleansedMulti.MainDivision = Element.state;
postalCleansedMulti.City = Element.city;
postalCleansedMulti.PostalCode = Element.zip;
postalCleansedMulti.StreetAddress1 = Element.streetaddress1;
TALasofDateCleansedMulti = Conversions.ToDate("2020-12-11");
TALCleansedMulti.asOfDate = TALasofDateCleansedMulti;
TALCleansedMulti.Item = postalCleansedMulti;
reqCleansedMulti.TaxAreaLookup = TALCleansedMulti;
var LITCleansedMulti = new AreaLookup.LoginType();
venvCleansedMulti.Login = new AreaLookup.LoginType();
venvCleansedMulti.Login.UserName = "****";
venvCleansedMulti.Login.Password = "****";
venvCleansedMulti.Item = reqCleansedMulti;
int j = 1;
//inputXMLCleansed = resCleansed.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " - " + resCleansed.TaxAreaResult[0].PostalAddress[0].PostalCode + " - " + resCleansed.TaxAreaResult[0].confidenceIndicator;
//debugOutputCleansed(inputXMLCleansed);
try
{
clientCleansedMulti.LookupTaxAreas90(ref venvCleansedMulti);
resCleansedMulti = (AreaLookup.TaxAreaResponseType)venvCleansedMulti.Item;
debugOutputCleansedMulti(resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + " | Street Address 1" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + " | Street Address 2" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + " | County" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + " | City" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + " | Zip Code" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + " | State" + Environment.NewLine +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator + " | Confidence Indicator");
string pathCleansed = #"C:\dev\data\data.csv";
string[] createText = {
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress1 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].StreetAddress2 + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].City + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].MainDivision + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].PostalCode + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].Country + "," +
resCleansedMulti.TaxAreaResult[0].PostalAddress[0].SubDivision + "," +
resCleansedMulti.TaxAreaResult[0].confidenceIndicator
};
File.AppendAllLines(pathCleansed, createText, System.Text.Encoding.UTF8);
txtCounter.Text = j.ToString();
j++;
var loopTo = resCleansedMulti.TaxAreaResult.Length - 1;
for (b = 0; b <= loopTo; b++)
{
if (c == 0)
{
StrNoteCleansedMulti = resCleansedMulti.TaxAreaResult[b].PostalAddress[0].StreetAddress1 + " - " + resCleansedMulti.TaxAreaResult[b].confidenceIndicator; c = 1;
}
else
{
StrNoteCleansedMulti += ", " + resCleansedMulti.TaxAreaResult[b].taxAreaId + " - " + resMulti.TaxAreaResult[b].confidenceIndicator;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
reqCleansedMulti = default;
reqresCleansedMulti = default;
resCleansedMulti = default;
}
}
Essentially you need a way to save your work in progress. One pattern would be to load the file and store it in a database, then as you process each line you mark off which item you have processed. If you did this I would split the code into different modules, importing file, processing file, and exporting results.
Another simpler approach might be to write the results out as you process them, and record the line number from the input file. Then if you have to restart, find the last line you output and use that to skip reprocessing the items in your input file
I am trying to make a restaurant form which stores data to a database when a user orders food. If the user comes again and enters his first and last name, the other data, like food and pickup option, should be filed automatically. For the food, I have a checkbox.
Here is the insert code:
string strCheckValue = "";
if (CheckBox1.Checked)
{
strCheckValue = strCheckValue + "," + CheckBox1.Text;
}
if (CheckBox2.Checked)
{
strCheckValue = strCheckValue + "," + CheckBox2.Text;
}
if (CheckBox3.Checked)
{
strCheckValue = strCheckValue + "," + CheckBox3.Text;
}
if (CheckBox4.Checked)
{
strCheckValue = strCheckValue + "," + CheckBox4.Text;
}
if (CheckBox5.Checked)
{
strCheckValue = strCheckValue + "," + CheckBox5.Text;
}
if (CheckBox6.Checked)
{
strCheckValue = strCheckValue + "," + CheckBox6.Text;
}
if (CheckBox7.Checked)
{
strCheckValue = strCheckValue + "," + CheckBox7.Text;
}
The strCheckValue is stored in the database and gives result like this:
,Samosa,Biryani,Naan
Now I want to select all the food items a user previously selected while ordering the food when he hits remember me button.
For that my code is:
//checkbox value display
CheckBox1.Checked = false;
CheckBox2.Checked = false;
CheckBox3.Checked = false;
CheckBox4.Checked = false;
CheckBox5.Checked = false;
CheckBox6.Checked = false;
CheckBox7.Checked = false;
string aa = dr["ctm_food"].ToString();
string[] a = aa.Split(',');
Label10.Text = a[2].ToString();
foreach (Control cc in this.Controls)
{
if(cc is CheckBox)
{
CheckBox b = (CheckBox)cc;
for(int j=1; j<a.Length; j++)
{
if (a[j].ToString() == b.Text)
{
b.Checked = true;
}
}
}
}
In label10, I can see the food that the user ordered. But the checkbox is not getting selected. What will be the right approach to complete this exercise?
I believe this.Controls does not contain your checkboxes. It will also simplify your code if you'd keep all checkbox references in one place.
CheckBox[] checkboxes = new CheckBox[] {
CheckBox1, CheckBox2, CheckBox3, CheckBox4, CheckBox5, CheckBox6, CheckBox7
};
string aa = dr["ctm_food"].ToString();
string[] a = aa.Split(',');
Label10.Text = a[2].ToString();
foreach (CheckBox b in checkboxes) {
b.Checked = false;
for (int j = 1; j < a.Length; j++) {
if (a[j].ToString() == b.Text) {
b.Checked = true;
}
}
}
I would like my web browser to save visited sights into a history xml file.I have two forms for history and web browser. I would like to get the url bar text into my history form where I have the method to to write an xml file.
This is what I tried. (web browser form)
public String historyURL
{
get
{
return urlBar.Text;
}
And in my History form I tried to call this method
private void addHistory(string url, string data)
{
url = this.WebBrowserForm.historyURL.ToString();
XmlDocument myXml = new XmlDocument();
int i=1;
XmlElement el = myXml.CreateElement("item");
el.SetAttribute("url", url);
el.SetAttribute("lastVisited", data);
My showHistory method
private void showHistory()
{
historyTreeView.Nodes.Clear();
XmlDocument myXml = new XmlDocument();
if (File.Exists(historyXml))
{
myXml.Load(historyXml);
DateTime now = DateTime.Now;
if (sortHistory.Text.Equals("Ordered Visited Today"))
{
historyTreeView.ShowRootLines = false;
foreach (XmlElement el in myXml.DocumentElement.ChildNodes)
{
DateTime d = DateTime.Parse(el.GetAttribute("lastVisited"));
if (!(d.Date == now.Date)) return;
TreeNode node =
new TreeNode(el.GetAttribute("url"), 3, 3);
node.ToolTipText = el.GetAttribute("url") + "\nLast Visited: " + el.GetAttribute("lastVisited") + "\nTimes Visited: " + el.GetAttribute("times");
node.Name = el.GetAttribute("url");
node.ContextMenuStrip = histContextMenu;
historyTreeView.Nodes.Add(node);
}
}
if (sortHistory.Text.Equals("View by Date"))
{
historyTreeView.ShowRootLines = true;
historyTreeView.Nodes.Add("2 Weeks Ago", "2 Weeks Ago", 2, 2);
historyTreeView.Nodes.Add("Last Week", "Last Week", 2, 2);
historyTreeView.Nodes.Add("This Week", "This Week", 2, 2);
historyTreeView.Nodes.Add("Yesterday", "Yesterday", 2, 2);
historyTreeView.Nodes.Add("Today", "Today", 2, 2);
foreach (XmlElement el in myXml.DocumentElement.ChildNodes)
{
DateTime d = DateTime.Parse(el.GetAttribute("lastVisited"));
TreeNode node = new TreeNode(el.GetAttribute("url"), 3, 3);
node.ToolTipText = el.GetAttribute("url") + "\nLast Visited: " + el.GetAttribute("lastVisited") + "\nTimes Visited: " + el.GetAttribute("times");
node.Name = el.GetAttribute("url");
node.ContextMenuStrip = histContextMenu;
if (d.Date == now.Date)
historyTreeView.Nodes[4].Nodes.Add(node);
else
if (d.AddDays(1).ToShortDateString().Equals(now.ToShortDateString()))
historyTreeView.Nodes[3].Nodes.Add(node);
else
if (d.AddDays(7) > now)
historyTreeView.Nodes[2].Nodes.Add(node);
else
if (d.AddDays(14) > now)
historyTreeView.Nodes[1].Nodes.Add(node);
else
if (d.AddDays(21) > now)
historyTreeView.Nodes[0].Nodes.Add(node);
else
if (d.AddDays(22) > now)
myXml.DocumentElement.RemoveChild(el);
}
My full addHistory method for refference
private void addHistory(string url, string data)
{
url = this.WebBrowserForm.historyURL.ToString();
XmlDocument myXml = new XmlDocument();
int i=1;
XmlElement el = myXml.CreateElement("item");
el.SetAttribute("url", url);
el.SetAttribute("lastVisited", data);
if (!File.Exists(historyXml))
{
XmlElement root = myXml.CreateElement("history");
myXml.AppendChild(root);
el.SetAttribute("times", "1");
root.AppendChild(el);
}
else
{
myXml.Load(historyXml);
foreach (XmlElement x in myXml.DocumentElement.ChildNodes)
{
if (x.GetAttribute("url").Equals(url))
{
i = int.Parse(x.GetAttribute("times")) + 1;
myXml.DocumentElement.RemoveChild(x);
break;
}
}
el.SetAttribute("times", i.ToString());
myXml.DocumentElement.InsertBefore(el, myXml.DocumentElement.FirstChild);
/*ordered visited today*/
if (sortHistory.Text.Equals("Ordered Visited Today"))
{
if (!historyTreeView.Nodes.ContainsKey(url))
{
TreeNode node =
new TreeNode(url, 3, 3);
node.ToolTipText = url + "\nLast Visited: " + data + "\nTimes visited :" + i.ToString();
node.Name = url.ToString();
node.ContextMenuStrip = histContextMenu;
historyTreeView.Nodes.Insert(0, node);
}
else
historyTreeView.Nodes[url].ToolTipText
= url + "\nLast Visited: " + data + "\nTimes visited: " + i.ToString();
}
/* view by date*/
if (sortHistory.Text.Equals("View by Date"))
{
if (historyTreeView.Nodes[4].Nodes.ContainsKey(url))
historyTreeView.Nodes[url].ToolTipText
= url.ToString() + "\nLast Visited: " + data + "\nTimes visited: " + i.ToString();
else
{
TreeNode node =
new TreeNode(url, 3, 3);
node.ToolTipText = url + "\nLast Visited: " + data + "\nTimes visited :" + i.ToString();
node.Name = url;
node.ContextMenuStrip = histContextMenu;
historyTreeView.Nodes[4].Nodes.Add(node);
}
}
}
myXml.Save(historyXml);
}
Where am I going wrong?
how to recognize new line c# while uploading word documents..? i have to give next line as a new word in word document here what is happening means if i add three or more words in .doc in separate line its taking as one word i want to separate the words but if i give a space after a word it is taking as expected without giving space if i start a new word in new line its taking as one word
money
power
cash
moneypowercash
like this iam getting here if i give space after these words its getting as expected
how to resolve this issue here i will give my code to generating this keyword
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (cmbDepartment.SelectedValue != "0" && cmbDocumentType.SelectedValue != "0")
{
TodayDate = DateTime.Today.ToString("yyyy-MM-dd");
TempFolder = System.Configuration.ConfigurationManager.AppSettings["TempWorkFolder"];
TextReader reader = new FilterReader(TempFolder + Session["EncyptImgName"]);
StringBuilder Keywords = new StringBuilder();
using (reader)
{
Keywords = Keywords.Append(reader.ReadToEnd());
}
//remove common words
string[] removablewords = { ":", ".", "~"};
foreach (string st in removablewords)
{
Keywords.Replace(st, " ");
}
//Reomve unwated spaces
while (Keywords.ToString().Contains(" "))
{
Keywords.Replace(" ", " ");
}
string str = Keywords.ToString();
Keywords.Clear();
Keywords.Append("<words><s>" + str.Replace(" ", "</s><s>") + "</s></words>");
string xml = Keywords.ToString();
XElement items = XElement.Parse(xml);
var groups = from t in items.Descendants("s")
group t by t.Value.ToLower() into g
select new KeyFrequency(g.Key, g.Count());
groups = groups.OrderByDescending(g => g.Frequency).Take(15);
keyvalues = new List<string>();
foreach (KeyFrequency g in groups)
{
keyvalues.Add(g.Key);
}
for (key = 0; key < keyvalues.Count && key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = true;
btn.Text = keyvalues[key];
btn.CommandArgument = keyvalues[key];
}
if (key < 10)
{
for (key = key; key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = false;
}
}
else
{
AsyncFileUpload1.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
Button1.Text = "Keywords Not Available for This Document";
Button1.CommandArgument = null;
Button2.Visible = false;
Button3.Visible = false;
Button4.Visible = false;
Button5.Visible = false;
Button6.Visible = false;
Button7.Visible = false;
Button8.Visible = false;
Button9.Visible = false;
Button10.Visible = false;
}
}
For each new line, try replacing \n with "</w:t><w:br/><w:t>". It worked for me.
string.Replace("\n", "</w:t><w:br/><w:t>")
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.