Example #1
0
 private void Items_ItemChange(object Item)
 {
     if (MutexManager.InFullSync())
     {
         return;
     }
     try
     {
         if (Item is ContactItem)
         {
             ContactItem item = (ContactItem)Item;
             if (MutexManager.IsBlocked(item))
             {
                 logger.Debug("Removing contact " + OutlookAdapter.ContactItemDisplay(item) + " from mutex file");
                 MutexManager.ClearBlockedContact(item);
                 return;
             }
             logger.Info("Adding " + OutlookAdapter.ContactItemDisplay(item) + " to mutex file");
             MutexManager.AddToBlockedContacts(item);
             logger.Info("Updating " + OutlookAdapter.ContactItemDisplay(item));
             GoogleAdapter ga = new GoogleAdapter(Config.Username, Config.Password, logger);
             ga.UpdateContactFromOutlookAsync(item, null);
         }
     }
     catch (System.Exception ex)
     {
         logger.Error(ex.Message);
         logger.Debug(ex.StackTrace.ToString());
         MessageBox.Show(ex.Message);
     }
 }
Example #2
0
 /// <summary>
 /// EventHandler for ItemAdd Event of InboxFolder
 /// </summary>
 /// <param name="Item">The Item wich was added to InboxFolder</param>
 private void Items_ItemAdd(object Item)
 {
     if (MutexManager.InFullSync())
     {
         return;
     }
     try
     {
         // Check the ItemType, could be a MeetingAccept or something else
         if (Item is Ol.ContactItem)
         {
             // Cast to ContactItem Object
             Ol.ContactItem contact = (Ol.ContactItem)Item;
             if (MutexManager.IsBlocked(contact))
             {
                 logger.Debug("Removing contact " + OutlookAdapter.ContactItemDisplay(contact) + " from mutex file");
                 MutexManager.ClearBlockedContact(contact);
                 return;
             }
             logger.Info("Adding " + OutlookAdapter.ContactItemDisplay(contact));
             // Do something with Item
             GoogleAdapter ga = new GoogleAdapter(Config.Username, Config.Password, logger);
             MutexManager.AddToBlockedContacts(contact);
             ga.CreateContactFromOutlookAsync(contact);
             // Release COM Object
             contact = null;
         }
     }
     catch (System.Exception ex)
     {
         logger.Error(ex.Message);
         logger.Debug(ex.StackTrace.ToString());
         MessageBox.Show(ex.Message);
     }
 }
