c# outlook addin userproperty of first item in collection not found - c#

Outlook 2016
.Net Framework 4.5
i encounter a really strange behaviour:
when i iterate through the items collection of a contact folder in some very special undefined cases (which i do not really understand) some userproperties of the first item of the collection fail to load. However the UserProperties are definitly set.
The approach is following:
I open the contact folder (to which the items will be moved) in outlook.
then i execute the "test"
the execution of the test can be suammrized as following:
click button ->
start thread
iterate through the items (on first iteration no items are present).
add new items{
create item
set userproperty PRE before item is initially saved
save item
move item to desired folder
set userproperty POST after item is moved
save item
}
end thread
click button ->
start thread
iterate through the items (here the userproperty POST sometimes fails to load on the first item of the collection, however when i investigate it, it IS there. It only fails for the first item and succeeds for every other following item).
...END
it seems to me that outlook somehow fails to update the userproperty definitions timely. But note that the first BackgroundWorker thread is already finished when iterating through the items with the second backgroundworker thread.
The problem could be related to the fact that iam viewing the folder in the explorer while the items are added and iterated.
This bug is hard to reproduce and does only occur rarely.
however i'm really missing insight into the inner workings of outlook so i can only speculate.
Idea for workarounds:
I could add an item with all userproperties before moving it. the problem here is that i need to add new userproperties, after the item is initially saved and moved to the folder, in some scenarios.
in few cases the userproperty key is dynamically created (with a pattern) so it wouldn't be optimal to predefine all userproperties.
It's very important that the userProperties are reliably loaded because some important features are based upon them.
Does anybody has a clue how the problem is caused and how to solve it? because this behaviour is driving me crazy.
some Code (not the original but it should contain all the relevant aspects)
//Ribbon
TestNS.TestCaller testCaller;
string folderID = "00000000BDB409934ED327439481EB6E1E1CC4D3010055B62301B58E32478DCD8C0D3FA6304600002C4CA4400000";
public void testButton0_Action(Office.IRibbonControl control)
{
if(testCaller == null){
testCaller = new TestNS.TestCaller(ThisAddIn.Outlook,folderID);
}
testCaller.Run();
}
//Ribbon end
using System.Runtime.InteropServices;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
namespace TestNS
{
public class TestCaller{
private Outlook.Application application;
private BackgroundWorker worker = new BackgroundWorker();
private Test test = null;
private string folderId;
private bool init = true;
private bool busy = false;
public TestCaller(Outlook.Application application, string folderId){
this.application = application;
this.folderId = folderId;
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnCompleted);
}
public void Run()
{
if (!busy)
{
busy = true;
test = new Test(application, folderId, init);
worker.RunWorkerAsync();
}
}
private void DoWork(object sender, DoWorkEventArgs e)
{
test.Process();
test = null;
}
private void OnCompleted(object sender, RunWorkerCompletedEventArgs e)
{
busy = false;
init = false;
}
}
class Test
{
public const string key_preCreateProperty ="preCreate";
public const string key_postCreateProperty = "postCreate";
private Outlook.Application application;
private string folderId;
private bool createData;
public Test(Outlook.Application application,string folderId,bool createData)
{
this.application = application;
this.folderId = folderId;
this.createData = createData;
}
public void Process(){
Examine();
if(createData){
CreateData();
}
}
public void CreateData()
{
List<Poco> pocos = new List<Poco>();
for (int i = 0; i < 10; i++)
{
pocos.Add(
new Poco
{
Pre = "Pre" + i,
Post = "Post" + i
}
);
}
CreateContactItems(folderId,pocos);
}
public void Examine()
{
bool preIsLoaded = false;
bool postIsLoaded = false;
Debug.WriteLine(">>>Examine");
Outlook.MAPIFolder folder = application.Session.GetFolderFromID(folderId);
Outlook.Items folderItems = folder.Items;
int i = 0;
//print UserProperties registered to the items
foreach(Outlook.ContactItem contactItem in folderItems){
var itemUserProperties = contactItem.UserProperties;
string itemUserPropertiesString = "";
foreach (var itemProp in itemUserProperties)
{
Outlook.UserProperty prop = (Outlook.UserProperty)itemProp;
itemUserPropertiesString += " " +prop.Name + " " + prop.Value + " \n";
}
//HERE: sometimes it prints only Pre on the first index of the iteration
Debug.WriteLine(string.Format("i={0} , itemUserProperties Count={1} , following UserProperties: \n{2}", i++, itemUserProperties.Count, itemUserPropertiesString));
string pre = null;
string post = null;
try
{
pre = contactItem.GetUserProperty(key_preCreateProperty);
preIsLoaded = true;
}
catch(KeyNotFoundException ex){
Debug.WriteLine("Error: Pre Not found"); //should not happen - doesn't happen
}
try
{
post = contactItem.GetUserProperty(key_postCreateProperty);
postIsLoaded = true;
}
catch (KeyNotFoundException ex)
{
Debug.WriteLine("Error: Post Not found"); //shoul not happen - happens rarely totally indeterminitic
}
Marshal.ReleaseComObject(itemUserProperties);
}
Debug.WriteLine("<<<Examine");
if (folderItems.Count > 0 && (!preIsLoaded || !postIsLoaded))
{
MessageBox.Show("preIsLoaded="+preIsLoaded +" \n" +"postIsLoaded="+postIsLoaded);
}
Marshal.ReleaseComObject(folderItems);
Marshal.ReleaseComObject(folder);
}
public void CreateContactItems(string folderId,List<Poco> pocos)
{
Outlook.MAPIFolder folder = application.Session.GetFolderFromID(folderId);
foreach(Poco poco in pocos){
CreateContactItem(folder,poco);
}
Marshal.ReleaseComObject(folder);
}
public void CreateContactItem(Outlook.MAPIFolder testFolder,Poco data)
{
Outlook.ContactItem contactItem = application.CreateItem(Outlook.OlItemType.olContactItem);
contactItem.SetUserProperty(key_preCreateProperty, data.Pre);
contactItem.Save();
Outlook.ContactItem movedContactItem = (Outlook.ContactItem)contactItem.Move(testFolder);
Marshal.ReleaseComObject(contactItem);
contactItem = movedContactItem;
contactItem.FirstName = data.Pre;
contactItem.LastName = data.Post;
contactItem.SetUserProperty(key_postCreateProperty, data.Post);
contactItem.Save();
Marshal.ReleaseComObject(contactItem);
}
}
public static class Util
{
public static void SetUserProperty(this Outlook.ContactItem item, string name, dynamic value)
{
Outlook.UserProperty property = item.UserProperties[name];
if (property == null)
{
property = item.UserProperties.Add(name, Outlook.OlUserPropertyType.olText);
}
property.Value = value;
}
public static dynamic GetUserProperty(this Outlook.ContactItem item, string name)
{
Outlook.UserProperty property = item.UserProperties[name];
if (property != null)
{
return property.Value;
}
throw new KeyNotFoundException(string.Format("UserProperty name={0} not found", name));
}
}
public class Poco
{
public string Pre
{
get;
set;
}
public string Post
{
get;
set;
}
}
}
Thank you for any replies

