How to make my browser save URLs from a different form - c#

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?

Related

Is there a way to retrieve events (appointments) from all Outlook's shared calendars?

My problem is, I can't access and so iterate Outlook's shared calendars. I've tried several ways but they all take me back to the default calendar (i.e. my account calendar).
I tried to loop in the subfolders, the GetSharedDefaultFolder() method and using different types of objects of the Interop library but I couldn't solve it.
Here are the methods I've tried. To run the program (in particular GetMethod3() and GetMethod5()) you have to set the string "email" with your own email.
using System;
using System.Text;
using Microsoft.Office.Interop.Outlook;
namespace OutlookTest {
class Program {
static void Main(string[] args) {
OutlookSharedCalendar outlookSharedCalendar = new OutlookSharedCalendar();
}
}
public class OutlookSharedCalendar{
Microsoft.Office.Interop.Outlook.Application oApp;
NameSpace oNameSpace = null;
MAPIFolder oMAPIFolder = null;
MAPIFolder objFolder = null;
MAPIFolder objSubFolder = null;
Explorer objExplorer;
AppointmentItem objCalenderItem;
Folders objOutlookFolders;
AddressEntry addrEntry = null;
Items oCalendarItems = null;
string email = "myemail#email.com";
public OutlookSharedCalendar() {
AppStart();
GetMethod1();
AppEnd();
AppStart();
GetMethod2();
AppEnd();
AppStart();
GetMethod3();
AppEnd();
AppStart();
GetMethod4();
AppEnd();
AppStart();
GetMethod5();
AppEnd();
}
public void GetMethod1() {
oMAPIFolder = oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
oCalendarItems = (Items)oMAPIFolder.Items;
oCalendarItems.IncludeRecurrences = true;
foreach(AppointmentItem item in oCalendarItems) {
if(item.IsRecurring) {
RecurrencePattern oRP = item.GetRecurrencePattern();
DateTime first = new DateTime(2018, 01, 01, item.Start.Hour, item.Start.Minute, 0);
DateTime last = new DateTime(2019, 10, 31);
AppointmentItem recur = null;
for(DateTime cur = first; cur <= last; cur = cur.AddDays(1)) {
recur = oRP.GetOccurrence(cur);
Console.WriteLine(recur.Subject + " - " + cur.ToLongDateString() + " - " + recur.Body);
}
}
else {
Console.WriteLine(item.Subject + " -> " + item.Start.ToLongDateString());
}
}
}
public void GetMethod2() {
int intFolderCtr;
int intSubFolderCtr;
int intAppointmentCtr;
// >> Initialize The Base Objects
objOutlookFolders = oApp.Session.Folders;
// >> Loop Through The PST Files Added n Outlook
for(intFolderCtr = 1; intFolderCtr <= objOutlookFolders.Count; intFolderCtr++) {
objFolder = objOutlookFolders[intFolderCtr];
objExplorer = objFolder.GetExplorer();
// >> Loop Through The Folders In The PST File
for(intSubFolderCtr = 1; intSubFolderCtr <= objExplorer.CurrentFolder.Folders.Count; intSubFolderCtr++) {
objSubFolder = objExplorer.CurrentFolder.Folders[intSubFolderCtr];
// >> Check if Folder Contains Appointment Items
if(objSubFolder.DefaultItemType == OlItemType.olAppointmentItem) {
// >> Loop Through Appointment Items
for(intAppointmentCtr = 1; intAppointmentCtr <= objSubFolder.Items.Count; intAppointmentCtr++) {
// >> Get Teh Calender Item From The Calender Folder
objCalenderItem = objSubFolder.Items[intAppointmentCtr];
// >> Process Appointment Item Accordingly
Console.WriteLine(objCalenderItem.Subject + " - " + objCalenderItem.Start + " - " + objCalenderItem.Body + " - " + objCalenderItem.Location);
}
}
}
}
}
public void GetMethod3() {
DateTime dtFrom = new DateTime(DateTime.Now.Year, 01, 01);
DateTime dtTo = new DateTime(DateTime.Now.Year, 12, 31);
Recipient teamMember = oApp.Session.CreateRecipient(email);
MAPIFolder sharedCalendar = oApp.Session.GetSharedDefaultFolder(teamMember, OlDefaultFolders.olFolderCalendar);
if(sharedCalendar.DefaultMessageClass != "IPM.Appointment" || teamMember.DisplayType != 0) {
return; //Calendar not shared.
}
string restrictCriteria = "[Start]<=\"" + dtTo.ToString("g") + "\"" + " AND [End]>=\"" + dtFrom.ToString("g") + "\"";
Items results = sharedCalendar.Items.Restrict(restrictCriteria);
foreach(AppointmentItem item in results) {
Console.WriteLine(item.Subject + " - " + item.Start + " - " + item.Body + " - " + item.Location);
}
}
public void GetMethod4() {
oMAPIFolder = oApp.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
DateTime dtEnd = new DateTime(DateTime.Now.Year, 12, 31);
DateTime dtStart = new DateTime(DateTime.Now.Year, 01, 01);
string restrictCriteria = "[Start]<=\"" + dtEnd.ToString("g") + "\"" +
" AND [End]>=\"" + dtStart.ToString("g") + "\"";
StringBuilder strBuilder = null;
Items folderItems = null;
Items resultItems = null;
AppointmentItem appItem = null;
int counter = default(int);
object item = null;
strBuilder = new StringBuilder();
folderItems = (Items)oMAPIFolder.Items;
folderItems.IncludeRecurrences = true;
folderItems.Sort("[Start]");
resultItems = folderItems.Restrict(restrictCriteria);
item = resultItems.GetFirst();
do {
if(item != null) {
if(item is AppointmentItem) {
counter++;
appItem = item as AppointmentItem;
Console.WriteLine(appItem.Subject + " -> " + appItem.Start.ToLongDateString());
strBuilder.AppendLine("#" + counter.ToString() +
"\tStart: " + appItem.Start.ToString() +
"\tSubject: " + appItem.Subject +
"\tLocation: " + appItem.Location);
}
item = resultItems.GetNext();
}
}
while(item != null);
}
public void GetMethod5() {
addrEntry = oApp.Session.CurrentUser.AddressEntry;
if(addrEntry.Type == "EX") {
Recipient recip = oApp.Session.CreateRecipient(email);
if(recip.Resolve()) {
Folder folder = oApp.Session.GetSharedDefaultFolder(recip, OlDefaultFolders.olFolderCalendar) as Folder;
foreach(AppointmentItem item in folder.Items) {
Console.WriteLine(item.Subject + " - " + item.Start + " - " + item.Body + " - " + item.Location);
}
}
}
}
public void AppStart() {
// >> Start Outlook
oApp = new Microsoft.Office.Interop.Outlook.Application();
}
public void AppEnd() {
// >> Close Application
oApp.Quit();
// >> Release COM Object
System.Runtime.InteropServices.Marshal.ReleaseComObject(oApp);
oApp = null;
}
}
}
I hope I can get advice on the code or if someone knows a viable alternative to Interop. Thank you all in advance.
The NameSpace.GetSharedDefaultFolder method is used to get a Folder object that represents the specified default folder for the specified user. For example, with minor changes:
public void GetMethod3() {
DateTime dtFrom = new DateTime(DateTime.Now.Year, 01, 01);
DateTime dtTo = new DateTime(DateTime.Now.Year, 12, 31);
Recipient teamMember = oApp.Session.CreateRecipient(email);
teamMember.Resolve();
if(teamMember.Resolved)
{
MAPIFolder sharedCalendar = oApp.Session.GetSharedDefaultFolder(teamMember, OlDefaultFolders.olFolderCalendar);
if(sharedCalendar.DefaultMessageClass != "IPM.Appointment" || teamMember.DisplayType != 0) {
return; //Calendar not shared.
}
string restrictCriteria = "[Start]<=\"" + dtTo.ToString("g") + "\"" + " AND [End]>=\"" + dtFrom.ToString("g") + "\"";
Items results = sharedCalendar.Items.Restrict(restrictCriteria);
foreach(AppointmentItem item in results) {
Console.WriteLine(item.Subject + " - " + item.Start + " - " + item.Body + " - " + item.Location);
}
}
}
As you may see the recipient should be resolved against your address book before trying to access a shared calendar. The Recipient.Resolve method attempts to resolve a Recipient object against the Address Book.