Example #3
0
 protected override void OnStartup(StartupEventArgs e)
 {
     MessageBox.Show(
         MutexManager.CreateApplicationMutex()
         .ToString());
     base.OnStartup(e);
 }
        public void CanAcquire_can_always_acquire_something_not_yet_acquired()
        {
            // Arrange
            var name = Guid.NewGuid().ToString();

            // Act
            var result = MutexManager.CanAcquire(name);

            // Assert
            result.ShouldBeTrue();
        }
        public void Can_create_a_named_Mutex()
        {
            // Arrange
            var name = Guid.NewGuid().ToString();

            // Act
            var result = MutexManager.Acquire(name);

            // Assert
            result.ShouldNotBeNull();
            result.Name.ShouldBe(name);

            result.Dispose();
        }
        public void CanAcquire_returns_false_for_a_lock_already_acquired()
        {
            // Arrange
            var name = Guid.NewGuid().ToString();

            // Act
            using (var result = MutexManager.Acquire(name))
            {
                MutexManager.CanAcquire(name).ShouldBeFalse();
            }

            // Assert
            MutexManager.Mutexes.Count.ShouldBe(0);
        }
        public void Creating_a_mutex_via_MutexManager_with_nowait_returns_null_if_not_available()
        {
            // Arrange
            var mutexName = "myname";

            // Act
            var mutex1 = MutexManager.AcquireNoWait(mutexName);
            var mutex2 = MutexManager.AcquireNoWait(mutexName);

            // Assert
            mutex1.ShouldNotBeNull();
            mutex2.ShouldBeNull();

            MutexManager.Mutexes.ContainsKey(mutexName).ShouldBeTrue();

            mutex1.Dispose();

            MutexManager.Mutexes.ContainsKey(mutexName).ShouldBeFalse();
        }
        public void Creating_a_mutex_via_MutexManager_acquires_lock()
        {
            // Arrange
            var mutexName = "myname";

            // Act
            using (var mutex = MutexManager.Acquire(mutexName))
            {
                // Assert
                mutex.Name.ShouldBe(mutexName);
                MutexManager.Mutexes.ContainsKey(mutexName).ShouldBeTrue();
                MutexManager.Mutexes[mutexName].State.ShouldBe(MutexState.Acquired);
                MutexManager.Mutexes[mutexName].Timestamp.ShouldBeGreaterThan(DateTime.MinValue);
                MutexManager.Mutexes[mutexName].ThreadId.ShouldBe(Thread.CurrentThread.ManagedThreadId);
            }

            // Assert
            MutexManager.Mutexes.ContainsKey(mutexName).ShouldBeFalse();
        }
        public void SyncFromGoogle()
        {
            do
            {
                try
                {
                    Monitor.Enter(ContactSync.SynchRoot);
                    try
                    {
                        logger.Info("Starting sync from Google...");
                        DateTime lastFetch = GetLastGoogleFetch();
                        logger.Debug("Last fetch date: " + lastFetch.ToShortDateString());

                        if (StartSynching != null)
                        {
                            StartSynching(this);
                        }
                        try
                        {
                            logger.Info("Obtaining updated Google contacts");
                            List <Contact> contacts = googleAdapter.ContactsChangedSince(lastFetch);
                            foreach (Contact c in contacts)
                            {
                                if (MutexManager.IsBlocked(c))
                                {
                                    logger.Debug("Removing contact " + GoogleAdapter.ContactDisplay(c) + " from mutex file");
                                    MutexManager.ClearBlockedContact(c);
                                    continue;
                                }
                                logger.Info("Syncronizing " + GoogleAdapter.ContactDisplay(c));
                                logger.Debug("Adding " + GoogleAdapter.ContactDisplay(c) + " to mutex list");
                                MutexManager.AddToBlockedContacts(c);
                                outlookAdapter.UpdateContactFromGoogle(c, null);
                                logger.Info(GoogleAdapter.ContactDisplay(c) + " syncrhonized");
                                if (Thread.CurrentThread.ThreadState == ThreadState.AbortRequested)
                                {
                                    return;
                                }
                            }
                        }
                        finally
                        {
                            if (EndSynching != null)
                            {
                                EndSynching(this);
                            }
                        }
                        logger.Debug("Setting last fetch date");
                        SetLastGoogleFetch(DateTime.Now);
                        logger.Info("Waiting for " + Interval + " milliseconds.");
                    }
                    finally
                    {
                        Monitor.Exit(ContactSync.SynchRoot);
                    }
                    Thread.Sleep(Interval);
                }
                catch (System.Exception ex)
                {
                    logger.Info(ex.Message);
                    logger.Debug(ex.StackTrace.ToString());
                    if (ex.Message.ToLower().Contains("captcha"))
                    {
                        MessageBox.Show("You need to enter a captcha to validate your account.\r\n" +
                                        "GContactsSync will redirect you to the validation page.\r\n" +
                                        "Press OK on the next message box when you have finished validating.");
                        System.Diagnostics.Process.Start("https://www.google.com/accounts/DisplayUnlockCaptcha");
                        MessageBox.Show("Press OK after validating your Google Account");
                    }
                    else
                    {
                        MessageBox.Show("Error " + ex.Message);
                    }
                }
            } while (Thread.CurrentThread.ThreadState != ThreadState.AbortRequested);
        }
        public void FullSync(Config.Direction dir)
        {
            MutexManager.StartingFullSync();
            try
            {
                try
                {
                    if (dir == Config.Direction.dirToOutlook)
                    {
                        SetLastGoogleFetch(DateTime.Now);
                    }
                    if (StartSynching != null)
                    {
                        StartSynching(this);
                    }
                    List <ContactItem> OutlookContacts;
                    List <Contact>     GoogleContacts;

                    logger.Info("Obtaining Outlook contacts...");
                    OutlookContacts = outlookAdapter.Contacts;
                    logger.Info("Obtaining Google Contacts...");
                    GoogleContacts = googleAdapter.Contacts;

                    EmailComparer comparer = new EmailComparer();
                    int           i        = 0;
                    int           total    = OutlookContacts.Count() + GoogleContacts.Count();
                    foreach (ContactItem item in OutlookContacts)
                    {
                        try
                        {
                            try
                            {
                                if (Thread.CurrentThread.ThreadState == ThreadState.AbortRequested)
                                {
                                    break;
                                }
                                i++;
                                var qryFindGoogleContact = GoogleContacts.Where(c => c.Title == item.FullName ||
                                                                                c.Emails.Contains(new EMail(item.Email1Address), comparer) ||
                                                                                c.Emails.Contains(new EMail(item.Email2Address), comparer) ||
                                                                                c.Emails.Contains(new EMail(item.Email3Address), comparer));
                                if (qryFindGoogleContact.Count() > 0)
                                {
                                    if (dir == Config.Direction.dirToOutlook)
                                    {
                                        logger.Info(String.Format("{0}/{1} Updating Outlook contact: " + OutlookAdapter.ContactItemDisplay(item), i, total));
                                        Contact gContact = qryFindGoogleContact.First();
                                        logger.Info("Updating outlook contact");
                                        SyncContact(gContact, item, dir);
                                    }
                                    else
                                    {
                                        logger.Info(String.Format("{0}/{1} Processing...", i, total));
                                    }
                                }
                                else
                                {
                                    logger.Info(String.Format("{0}/{1} Creating Google contact for " + OutlookAdapter.ContactItemDisplay(item), i, total));
                                    //  MutexManager.AddToBlockedContacts(item);
                                    CreateGoogleContact(item);
                                }
                            }
                            finally
                            {
                                if (OutlookSynched != null)
                                {
                                    OutlookSynched(this, item, i, OutlookContacts.Count());
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {
                            if (ex is ThreadAbortException)
                            {
                                break;
                            }
                        }
                    }

                    foreach (Contact item in GoogleContacts)
                    {
                        try
                        {
                            try
                            {
                                if (Thread.CurrentThread.ThreadState == ThreadState.AbortRequested)
                                {
                                    break;
                                }
                                i++;
                                var qryFindOutlookContact = OutlookContacts.Where(c => c.FullName == item.Title ||
                                                                                  item.Emails.Contains(new EMail(c.Email1Address), comparer) ||
                                                                                  item.Emails.Contains(new EMail(c.Email2Address), comparer) ||
                                                                                  item.Emails.Contains(new EMail(c.Email3Address), comparer));
                                if (qryFindOutlookContact.Count() > 0)
                                {
                                    if (dir == Config.Direction.dirToGoogle)
                                    {
                                        logger.Info(String.Format("{0}/{1} Updating Google contact: " + GoogleAdapter.ContactDisplay(item), i, total));
                                        ContactItem oContact = qryFindOutlookContact.First();
                                        SyncContact(item, oContact, dir);
                                    }
                                    else
                                    {
                                        logger.Info(String.Format("{0}/{1} Processing...", i, total));
                                    }
                                }
                                else
                                {
                                    logger.Info(String.Format("{0}/{1} Creating Outlook contact for " + GoogleAdapter.ContactDisplay(item), i, total));
                                    CreateOutlookContact(item);
                                }
                            }
                            finally
                            {
                                if (GoogleSynched != null)
                                {
                                    GoogleSynched(this, item, i, GoogleContacts.Count());
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {
                            if (ex is ThreadAbortException)
                            {
                                break;
                            }
                        }
                    }
                    if (EndSynching != null)
                    {
                        EndSynching(this);
                    }
                }
                catch (System.Exception ex)
                {
                    if ((EndSynching != null))
                    {
                        EndSynching(this);
                    }
                    else if (!(ex is ThreadAbortException) & (Error != null))
                    {
                        Error(this, ex);
                    }
                }
            }
            finally
            {
                if (dir == Config.Direction.dirToGoogle)
                {
                    SetLastGoogleFetch(DateTime.Now);
                }
                MutexManager.EndingFullSync();
            }
        }
Example #11
0
        /// <summary>
        /// Loads a rule base. The working memory is reset (all facts are lost).
        /// </summary>
        /// <param name="adapter">The Adapter used to read the rule base.</param>
        /// <param name="businessObjectsBinder">The business object binder that the engine must use.</param>
        /// <remarks>
        /// The adapter will be disposed at the end of the method's execution.
        /// </remarks>
        /// <see cref="org.nxbre.ie.adapters.IRuleBaseAdapter"/>
        public void LoadRuleBase(IRuleBaseAdapter adapter, IBinder businessObjectsBinder)
        {
            if (HasLogListener)
            {
                ForceDispatchLog("NxBRE Inference Engine Rule Base Loading Started, using adapter " + adapter.GetType().FullName,
                                 LogEventImpl.INFO);
            }

            using (adapter) {
                // reset the WM
                WM.PrepareInitialization();

                // sets the Binder
                Binder = businessObjectsBinder;

                // and pass it to the adapter if needed
                if (Binder != null)
                {
                    adapter.Binder = Binder;
                }

                // currently only forward chaining is supported
                direction = adapter.Direction;
                if (direction == "backward")
                {
                    throw new BREException("NxBRE does not support backward chaining");
                }
                else if (direction == String.Empty)
                {
                    if (HasLogListener)
                    {
                        ForceDispatchLog("NxBRE interprets no-direction directive as forward chaining.", LogEventImpl.WARN);
                    }
                    else if (direction == "bidirectional")
                    {
                        if (HasLogListener)
                        {
                            ForceDispatchLog("NxBRE interprets bidirectional as forward chaining.", LogEventImpl.WARN);
                        }
                        else if (direction != "forward")
                        {
                            throw new BREException("NxBRE does not support direction: " + direction);
                        }
                    }
                }

                // sets the label
                label = adapter.Label;

                // load the Equivalents and IntegrityQueries if the adapter supports it
                if (adapter is IExtendedRuleBaseAdapter)
                {
                    equivalents = ((IExtendedRuleBaseAdapter)adapter).Equivalents;
                    if (HasLogListener)
                    {
                        ForceDispatchLog("Loaded " + equivalents.Count + " Equivalents", LogEventImpl.DEBUG);
                    }

                    integrityQueries = ((IExtendedRuleBaseAdapter)adapter).IntegrityQueries;
                    foreach (Query integrityQuery in integrityQueries)
                    {
                        WM.FB.RegisterAtoms(integrityQuery.AtomGroup.AllAtoms);
                    }

                    if (HasLogListener)
                    {
                        ForceDispatchLog("Loaded " + integrityQueries.Count + " IntegrityQueries", LogEventImpl.DEBUG);
                    }
                }
                else
                {
                    equivalents      = new ArrayList();
                    integrityQueries = equivalents;
                }

                // instantiate the implication base and the query base
                ib = new ImplicationBase();
                qb = new QueryBase();

                // instantiate the related managers
                mm          = new MutexManager(IB);
                pm          = new PreconditionManager(IB);
                initialized = true;

                // load queries
                foreach (Query query in adapter.Queries)
                {
                    QB.Add(query);
                    WM.FB.RegisterAtoms(query.AtomGroup.AllAtoms);
                }
                if (HasLogListener)
                {
                    ForceDispatchLog("Loaded " + QB.Count + " Queries", LogEventImpl.DEBUG);
                }

                // load implications
                foreach (Implication implication in adapter.Implications)
                {
                    IB.Add(implication);
                    int nbRA = WM.FB.RegisterAtoms(implication.AtomGroup.AllAtoms);
                    if (HasLogListener)
                    {
                        ForceDispatchLog("Registered: " + nbRA + " body atoms", LogEventImpl.DEBUG);
                    }

                    // modifying implication must run searches based on their deduction, so must register the atom
                    if (implication.Action == ImplicationAction.Modify)
                    {
                        nbRA = WM.FB.RegisterAtoms(implication.Deduction);
                        if (HasLogListener)
                        {
                            ForceDispatchLog("Registered: " + nbRA + " head atoms", LogEventImpl.DEBUG);
                        }
                    }
                }
                if (HasLogListener)
                {
                    ForceDispatchLog("Loaded " + IB.Count + " Implications\n", LogEventImpl.DEBUG);
                }

                // load mutexes
                mm.AnalyzeImplications();
                if (HasLogListener)
                {
                    ForceDispatchLog("Loaded Mutexes\n" + mm.ToString(), LogEventImpl.DEBUG);
                }

                // load preconditions
                pm.AnalyzeImplications();
                if (HasLogListener)
                {
                    ForceDispatchLog("Loaded Preconditions\n" + pm.ToString(), LogEventImpl.DEBUG);
                }

                // load facts
                foreach (Fact fact in adapter.Facts)
                {
                    Assert(fact);
                }
                if (HasLogListener)
                {
                    ForceDispatchLog("Loaded " + WM.FB.Count + " Facts", LogEventImpl.DEBUG);
                }

                // finish the WM init
                WM.FinishInitialization();
            }             //end: using adapter
            if (HasLogListener)
            {
                ForceDispatchLog("NxBRE Inference Engine Rule Base Loading Finished", LogEventImpl.INFO);
            }
        }