Outlook Object Model cannot be used on a secondary thread within a COM addin. Outlook 2016 will raise an exception as soon as it detects an OOM object being accessed on a secondary thread.

Related

Selenium Webdriver: How to confirm element no longer displayed on page

I have a table containing details about jobs.
Currently I can use the following code to find the specified job and select delete.
[TestMethod]
public void DeleteJob()
{
JobsPage.GoTo();
JobsPage.Delete("TestJobTitle");
Assert.IsTrue(DeleteJobPage.IsAt, "Delete job page not displayed");
}
Below Method to find the specified job and click delete
public static void Delete(string delete)
{
var test = Driver.Instance.FindElement((By.XPath("//table/tbody/tr[td[2] = '" + delete + "']/td[9]/a[3]")));
test.Click();
}
I am now attempting to find a way to confirm the Job is no longer displayed on the JobsPage.
Assert.IsTrue(JobsPage._View("TestJobTitle"), "Job is still present");
The above Assert in the TestMethod is not working
I attempted the below method but need help to get working.
public static bool _View(string view)
{
IList<IWebElement> messages = Driver.Instance.FindElements(By.XPath("//table/tbody/tr[td[2] = '" + view + "']")).ToList();
foreach (IWebElement message in messages)
{
if (message.Text == view)
{
return true; // Job is still present
}
}
return false; // Job is not present
}
Don't know whether this helps or not. I have same scenario and I do search in a table for a user still exists or not.
public static bool ValidateSearchResult(string s)
{
bool val = false;
try
{
new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 0, 10)).Until(ExpectedConditions.ElementExists(By.TagName("tbody")));
IList<IWebElement> StatusColumnData = Drivers._driverInstance.FindElements(By.XPath("//table/tbody/tr/td[2]"));
foreach (IWebElement element in StatusColumnData)
{
if (element.Text.Contains(s))
{
val = true;
break;
}
else
val = false;
return val;
}
}
catch(Exception e)
{
throw (e);
}
}

