// GET: Administrators
 public ActionResult Index()
 {
     AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
     List<Administrator> model = hlp.GetAdministrators();
     return View(model);
     
 }
        List<SPTaggableList> GetModel(ClientContext ctx,AppWebHelper hlp)
        {
            List<SPTaggableList> model = null;
            try
            {
                model = new List<SPTaggableList>();
                LogHelper.Log("Inside getmodel");
                if (ctx != null)
                {   
                    ListCollection lists = ctx.Web.Lists;
                    
                    ctx.Load(lists, ListQuery => ListQuery.Include(
                        l=>l.Id,l => l.Title, l => l.BaseType,
                        l => l.Fields.Where(
                            f => f.TypeAsString == "TaxonomyFieldTypeMulti" || f.TypeAsString == "TaxonomyFieldType")
                       ));
                    
                    ctx.ExecuteQuery();
                   
                    foreach (List list in lists)
                    {
                        
                        if (list.BaseType == BaseType.DocumentLibrary && list.Fields.Count > 0)
                        {
                            
                            SPTaggableList NewList = new SPTaggableList();
                            NewList.Title = list.Title;
                            NewList.Id = list.Id.ToString();
                            NewList.Disabled = (hlp.ListsInfo.ContainsKey(NewList.Id) && hlp.ListsInfo[NewList.Id].ChildCount > 0) ? "Disabled" : string.Empty;
                            NewList.Asynchronous = (hlp.ListsInfo.ContainsKey(NewList.Id)) ? hlp.ListsInfo[NewList.Id].Asynchronous : true;
                            
                            List<SPTaggableField> ListFields = new List<SPTaggableField>();
                            foreach (Field field in list.Fields)
                            {
                                TaxonomyField TaxField = field as TaxonomyField;
                                string key = string.Concat(NewList.Id, "_", TaxField.Id.ToString());
                                var isEnabled = hlp.CurrentlyEnabledFields.Where(c=>c["Title"].Equals(key)).SingleOrDefault();
                                ListFields.Add(new SPTaggableField
                                {
                                    Id=TaxField.Id.ToString(),
                                    Title = TaxField.Title,
                                    TaggingEnabled = (isEnabled!=null) ? true : false
                                        
                                });
                            }
                            NewList.Fields = ListFields;                                
                            model.Add(NewList);
                        }
                    }
                }
                
                return model;
            }
            catch(Exception ex)
            {
                LogHelper.Log(ex.Message + ex.StackTrace);
                throw;
            }

        }    
 // GET: GlobalSettings/Edit/5
 public ActionResult Edit(int id)
 {
     try
     {
         AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
         return View(hlp.GetGlobalSetting(id));
     }
     catch (Exception ex)
     {
         LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
         throw;
     }
 }
 public ActionResult Delete(int id, FormCollection collection)
 {
     try
     {
         AppWebHelper hlp = new AppWebHelper(
             HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
         hlp.DeleteAdministrator(id);
         return View("Index", hlp.GetAdministrators());
     }
     catch (Exception ex)
     {
         LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
         throw;
     }
 }
 public ActionResult Edit(int id, FormCollection collection)
 {
     try
     {                
         AppWebHelper hlp = new AppWebHelper(
             HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
         hlp.UpdateGlobalSetting(id,collection["key"],collection["value"]);
         AutoTaggingHelper.GlobalConfigNeedsRefresh = true;
         return View("Index", hlp.GetGlobalSettings());
     }
     catch (Exception ex)
     {
         LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
         throw;
     }
 }      
        public ActionResult ByLetter(string letter)
        {
            List<EmptyWord> model = null;
            try
            {                
                AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
                model = hlp.GetEmptyWords(letter);                
                return PartialView("words", model);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                throw;
            }

        }
        public ActionResult Create(FormCollection collection)
        {
            try
            {                                
                AppWebHelper hlp = new AppWebHelper(
                    HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
                hlp.CreateEmptyWord(collection);
                return View("Index", hlp.GetEmptyWords(collection["word"].Substring(0,1)));                

            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                throw;
            }
        }
        private static List <GlobalSetting> GetGlobalConfig(AppWebHelper hlp)
        {
            if (_GlobalConfig == null || GlobalConfigNeedsRefresh)
            {
                lock (LockObject)
                {
                    if (_GlobalConfig == null || GlobalConfigNeedsRefresh)
                    {
                        _GlobalConfig            = hlp.GetGlobalSettings();
                        GlobalConfigNeedsRefresh = false;
                    }
                }
            }

            return(_GlobalConfig);
        }
        public static bool IsEmptyWord(string word, string lang, AppWebHelper hlp)
        {
            if (_EmptyWords == null || EmptyKeywordsNeedsRefresh)
            {
                lock (LockObject)
                {
                    if (_EmptyWords == null || EmptyKeywordsNeedsRefresh)
                    {
                        AutoTaggingHelper.FillEmptyWords(hlp);
                        EmptyKeywordsNeedsRefresh = false;
                    }
                }
            }
            var ww = _EmptyWords.Where(w => w.word == word && w.lang == lang).SingleOrDefault();

            return((ww != null) ? true:false);
        }
        /// <summary>
        /// The RER are a little buggy. Depending on the event triggered, using this:
        /// TokenHelper.CreateAppEventClientContext(properties, true) returns a null appweb although the 
        /// app web exists...Therefore, as I know the name of my App and since the AppWeb's url corresponds to it
        /// I assume that the default appweb location is https://hostweb/appweb. This isn't valid when the App is deployed
        /// trough the AppCatalog. That's why I record the URL of the AppCatalog in case the App gets installed in the
        /// AppCatalog since this info isn't available from CSOM.
        /// </summary>
        /// <param name="properties"></param>
        void AppInstalled(SPRemoteEventProperties properties)
        {
            LogHelper.Log("The application was installed on "+properties.AppEventProperties.HostWebFullUrl);
            using (ClientContext ctx = TokenHelper.CreateAppEventClientContext(properties, false))
            {
                ctx.Load(ctx.Web);
                ctx.Load(ctx.Web.CurrentUser);         
                ctx.ExecuteQuery();
                if(ctx.Web.WebTemplate == Constants.AppCatalogTemplate)
                {
                    LogHelper.Log("Writing app catalog url", LogSeverity.Error);
                    using(StreamWriter sw =  new StreamWriter(HttpContext.Current.Server.MapPath("~/App_Data/AppCataLog.xml")))
                    {
                        sw.Write(ctx.Web.Url);
                    }
                }
                AppWebHelper hlp = new AppWebHelper(properties.AppEventProperties.AppWebFullUrl.AbsoluteUri, true);
                hlp.AddAdministrator(ctx.Web.CurrentUser.LoginName);

            }
        }
        public ActionResult Upload(HttpPostedFileBase file)
        {
            LogHelper.Log("in upload");
            try
            {

                if (file != null && file.ContentLength > 0)
                {
                    LogHelper.Log("in file");
                    using (StreamReader sr = new StreamReader(file.InputStream))
                    {
                        LogHelper.Log("in StreamReader");
                        
                            LogHelper.Log("in spContext " + HttpContext.Request.Form[Constants.SPAppWebUrl]);
                            LogHelper.Log("in spContext " + HttpContext.Request.QueryString[Constants.SPAppWebUrl]);
                            AppWebHelper hlp = new AppWebHelper(
                                HttpContext.Request.Form[Constants.SPAppWebUrl] as string);
                            hlp.UploadEmptyWords(sr.ReadToEnd());                                                                           
                    }                    
                }
                LogHelper.Log("appweb:" + HttpContext.Request.QueryString["SPAppWebUrl"]);
                return RedirectToAction("Index", "EmptyWords",
                    new
                    {
                       SPHostUrl = HttpContext.Request.Form["SPHostUrl"],
                       SPAppWebUrl = HttpContext.Request.Form["SPAppWebUrl"]
                    });
            }
            catch(Exception ex)
            {
                LogHelper.Log(ex.Message+ex.StackTrace,LogSeverity.Error);
                throw;
            }


           
        }
 public ActionResult EnableAutoTagging(string id)
 {             
     LogHelper.Log("Entering tEnableAutoTagging");
     
     try
     {
         var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
         AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
         using (var ctx = spContext.CreateUserClientContextForSPHost())
         {
             if (hlp.EnableTaggingOnListField(id) == 1) //we register only one RER per list.
             {
                 string[] ids = id.Split(new char[] { '_' });
                 List TargetList = ctx.Web.Lists.GetById(new Guid(ids[0]));
                 ctx.Load(TargetList);
                 ctx.Load(TargetList.EventReceivers);
                 ctx.ExecuteQuery();
                 LogHelper.Log("Adding Event Receivers");
                 ConfigurationHelper.EnableDisableTagging(ctx, TargetList, true,hlp);
             }                    
             return PartialView("ListFields", GetModel(ctx, hlp));
         }                
     }
     catch (Exception ex)
     {
         LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
         throw;
     }            
 }
 public ActionResult SetSync(bool sync,string id)
 {
     try
     {
         var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
         AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
         hlp.SetSync(id, sync);
         LogHelper.Log("sync:" + sync + " id:" + id);
         SPEnabledList m = new SPEnabledList();
         m.Disabled = (hlp.ListsInfo.ContainsKey(id) && hlp.ListsInfo[id].ChildCount > 0) ? true : false;
         return PartialView("SyncStatus", m);
     }
     catch (Exception ex)
     {
         LogHelper.Log(ex.Message + ex.StackTrace);
         throw;
     }
     
 }
        public static void EnableDisableTagging(ClientContext ctx, List TargetList, bool AttachEvents, AppWebHelper hlp)
        {
            LogHelper.Log("Entering EnableDisableTagging");

            if (!AttachEvents)
            {
                try
                {
                    var TargetItemAddedEvent = TargetList.EventReceivers.Where(
                        ev => ev.ReceiverName == Constants.ItemAddedEventReceiverName).SingleOrDefault();

                    if (TargetItemAddedEvent != null)
                    {
                        TargetItemAddedEvent.DeleteObject();
                    }
                    var TargetFieldAddedEvent = TargetList.EventReceivers.Where(
                        ev => ev.ReceiverName == Constants.FieldDeletedEventReceiverName).SingleOrDefault();

                    if (TargetFieldAddedEvent != null)
                    {
                        TargetFieldAddedEvent.DeleteObject();
                    }

                    if (TargetItemAddedEvent != null || TargetFieldAddedEvent != null)
                    {
                        ctx.ExecuteQuery();
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                }
            }
            else
            {
                try
                {
                    int Sequence = 10;
                    EventReceiverDefinitionCreationInformation ItemAddedDef = new EventReceiverDefinitionCreationInformation();
                    ItemAddedDef.EventType        = EventReceiverType.ItemAdded;
                    ItemAddedDef.ReceiverName     = Constants.ItemAddedEventReceiverName;
                    ItemAddedDef.ReceiverUrl      = ConfigurationHelper.GetReceiverUrl();
                    ItemAddedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName;
                    ItemAddedDef.ReceiverClass    = ConfigurationHelper.GetReceiverClass();
                    if (!hlp.ListsInfo.ContainsKey(TargetList.Id.ToString()))
                    {
                        ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous;
                    }
                    else
                    {
                        if (hlp.ListsInfo[TargetList.Id.ToString()].Asynchronous)
                        {
                            ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous;
                        }
                        else
                        {
                            ItemAddedDef.Synchronization = EventReceiverSynchronization.Synchronous;
                        }
                    }

                    ItemAddedDef.SequenceNumber = Sequence;

                    EventReceiverDefinitionCreationInformation FieldDeletedDef = new EventReceiverDefinitionCreationInformation();
                    FieldDeletedDef.EventType        = EventReceiverType.FieldDeleted;
                    FieldDeletedDef.ReceiverName     = Constants.FieldDeletedEventReceiverName;
                    FieldDeletedDef.ReceiverUrl      = ConfigurationHelper.GetReceiverUrl();
                    FieldDeletedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName;
                    FieldDeletedDef.ReceiverClass    = ConfigurationHelper.GetReceiverClass();
                    FieldDeletedDef.Synchronization  = EventReceiverSynchronization.Asynchronous;
                    TargetList.EventReceivers.Add(ItemAddedDef);
                    TargetList.EventReceivers.Add(FieldDeletedDef);

                    TargetList.Update();
                    ctx.ExecuteQuery();
                    LogHelper.Log("Attached AutoTagging for " + ItemAddedDef.EventType.ToString() + " on " + TargetList.Id);
                }
                catch (Exception ex)
                {
                    LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                }
            }
        }
 private static void FillEmptyWords(AppWebHelper hlp)
 {
     _EmptyWords = hlp.GetEmptyWords();
 }       
 private static List<GlobalSetting> GetGlobalConfig(AppWebHelper hlp)
 {
     if (_GlobalConfig == null || GlobalConfigNeedsRefresh)
     {
         lock(LockObject)
         {
             if (_GlobalConfig == null || GlobalConfigNeedsRefresh)
             {
                 _GlobalConfig = hlp.GetGlobalSettings();
                 GlobalConfigNeedsRefresh = false;
             }
         }
     }
     
     return _GlobalConfig;
 }
 public static bool IsEmptyWord(string word,string lang,AppWebHelper hlp)
 {
     if (_EmptyWords == null || EmptyKeywordsNeedsRefresh)
     {                
         lock (LockObject)
         {
             if (_EmptyWords == null || EmptyKeywordsNeedsRefresh)
             {
                 AutoTaggingHelper.FillEmptyWords(hlp);
                 EmptyKeywordsNeedsRefresh = false;
             }
         }                
     }
     var ww = _EmptyWords.Where(w => w.word == word && w.lang == lang).SingleOrDefault();
     return (ww != null) ? true:false;
 }
        /// <summary>
        /// Helper Method to set a Taxonomy Field on a list item
        /// </summary>
        /// <param name="ctx">The Authenticated ClientContext</param>
        /// <param name="listItem">The listitem to modify</param>
        /// <param name="model">Domain Object of key/value pairs of the taxonomy field & value</param>
        public static void SetTaxonomyFields(ClientContext ctx, ListItem listItem,string FileContent,string ListId,string url)
        {                           
            FieldCollection _fields = listItem.ParentList.Fields;
            ctx.Load(ctx.Web.AllProperties);
            ctx.Load(_fields);
            ctx.ExecuteQuery();

            AppWebHelper hlp = new AppWebHelper(url,false);
            List<GlobalSetting> settings = GetGlobalConfig(hlp);
            LogHelper.Log(settings.Count.ToString());
            var enabled = settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault();
            
            bool KeywordCreationEnabled = Convert.ToBoolean(
                settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault().value);
            int KeywordRecognitionTreshold = Convert.ToInt32(
                                settings.Where(s => s.key == Constants.KeywordRecognitionTreshold).SingleOrDefault().value);
            int KeywordCreationTreshold = Convert.ToInt32(
                                settings.Where(s => s.key == Constants.KeywordCreationTreshold).SingleOrDefault().value);

            List<string> ConfiguredFields = hlp.ListTaxFields(ListId);
            foreach(var _f in _fields)
            {                
                if(ConfiguredFields.Contains(_f.Id.ToString()))
                {
                    TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetById(_f.Id));
                    if(_f.InternalName != Constants.TaxFieldInternalName)
                    {
                        
                        ctx.Load(_field);
                        ctx.ExecuteQuery();
                        Collection<Term> MatchingTerms = null;
                        MatchingTerms = AutoTaggingHelper.MatchingTerms(FileContent, ctx, _field.TermSetId, _field.AnchorId);

                        if (MatchingTerms.Count > 0)
                        {
                            LogHelper.Log("Updating taxfield " + _field.Title);
                            if (_field.AllowMultipleValues)
                            {
                                _field.SetFieldValueByCollection(listItem, MatchingTerms, 1033);
                            }
                            else
                            {
                                _field.SetFieldValueByTerm(listItem, MatchingTerms.First(), 1033);
                            }

                            listItem.Update();
                            ctx.ExecuteQuery();
                        }    
                    }
                    else
                    {
                        TaxonomyTerms tt = new TaxonomyTerms(ctx);
                        string TextLanguage=
                            AutoTaggingHelper.LanguageIdentifier.Identify(FileContent).FirstOrDefault().Item1.Iso639_3;
                        StringBuilder EntKeyWordsValue = new StringBuilder();
                        Dictionary<string, int> tokens = 
                            Tokenize(FileContent,
                            KeywordRecognitionTreshold,
                            TextLanguage);
                        StringBuilder TokenString = new StringBuilder();
                        foreach (KeyValuePair<string, int> token in tokens)
                        {
                            Guid KeywordId = TaxonomyTerms.GetKeyword(token.Key);
                            TokenString.AppendFormat("{0}|", token.Key);
                            if (KeywordId != Guid.Empty)
                            {
                                EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, KeywordId);
                            }
                            else
                            {
                                
                                if (KeywordCreationEnabled && token.Value >= KeywordCreationTreshold &&
                                    !AutoTaggingHelper.IsEmptyWord(token.Key.ToLowerInvariant(), TextLanguage,hlp))
                                {
                                    
                                    Guid g = AddKeyWord(token.Key, ctx);
                                    if (g != Guid.Empty)
                                    {
                                        EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, g);
                                    }

                                }
                            }
                        }
                        LogHelper.Log(TokenString.ToString());
                        if (EntKeyWordsValue.ToString().Length > 0)
                        {
                            LogHelper.Log("keyword value " + EntKeyWordsValue.ToString(), LogSeverity.Error);

                            TaxonomyFieldValueCollection col = new TaxonomyFieldValueCollection(ctx, string.Empty, _field);
                            col.PopulateFromLabelGuidPairs(EntKeyWordsValue.ToString());
                            _field.SetFieldValueByValueCollection(listItem, col);
                            listItem.Update();
                            ctx.ExecuteQuery();
                        }                       
                    }
                        
                }
            }

        }        
 public ActionResult Index()
 {
     AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
     List<GlobalSetting> model = hlp.GetGlobalSettings();
     return View(model);
 }                       
        public ActionResult DisableAutoTagging(string id)
        {
            LogHelper.Log("Entering DisableAutoTagging");
            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
                AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
                using (var ctx = spContext.CreateUserClientContextForSPHost())
                {
                    string[] ids = id.Split(new char[] { '_' });
                    LogHelper.Log("Inside DisableAutoTagging");
                    if (hlp.DisableTaggingOnListField(ids[1],ids[0]) == 0) //Only delete the RER if no more fields are enabled.
                    {
                        
                        List TargetList = ctx.Web.Lists.GetById(new Guid(ids[0]));
                        ctx.Load(TargetList.EventReceivers);
                        ctx.Load(TargetList);
                        ctx.ExecuteQuery();
                        LogHelper.Log("Before EnableDisableTagging");
                        ConfigurationHelper.EnableDisableTagging(ctx, TargetList, false,hlp);
                        LogHelper.Log("After EnableDisableTagging");
                    }

                    return PartialView("ListFields", GetModel(ctx, new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string)));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                throw;
            }
            
        }
        public static void EnableDisableTagging(ClientContext ctx,List TargetList,bool AttachEvents,AppWebHelper hlp)
        {
            LogHelper.Log("Entering EnableDisableTagging");
            
            if (!AttachEvents)
            {
                try
                {
                    
                    var TargetItemAddedEvent = TargetList.EventReceivers.Where(
                        ev => ev.ReceiverName == Constants.ItemAddedEventReceiverName).SingleOrDefault();

                    if (TargetItemAddedEvent != null)
                    {
                        TargetItemAddedEvent.DeleteObject();                        
                    }
                    var TargetFieldAddedEvent = TargetList.EventReceivers.Where(
                        ev => ev.ReceiverName == Constants.FieldDeletedEventReceiverName).SingleOrDefault();

                    if (TargetFieldAddedEvent != null)
                    {
                        TargetFieldAddedEvent.DeleteObject();
                    }
                    
                    if(TargetItemAddedEvent != null || TargetFieldAddedEvent != null)
                    {
                        ctx.ExecuteQuery();
                    }

        
                }
                catch (Exception ex)
                {
                    LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                }

            }
            else
            {
                try
                {
                    int Sequence = 10;                            
                    EventReceiverDefinitionCreationInformation ItemAddedDef = new EventReceiverDefinitionCreationInformation();
                    ItemAddedDef.EventType = EventReceiverType.ItemAdded;
                    ItemAddedDef.ReceiverName = Constants.ItemAddedEventReceiverName;
                    ItemAddedDef.ReceiverUrl = ConfigurationHelper.GetReceiverUrl();
                    ItemAddedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName;
                    ItemAddedDef.ReceiverClass = ConfigurationHelper.GetReceiverClass();
                    if(!hlp.ListsInfo.ContainsKey(TargetList.Id.ToString()))
                    {
                        ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous;
                    }
                    else
                    {
                        if (hlp.ListsInfo[TargetList.Id.ToString()].Asynchronous)
                        {
                            ItemAddedDef.Synchronization = EventReceiverSynchronization.Asynchronous;
                        }
                        else
                        {
                            ItemAddedDef.Synchronization = EventReceiverSynchronization.Synchronous;
                        }   
                    }
                                     
                    ItemAddedDef.SequenceNumber = Sequence;

                    EventReceiverDefinitionCreationInformation FieldDeletedDef = new EventReceiverDefinitionCreationInformation();
                    FieldDeletedDef.EventType = EventReceiverType.FieldDeleted;
                    FieldDeletedDef.ReceiverName = Constants.FieldDeletedEventReceiverName;
                    FieldDeletedDef.ReceiverUrl = ConfigurationHelper.GetReceiverUrl();
                    FieldDeletedDef.ReceiverAssembly = Assembly.GetExecutingAssembly().FullName;
                    FieldDeletedDef.ReceiverClass = ConfigurationHelper.GetReceiverClass();
                    FieldDeletedDef.Synchronization = EventReceiverSynchronization.Asynchronous;
                    TargetList.EventReceivers.Add(ItemAddedDef);
                    TargetList.EventReceivers.Add(FieldDeletedDef);

                    TargetList.Update();                    
                    ctx.ExecuteQuery();
                    LogHelper.Log("Attached AutoTagging for " + ItemAddedDef.EventType.ToString() + " on " + TargetList.Id);
                }
                catch (Exception ex)
                {
                    LogHelper.Log(ex.Message+ex.StackTrace,LogSeverity.Error);
                }
            
            }
        }
 private static void FillEmptyWords(AppWebHelper hlp)
 {
     _EmptyWords = hlp.GetEmptyWords();
 }
        /// <summary>
        /// Helper Method to set a Taxonomy Field on a list item
        /// </summary>
        /// <param name="ctx">The Authenticated ClientContext</param>
        /// <param name="listItem">The listitem to modify</param>
        /// <param name="model">Domain Object of key/value pairs of the taxonomy field & value</param>
        public static void SetTaxonomyFields(ClientContext ctx, ListItem listItem, string FileContent, string ListId, string url)
        {
            FieldCollection _fields = listItem.ParentList.Fields;

            ctx.Load(ctx.Web.AllProperties);
            ctx.Load(_fields);
            ctx.ExecuteQuery();

            AppWebHelper         hlp      = new AppWebHelper(url, false);
            List <GlobalSetting> settings = GetGlobalConfig(hlp);

            LogHelper.Log(settings.Count.ToString());
            var enabled = settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault();

            bool KeywordCreationEnabled = Convert.ToBoolean(
                settings.Where(s => s.key == Constants.EnableKeywordCreation).SingleOrDefault().value);
            int KeywordRecognitionTreshold = Convert.ToInt32(
                settings.Where(s => s.key == Constants.KeywordRecognitionTreshold).SingleOrDefault().value);
            int KeywordCreationTreshold = Convert.ToInt32(
                settings.Where(s => s.key == Constants.KeywordCreationTreshold).SingleOrDefault().value);

            List <string> ConfiguredFields = hlp.ListTaxFields(ListId);

            foreach (var _f in _fields)
            {
                if (ConfiguredFields.Contains(_f.Id.ToString()))
                {
                    TaxonomyField _field = ctx.CastTo <TaxonomyField>(_fields.GetById(_f.Id));
                    if (_f.InternalName != Constants.TaxFieldInternalName)
                    {
                        ctx.Load(_field);
                        ctx.ExecuteQuery();
                        Collection <Term> MatchingTerms = null;
                        MatchingTerms = AutoTaggingHelper.MatchingTerms(FileContent, ctx, _field.TermSetId, _field.AnchorId);

                        if (MatchingTerms.Count > 0)
                        {
                            LogHelper.Log("Updating taxfield " + _field.Title);
                            if (_field.AllowMultipleValues)
                            {
                                _field.SetFieldValueByCollection(listItem, MatchingTerms, 1033);
                            }
                            else
                            {
                                _field.SetFieldValueByTerm(listItem, MatchingTerms.First(), 1033);
                            }

                            listItem.Update();
                            ctx.ExecuteQuery();
                        }
                    }
                    else
                    {
                        TaxonomyTerms tt           = new TaxonomyTerms(ctx);
                        string        TextLanguage =
                            AutoTaggingHelper.LanguageIdentifier.Identify(FileContent).FirstOrDefault().Item1.Iso639_3;
                        StringBuilder            EntKeyWordsValue = new StringBuilder();
                        Dictionary <string, int> tokens           =
                            Tokenize(FileContent,
                                     KeywordRecognitionTreshold,
                                     TextLanguage);
                        StringBuilder TokenString = new StringBuilder();
                        foreach (KeyValuePair <string, int> token in tokens)
                        {
                            Guid KeywordId = TaxonomyTerms.GetKeyword(token.Key);
                            TokenString.AppendFormat("{0}|", token.Key);
                            if (KeywordId != Guid.Empty)
                            {
                                EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, KeywordId);
                            }
                            else
                            {
                                if (KeywordCreationEnabled && token.Value >= KeywordCreationTreshold &&
                                    !AutoTaggingHelper.IsEmptyWord(token.Key.ToLowerInvariant(), TextLanguage, hlp))
                                {
                                    Guid g = AddKeyWord(token.Key, ctx);
                                    if (g != Guid.Empty)
                                    {
                                        EntKeyWordsValue.AppendFormat("-1;#{0}|{1};", token.Key, g);
                                    }
                                }
                            }
                        }
                        LogHelper.Log(TokenString.ToString());
                        if (EntKeyWordsValue.ToString().Length > 0)
                        {
                            LogHelper.Log("keyword value " + EntKeyWordsValue.ToString(), LogSeverity.Error);

                            TaxonomyFieldValueCollection col = new TaxonomyFieldValueCollection(ctx, string.Empty, _field);
                            col.PopulateFromLabelGuidPairs(EntKeyWordsValue.ToString());
                            _field.SetFieldValueByValueCollection(listItem, col);
                            listItem.Update();
                            ctx.ExecuteQuery();
                        }
                    }
                }
            }
        }
        public void HandleAutoTaggingFieldDeleted(SPRemoteEventProperties properties)
        {
            
            string TargetFieldId = GetFieldId(properties.ListEventProperties.FieldXml);
            LogHelper.Log("Field "+TargetFieldId+" was deleted, cleaning config list");
            Uri webUri = new Uri(properties.ListEventProperties.WebUrl);
            string realm = TokenHelper.GetRealmFromTargetUrl(webUri);
            string accessToken = TokenHelper.GetAppOnlyAccessToken(
                TokenHelper.SharePointPrincipal, webUri.Authority, realm).AccessToken;
            using (var ctx = TokenHelper.GetClientContextWithAccessToken(properties.ListEventProperties.WebUrl, accessToken))
            {
                if (ctx != null)
                {
                    ctx.Load(ctx.Web.AllProperties);
                    ctx.ExecuteQuery();
                    AppWebHelper hlp = new AppWebHelper(properties.ListEventProperties.WebUrl,false);
                    if (hlp.DisableTaggingOnListField(TargetFieldId, properties.ListEventProperties.ListId.ToString()) == 0) //Only delete the RER if no more fields are enabled.
                    {
                        

                
                                List TargetList = ctx.Web.Lists.GetById(properties.ListEventProperties.ListId);
                                ctx.Load(TargetList.EventReceivers);
                                ctx.Load(TargetList);
                                ctx.ExecuteQuery();
                                LogHelper.Log("Before EnableDisableTagging");
                                ConfigurationHelper.EnableDisableTagging(ctx, TargetList, false,hlp);
                                LogHelper.Log("After EnableDisableTagging");
                    }
                }                
            }
        }