The process cannot access the file "XXX.txt" because it is being used by another process

I would like to write to and read from the same text file. However, I faced the issue of "The process cannot access "XXX.txt" because it is being used by another process".
I created two classes, A & B and define two objects for each of the classes in the main form.
Class A will be writing data into the text file while Class B will reading data from the text file at the same time.
I had put Class B in a timer while Class A will start when I click a button.
Class A :-
private void Processdata(string indata)
{
//======================================[TCP/IP]=====================================================//
using (StreamWriter sw = new StreamWriter(TCPfilename, true))
{
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
sw.WriteLine(formattedTime + "\t" + indata);
}
// Regular Expression for WIFI Drone & Phantom 3 Drone
Regex regexp3_1 = new Regex(#"^AH(60601F740D70)(-\d{0,2})");
Regex regexp3_2 = new Regex(#"^AH(60601F415CAF)(-\d{0,2})");
Regex regexp3_3 = new Regex(#"^AH(60601F078D3E)(-\d{0,2})");
Regex regexp3 = new Regex(#"^AH(60601F(\S{0,6}))(-\d{0,2})");
Regex regexP3 = new Regex(#"^GGP3(\S{0,8})");
Regex regexPA = new Regex(#"^AH(A0143D\S{0,6})(-\d{0,2})");
Regex regex3D = new Regex(#"^AH(8ADC96\S{0,6})(-\d{0,2})");
Regex regexMA = new Regex(#"^AH(60601F93F3FB)(-\d{0,2})");
Regex regexMP = new Regex(#"^AH(60601F33729E)(-\d{0,2})");
Regex regexTL = new Regex(#"^AH(60601FD8A1EF)(-\d{0,2})");
// Regular Expression for WIFI
Regex regexAH = new Regex(#"^AH(\S{0,12})(-\d{0,2})");
Regex regexAH2 = new Regex(#"^AH(\S{0,12})(-\d{0,2})\S{0,6}(\S{0,74})");
// Match WIFI Drone & Phantom 3 Drone Data with Regular Expression
Match matchp3_1 = regexp3_1.Match(indata);
Match matchp3_2 = regexp3_2.Match(indata);
Match matchp3_3 = regexp3_3.Match(indata);
Match matchp3 = regexp3.Match(indata);
Match matchP3 = regexP3.Match(indata);
Match matchPA = regexPA.Match(indata);
Match match3D = regex3D.Match(indata);
Match matchMA = regexMA.Match(indata);
Match matchMP = regexMP.Match(indata);
Match matchTL = regexTL.Match(indata);
// Match WIFI Data with Regular Expression
Match matchAH = regexAH.Match(indata);
Match matchAH2 = regexAH2.Match(indata);
using (StreamWriter rssi = new StreamWriter(TCPRSSIfilename, true))
{
var time = DateTime.Now;
// Parrot
if (matchPA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Parrot" + "; " + matchPA.Groups[1].Value.ToString() + "; " + matchPA.Groups[0].Value.ToString() + "; " + matchPA.Groups[2].Value.ToString());
rssi.Flush();
}
// 3DR
else if (match3D.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-3DR_Solo" + "; " + match3D.Groups[1].Value.ToString() + "; " + match3D.Groups[0].Value.ToString() + "; " + match3D.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Air
else if (matchMA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Air" + "; " + matchMA.Groups[1].Value.ToString() + "; " + matchMA.Groups[0].Value.ToString() + "; " + matchMA.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Pro
else if (matchMP.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Pro" + "; " + matchMP.Groups[1].Value.ToString() + "; " + matchMP.Groups[0].Value.ToString() + "; " + matchMP.Groups[2].Value.ToString());
rssi.Flush();
}
// Tello
else if (matchTL.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Tello" + "; " + matchTL.Groups[1].Value.ToString() + "; " + matchTL.Groups[0].Value.ToString() + "; " + matchTL.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 740D70)
else if (matchp3_1.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_1.Groups[1].Value.ToString() + "; " + matchp3_1.Groups[0].Value.ToString() + "; " + matchp3_1.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 415CAF)
else if (matchp3_2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_2.Groups[1].Value.ToString() + "; " + matchp3_2.Groups[0].Value.ToString() + "; " + matchp3_2.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 078D3E)
else if (matchp3_3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_3.Groups[1].Value.ToString() + "; " + matchp3_3.Groups[0].Value.ToString() + "; " + matchp3_3.Groups[2].Value.ToString());
rssi.Flush();
}
// General Phantom 3
else if (matchp3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3.Groups[1].Value.ToString() + "; " + matchp3.Groups[0].Value.ToString() + "; " + matchp3.Groups[2].Value.ToString());
rssi.Flush();
}
// WIFI
else if (matchAH.Success && matchAH2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Wifi -" + matchAH2.Groups[3].Value.ToString() + "; " + matchAH.Groups[1].Value.ToString() + "; " + matchAH.Groups[0].Value.ToString() + "; " + matchAH.Groups[2].Value.ToString());
rssi.Flush();
}
}
}
Class B :-
public void DisplayOnDataGridView(DataGridView dl, GMapControl gmap, string TCPRSSIfile, string UDPRSSIfile)
{
//================================[TCP/IP]==================================================//
using (StreamReader streamReader = new StreamReader(TCPRSSIfile, true))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+ -)(\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
if (matchSearch.Groups[3].Value.ToString() != null)
{
for (int i = 0; i <= matchSearch.Groups[3].Value.ToString().Length - 2; i += 2)
{
//Convert Hex format to standard ASCII string
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(matchSearch.Groups[3].Value.ToString().Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
}
StringBuilder sbwifi = new StringBuilder(sb.Length);
foreach (char c in sb.ToString())
{
if ((int)c > 127) // 127 = Delete
continue;
if ((int)c < 32) // 1-31 = Control Character
continue;
if (c == ',')
continue;
if (c == '"')
continue;
sbwifi.Append(c);
}
Regex wifi = new Regex(#"^(\S+)\$");
Match matchwifi = wifi.Match(sbwifi.ToString());
if (matchwifi.Success)
{
sbwifi.Clear();
sbwifi.Append(matchwifi.Groups[1].Value.ToString());
}
if (matchSearch.Success)
{
try
{
if (dl.Rows.Count == 0)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
else
{
for (int row = 0; row < dl.Rows.Count; row++)
{
if (dl.Rows[row].Cells["DroneID"].Value.ToString() == matchSearch.Groups[4].Value.ToString())
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi") == false)
{
Image img1 = Image.FromFile(#"D:\Image\alert.PNG");
if (dl.Rows[row].Cells["DroneStatus"].Value != img1)
{
dl.Rows[row].Cells["DroneStatus"].Value = img1;
}
}
dl.Rows[row].Cells["TimeDetected"].Value = matchSearch.Groups[1].Value.ToString();
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
duplicate = true;
}
}
if (!duplicate)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
//========================================[UDP]===================================================//
using (StreamReader streamReader = new StreamReader(UDPRSSIfile))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
if (matchSearch.Success)
{
try
{
//if (matchSearch.Groups[4].Value.ToString() != "0.000000")
//{
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString(), matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
//}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
if (dl.Rows[rownumber].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
DetectedZone(gmap, false);
}
else
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
DetectedZone(gmap, true);
}
Image img = Image.FromFile(#"D:\Image\arrow.jpg");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
RSSI_Signal(dl, matchSearch.Groups[5].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
// Add Number for Each DataGridView Row
if (null != dl)
{
foreach (DataGridViewRow r in dl.Rows)
{
dl.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
Main Form :-
//========Call Class A Object==============//
private void button2_Click(object sender, EventArgs e)
{
// TCP/IP Address - Debug TCP Text File - Debug UDP Text File - UDP Port Number - TCP/IP RSSI Text File - UDP RSSI Text File
ListeningPole lp1 = new ListeningPole();
lp1.PortConnect("192.168.1.133", #"D:\Skydroner\SkyDroner_DebugTCP_1.txt", #"D:\Skydroner\SkyDroner_DebugUDP_1.txt", 61557, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
//========Timer to Run Class B Object==============//
private void MainForm_Load(object sender, EventArgs e)
{
// Start Timer for Display Scroll Mouse Message
RowCountTimer.Interval = 1000;
RowCountTimer.Start();
}
private void RowCountTimer_Tick(object sender, EventArgs e)
{
Display dp1 = new Display();
dp1.DisplayOnDataGridView(DroneList, gmap, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
Anyone have any solution for this error.
Please help.
Thanks.
Make sure to call Close() on the writer to close it before reading. I've seen instances where utilizing a using block with the writer may not close it in time for the reader to be able to read it.

Slow loading of treeview

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

How can i pass List<string> response as an xml document using c#

I would like to pass an List response as an xml document and want to load it as xml.
Currently i am performing it using this code :
List<string> BugWSResponseList1 = new List<string>();
BugWSResponseList1 = CreateBugs(FilePath_EXPRESS_API_BugAdd_CreateBugs_DataFile, newValue);
XmlDocument xd = new XmlDocument();
//string s = string.Join(",", BugWSResponseList2);
//xd.LoadXml(s);
string s = "<Bugs>" + string.Join(",", BugWSResponseList1) + "</Bugs>";
xd.LoadXml(s);
//Dictionary Creation for Benchmark API
XmlDocument ResponseNode_bugs = null;
ResponseNode_bugs = new DrWatsonCore().LoadXMLDocument(s);
I would like to avoid to convert the List<string> response to string first and then loading it as xml.
Please suggest how can i achieve that.
Please find the detail of my LoadXMLDocument function as follows:
public XmlDocument LoadXMLDocument(string XMLData)
{
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(XMLData);
}
catch (Exception ex)
{
Logger.Write("\n\n" + DateTime.Now + " : " + "LoadXMLDocument : SEVERE ERROR : Failed to create XMLDocument from given string : \n\n");
Logger.Write("\n\n" + DateTime.Now + " : " + "Exception : : \n\n" + ex.Message);
Logger.Write("\n\n" + DateTime.Now + " : " + "Given String : : \n\n");
if (DrWatsonHome.doVerboseLogging)
{
Logger.Write(XMLData);
}
else
{
string Response = XMLData;
Logger.Write("\n\n" + DateTime.Now + " : " + "Response Length : " + Response.Length + " characters.");
int ResponseLengthToPrint = DrWatsonHome.VerboseLogging_Length_Chars < Response.Length ? DrWatsonHome.VerboseLogging_Length_Chars : Response.Length;
Logger.Write("\n\n" + DateTime.Now + " : " + "Response : " + Response.Substring(0, ResponseLengthToPrint) + " ...");
}
}
finally
{
}
return doc;
}
Can i achieve it after making some modifications in it.Please suggest.
I am using List now and my function is as follows:
List<XElement> Sairam(string FilePath, string Timestamp)
{
List<XElement> WSResponse = new List<XElement>();
XmlDocument XDoc = new DrWatsonCore().LoadXMLFromFile(FilePath);
XmlNode BugListNode = XDoc.SelectSingleNode("/DrWatson/Bugs");
List<Bug> BugList = new DrWatsonCore().GetBugList(BugListNode);
List<Thread> BugFtecherThreadList = new List<Thread>();
foreach (Bug bug in BugList)
{
bug.FoundInBuild = Timestamp;
string URL = new DrWatsonCore().CreateWXURL(EXPRESS_API_METHOD.bug_add, bug, REST_EndPoint, AppGUID, new WatsonUser(Username_Watson, Password_Watson));
string Response = string.Empty;
object URLobj = (object) URL;
Response = CreateBug(URLobj);
// WSResponse.Add(Response);
}
return WSResponse;
}
I would like to get the WSResponse as the final response of teh program but i am unable to fetch it. Please suggest so how can i get the response of this program from this function.

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.

Categories

Resources