Outlook 2013 & Outlook Add-In :: MAPIFolderEvents_12_Event.BeforeItemMove Not Firing?

I am trying to implement Adrian Brown's very nice Outlook Add-In code and it works 2 out of 3 times. ItemAdd and ItemChange events are firing as expected, but the event handler for MAPIFolderEvents_12_Event.BeforeItemMove does not appear to be doing anything - I don't even hit a breakpoint on the first line of the event handler.
More Code for Clarity
This is the CalendarMonitor class; it monitors ItemAdd, ItemChange events on the Items collection of the folder, as well as BeforeItemMove on the MAPIFolder:
public class CalendarMonitor
{
private Explorer _explorer;
private List<string> _folderPaths;
private List<MAPIFolder> _calendarFolders;
private List<Items> _calendarItems;
private MAPIFolder _deletedItemsFolder;
public event EventHandler<EventArgs<AppointmentItem>> AppointmentAdded;
public event EventHandler<EventArgs<AppointmentItem>> AppointmentModified;
public event EventHandler<CancelEventArgs<AppointmentItem>> AppointmentDeleting;
public CalendarMonitor(Explorer explorer)
{
_folderPaths = new List<string>();
_calendarFolders = new List<MAPIFolder>();
_calendarItems = new List<Items>();
_explorer = explorer;
_explorer.BeforeFolderSwitch += Explorer_BeforeFolderSwitch;
var session = _explorer.Session;
try
{
_deletedItemsFolder = session.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems);
HookupDefaultCalendarEvents(session);
}
finally
{
Marshal.ReleaseComObject(session);
session = null;
}
}
private void HookupDefaultCalendarEvents(_NameSpace session)
{
var folder = session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);
if (folder == null) return;
try
{
HookupCalendarEvents(folder);
}
finally
{
Marshal.ReleaseComObject(folder);
folder = null;
}
}
private void Explorer_BeforeFolderSwitch(object obj, ref bool cancel)
{
var folder = (obj as MAPIFolder);
if (folder == null) return;
try
{
// Hookup events to any other Calendar folder opened.
if (folder.DefaultItemType == OlItemType.olAppointmentItem)
HookupCalendarEvents(folder);
}
finally
{
Marshal.ReleaseComObject(folder);
folder = null;
}
}
private void HookupCalendarEvents(MAPIFolder calendarFolder)
{
if (calendarFolder.DefaultItemType != OlItemType.olAppointmentItem)
{
throw new ArgumentException("The MAPIFolder must use AppointmentItems as the default type.");
}
// Ignore other user's calendars.
if (_folderPaths.Contains(calendarFolder.FolderPath) || (!IsUsersCalendar(calendarFolder))) return;
var items = calendarFolder.Items;
// Store folder path to prevent repeating listeners
_folderPaths.Add(calendarFolder.FolderPath);
// Store a reference to the folder & items to prevent garbage collection
_calendarFolders.Add(calendarFolder);
_calendarItems.Add(items);
// Add listeners
((MAPIFolderEvents_12_Event)calendarFolder).BeforeItemMove += Calendar_BeforeItemMove;
items.ItemChange += CalendarItems_ItemChange;
items.ItemAdd += CalendarItems_ItemAdd;
}
private void CalendarItems_ItemAdd(object obj)
{
var appointment = (obj as AppointmentItem);
if (appointment == null) return;
try
{
if (AppointmentAdded != null)
AppointmentAdded(this, new EventArgs<AppointmentItem>(appointment));
}
finally
{
Marshal.ReleaseComObject(appointment);
appointment = null;
}
}
private void CalendarItems_ItemChange(object obj)
{
var appointment = (obj as AppointmentItem);
if (appointment == null) return;
try
{
if (AppointmentModified != null)
AppointmentModified(this, new EventArgs<AppointmentItem>(appointment));
}
finally
{
Marshal.ReleaseComObject(appointment);
appointment = null;
}
}
private void Calendar_BeforeItemMove(object obj, MAPIFolder moveToFolder, ref bool cancel)
{
if ((moveToFolder != null) && (!IsDeletedItemsFolder(moveToFolder))) return;
var appointment = (obj as AppointmentItem);
if (appointment == null) return;
try
{
if (AppointmentDeleting == null) return;
// Listeners to the AppointmentDeleting event can cancel the move operation if moving
// to the deleted items folder.
var args = new CancelEventArgs<AppointmentItem>(appointment);
AppointmentDeleting(this, args);
cancel = args.Cancel;
}
finally
{
Marshal.ReleaseComObject(appointment);
appointment = null;
}
}
private bool IsUsersCalendar(MAPIFolder folder)
{
// This is based purely on my observations so far - a better way?
return (folder.Store != null);
}
private bool IsDeletedItemsFolder(MAPIFolder folder)
{
return (folder.EntryID == _deletedItemsFolder.EntryID);
}
public AppointmentItem Item { get; set; }
}
New Information:
I have done some additional "troubleshooting" and come up with more information: on a whim, I created a new calendar in Outlook (while debugging) and lo and behold the BeforeItemMove event fires just like I expect it to when deleting an appointment in the new calendar, but it still doesn't work in the original.
If I exit the debug session and restart, neither calendar's event functions as expected, despite working fine earlier. Any new calendar's BeforeItemMove event will work fine, until I close Outlook - then it's back to not responding.
I am hoping that this additional information will provide insight to those wiser than I. Any assistance is greatly appreciated.
calFolder variable must be declared on the global/class level to avoid being released by the Garbage Collector.
Where did you declare the source object? Is it alive when the event should be fired?
Anyway, you may consider developing an inspector wrapper. See Developing an Inspector Wrapper for Outlook 2010 and How to: Implement a Wrapper for Inspectors and Track Item-Level Events in Each Inspector for more information.
The sample project in C# and VB.NET is also available - Outlook 2010: Developing an Inspector Wrapper.

How to prevent WMI quotas from overflowing?

I am using a C# application to monitor the processes launched from a particular folder, and I am using WMI for monitoring. My WMI query is like
SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.ExecutablePath LIKE '{0}%'
where I substitute the parameter with the path to the folder which I am intereseted. The WMI query is working fine and I am subscribing to the event notifications to do some additional processsing when a process from the particular folder comes up. The monitoring tool runs fine for hours after which I start getting a WMI QuotaViolation exception in my app. Once this happens I need to restart the Windows Management Instrumentation service to get the thing working.
I was initially using a
`SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process'`
query and then checking the processes folder in the event notification, the modification in the query was done hoping it would reduce the result set and therefore prevent the Quota Violation.
Is there any way to flush the WMI quotas periodically or any other method whereby I can prevent the QuotaViolation? What is the best way to handle a QuotaViolation scenario?
Edit:
This is my process watcher object :
public class ProcessWatcher : ManagementEventWatcher
{
private string folder = "";
// Process Events
public event ProcessEventHandler ProcessCreated; //notifies process creation
//add any more event notifications required here
// WMI WQL process query strings
static readonly string WMI_OPER_EVENT_QUERY = #"SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process'";
static readonly string WMI_OPER_EVENT_QUERY_WITH_PROC =
WMI_OPER_EVENT_QUERY + " and TargetInstance.Name = '{0}'";
public ProcessWatcher(string basepath)
{
folder = basepath;
Init(string.Empty);
}
public ProcessWatcher(string processName, string basepath)
{
folder = basepath;
Init(processName);
}
private void Init(string processName)
{
this.Query.QueryLanguage = "WQL";
if (string.IsNullOrEmpty(processName))
{
this.Query.QueryString = string.Format(WMI_OPER_EVENT_QUERY + #" AND TargetInstance.ExecutablePath LIKE '{0}%'", folder.Replace(#"\",#"\\")) ;
}
else
{
this.Query.QueryString =
string.Format(WMI_OPER_EVENT_QUERY_WITH_PROC, processName);
}
this.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
}
private void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
ManagementBaseObject mObj = e.NewEvent["TargetInstance"] as ManagementBaseObject;
if (mObj != null)
{
Win32_Process proc = new Win32_Process(mObj);
if (proc != null)
{
folder = folder.ToLower() ?? "";
string exepath = (string.IsNullOrEmpty(proc.ExecutablePath)) ? "" : proc.ExecutablePath.ToLower();
if (!string.IsNullOrEmpty(folder) && !string.IsNullOrEmpty(exepath) && exepath.Contains(folder))
{
if (ProcessCreated != null) ProcessCreated(proc);
}
}
proc.Dispose();
}
mObj.Dispose();
}
catch(Exception ex) { throw; }
finally
{
e.NewEvent.Dispose();
}
}
I create a ProcessWatcher object at app startup, in a viewmodel constructor like :
watch = new ProcessWatcher(BasePath);
watch.ProcessCreated += new ProcessEventHandler(procWatcher_ProcessCreated);
watch.Start();
The start call is where the QuotaViolation is raised if I try to start it a second time without restarting WMI.
At app exit, I am disposing off the ProcessWatcher object like :
watch.Stop();
watch.Dispose();
The Relevant Stack trace is :
Exception InnerException [System.Management.ManagementException: Quota violation
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementEventWatcher.Start()
at App.ProcessTabViewModel1..ctor()
System.Management.ManagementException: Quota violation
Yes, that happens. I wrote a little test program, based on your snippet after adding the missing pieces:
static void Main(string[] args) {
for (int ix = 0; ix < 1000; ++ix) {
var obj = new ProcessWatcher("");
obj.ProcessCreated += obj_ProcessCreated;
obj.Start();
}
}
Kaboom! With the exact same stack trace as you quoted. It conked out at ix == 76. In other words, the WMI quota for this query is 75. Tested in Windows 8.1. Feels about right, this is a very expensive query, none too fast either.
You are going to have to do this fundamentally different, create only one query. One is enough, you probably got into trouble by doing this for many folders. Attack that differently, do your own filtering when you get the event. A rough example (I didn't quite get the filtering you want to do):
public class ProcessWatcher2 : IDisposable {
public delegate void ProcessCreateEvent(string name, string path);
public event ProcessCreateEvent ProcessCreated;
public ProcessWatcher2(string folder) {
this.folder = folder;
lock (locker) {
listeners.Add(this);
if (watcher == null) Initialize();
}
}
public void Dispose() {
lock (locker) {
listeners.Remove(this);
if (listeners.Count == 0) {
watcher.Stop();
watcher.Dispose();
watcher = null;
}
}
}
private static void Initialize() {
var query = new WqlEventQuery(#"SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process'");
watcher = new ManagementEventWatcher(query);
watcher.EventArrived += watcher_EventArrived;
watcher.Start();
}
private static void watcher_EventArrived(object sender, EventArrivedEventArgs e) {
using (var proc = (ManagementBaseObject)e.NewEvent["TargetInstance"]) {
string name = (string)proc.Properties["Name"].Value;
string path = (string)proc.Properties["ExecutablePath"].Value;
lock (locker) {
foreach (var listener in listeners) {
bool filtered = false;
// Todo: implement your filtering
//...
var handler = listener.ProcessCreated;
if (!filtered && handler != null) {
handler(name, path);
}
}
}
}
}
private static ManagementEventWatcher watcher;
private static List<ProcessWatcher2> listeners = new List<ProcessWatcher2>();
private static object locker = new object();
private string folder;
}

Receiving Notfication when app is running

In fear of asking a question that might have been asked before, but my search skills did not able me to find. Okay, so here goes.
I have Windows Phone 8 App, where I can receive TileUpdates and Notifications, when My app is not running in the foreground. This I did by following http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202940(v=vs.105).aspx
In that link I learned that for getting notifications when app is running I should simply attach an event for the reception case. This I did in my AcquirePushChannel() function, which looks as follows:
public static void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("MyPushChannel");
CurrentChannel.Open();
if (!CurrentChannel.IsShellToastBound)
{
CurrentChannel.BindToShellTile();
}
CurrentChannel.BindToShellToast();
CurrentChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(Push_NotificationRecieved);
}
if (!CurrentChannel.IsShellTileBound)
{
CurrentChannel.BindToShellToast();
CurrentChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(Push_NotificationRecieved);
}
CurrentChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(Push_NotificationChannelChanged);
}
I have implemented CurrentChannel.ChannelUriUpdated, for the case that channelUri changes and I execute some code to also changes my ChannelsTable in the Cloud.
My Push_NotificationRecieved looks like:
private static void Push_NotificationRecieved(object sender, NotificationEventArgs e)
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
// Display a dialog of all the fields in the toast.
MessageBox.Show(message.ToString());
//Dispatcher.BeginInvoke((message) => MessageBox.Show(message.ToString()));
}
I cannot see why the notification is not registered. Since in my log in the cloud I receive that the Toast Notification was received?
Any Ideas? Furthermore can I display the toast from the code or something similar, as far as I have read it is not possible?
Extra
Have tried changing the functions to public but did not help with the problem.
Anybody have an Idea to why the event is not firing.
The answer you posted is almost correct. From the previous you have:
public static void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("MyPushChannel");
CurrentChannel.Open();
if (!CurrentChannel.IsShellToastBound)
{
CurrentChannel.BindToShellTile();
}
CurrentChannel.BindToShellToast();
}
if (!CurrentChannel.IsShellTileBound)
{
CurrentChannel.BindToShellToast();
}
CurrentChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(Push_NotificationChannelChanged);
CurrentChannel.ShellToastNotificationReceived += CurrentChannel_ShellToastNotificationReceived;
}
And to that you have to add:
private static void CurrentChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
// Display a dialog of all the fields in the toast.
MessageBox.Show(message.ToString());
}
So all you send is inside the e.collection. So you can from the server send all kind of parameters.
Of course just after I set a bounty to run I got it working. So here is the updated code.
public static void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("MyPushChannel");
CurrentChannel.Open();
if (!CurrentChannel.IsShellToastBound)
{
CurrentChannel.BindToShellTile();
}
CurrentChannel.BindToShellToast();
}
if (!CurrentChannel.IsShellTileBound)
{
CurrentChannel.BindToShellToast();
}
CurrentChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(Push_NotificationChannelChanged);
CurrentChannel.ShellToastNotificationReceived += CurrentChannel_ShellToastNotificationReceived;
}
Okay so the reason for this, is that you need to set the events on every startup. Then you will get the wished properties. Then you have to create your own code for getting what you want :)

Function works when called synchronously, but does not work when called asynchronously

It is my first post on StackOverflow forum so please to be lenient. I have a problem with function which works called synchronously, but doesnot works called asynchronously.
Below You will find function called synchronously:
private void issueInvoices(List<int> lista)
{
foreach (int knh_id in lista)
{
Invoice fs = new Invoice();
fs.FKS_AKCYZA = false;
fs.FKS_CZY_KLON = false;
fs.FKS_DATE = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
fs.NUMBER = knh_id);
}
}
As You can see i passed list to function named issueInvoices list of invoice numbers and in loop i create some invoices.
This function works properly but if i try to call it asynchronously (to display progress bar) my function can not assign to fs.FKS_DATE object dateTime. It looks like static function “Convert.ToDateTime” doesnot work properly. But please take a look on below code where function issueInvoices is called asynchronously…
public delegate void BinaryDelegate(List<int> knh_id);
BinaryDelegate b = new BinaryDelegate(issueInvoices);
IAsyncResult theAsRes = b.BeginInvoke(lista, new AsyncCallback(AddComplete), "Thx U!");
FrmProgressBar fpb=new FrmProgressBar(“Please wait…”);
fpb.Show();
/* below i check how many operation i have to do, if all operations are done, then I close fpb window, program is updating progres bar and in thread make operation issueInvoices*/
while (ilosc_zrobionych != liczbaKontrahentow)
{
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
}
fpb.Close();
I put some breakpoints and it looks like program stoping in line, it can conver to datetime, but when i do this synchronously, it works without any errors.
fs.FKS_DATE = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
What could couse this problem and how to resolve it?
Many thanks in advance for reply.
BELOW IS WHOLE CLASS CALLED ASYNCHRONOUSLY:
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;
using Castle.ActiveRecord;
using WFR.Model;
using System.Threading;
namespace Faktury_i_Rachunki_2.Forms
{
public partial class FrmEmisjaFakturPotwierdzonych : FrmBaseForm
{
private ArrayList listaSposobowZaplaty;
public List<int> lista;
private int liczbaWygenerowach;
private int liczbaKontrahentow;
private int ilosc_zrobionych;
private FrmProgressBar fpb;
public delegate void BinaryDelegate(List<int> knh_id);
public FrmEmisjaFakturPotwierdzonych()
{
InitializeComponent();
fpb = new FrmProgressBar("Please wait....");
}
private void BtOK_Click(object sender, EventArgs e)
{
BinaryDelegate b = new BinaryDelegate(WyemitujFakture);
lista.Add(12);
lista.Add(13);
lista.Add(17);
lista.Add(1);
liczbaKontrahentow = lista.Count;
if (TBRejestr.Text.Trim() != "")
{
if (liczbaKontrahentow > 0)
{
liczbaWygenerowach = 0;
ilosc_zrobionych = 0;
WyemitujFakture(lista);
IAsyncResult theAsRes = b.BeginInvoke(lista, new AsyncCallback(AddComplete), "THX");
fpb.Show();
while (ilosc_zrobionych != liczbaKontrahentow)
{
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
}
fpb.Close();
}
try
{
MessageBox.Show("Wygenerowano " + liczbaWygenerowach.ToString() + " faktur");
}
catch
{
}
}
}
private void WyemitujFakture(List<int> lista)
{
foreach (int knh_id in lista)
{
try
{
if (luk.Count > 0)
{
FakturySprzedazy fs = new FakturySprzedazy();
fs.FKS_AKCYZA = false;
fs.FKS_CZY_KLON = false;
fs.FKS_DATA_DOW_KS = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
fs.FKS_DATA_FAKTURY = Convert.ToDateTime(MTBDataFaktury.Text);
fs.FKS_DATA_SPRZEDAZY = Convert.ToDateTime(MTBDataSprzedazy.Text);
liczbaWygenerowach++;
}
}
catch (Exception ex)
{
MessageBox.Show("Nie można wyemitować faktury dla kontrahenta o id = " + knh_id.ToString() + " " + ex.Message);
}
ilosc_zrobionych++;
}
}
You are accessing a UI control from a background thread:
MTBDataZapisuDoFK.Text
That is not allowed.
Get this value before calling the method, store it in a variable and send the value as an argument to issueInvoices.
The problem is in getting the value of MTBDataZapisuDoFK.Text (which I assume to be a textbox). Getting or setting the text of a textbox means sending messages to its window. But you keep the UI-thread busy in the while loop and therefore it can not process any messages.
Put a call to Application.DoEvents() into the while loop to allow messages to be processed:
fpb.Show();
while (ilosc_zrobionych != liczbaKontrahentow)
{
Application.DoEvents();
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
}
fpb.Close();
I assume that the only reason for calling the method asynchronously is to be able to update the UI during processing the WyemitujFakture-method. Using Application.DoEvents() you do not need asynchonous calls:
fpb = new FrmProgressBar("Please wait....");
fpb.Show();
Application.DoEvents();
WyemitujFakture(lista);
fpb.Close();
You should call Application.DoEvents() after you call fpb.Show() to allow the form to be displayed properly. Also you should instantiate the form in the method itself instead of the constructor, because you can not use the same instance again after calling fpb.Close() (it will be disposed).
Then you can update the progress bar in the WyemitujFakture-method:
private void WyemitujFakture(List<int> lista)
{
foreach (int knh_id in lista)
{
try
{
if (luk.Count > 0)
{
FakturySprzedazy fs = new FakturySprzedazy();
fs.FKS_AKCYZA = false;
fs.FKS_CZY_KLON = false;
fs.FKS_DATA_DOW_KS = Convert.ToDateTime(MTBDataZapisuDoFK.Text);
fs.FKS_DATA_FAKTURY = Convert.ToDateTime(MTBDataFaktury.Text);
fs.FKS_DATA_SPRZEDAZY = Convert.ToDateTime(MTBDataSprzedazy.Text);
liczbaWygenerowach++;
}
}
catch (Exception ex)
{
MessageBox.Show("Nie mozna wyemitowac faktury dla kontrahenta o id = " + knh_id.ToString() + " " + ex.Message);
}
ilosc_zrobionych++;
fpb.PBStan.Value = (int)((100 * ilosc_zrobionych) / liczbaKontrahentow);
Application.DoEvents();
}
}

Categories