// Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite osite = ((SPSite)properties.Feature.Parent);

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite elevatedSite = new SPSite(osite.ID))
                    {
                        var web = elevatedSite.RootWeb;
                        RemoveEventReceiverFromList(web);
                        SPList list            = web.GetList(web.ServerRelativeUrl + "/_catalogs/masterpage/");
                        bool oldWebAllowUnsafe = web.AllowUnsafeUpdates;
                        web.AllowUnsafeUpdates = true;

                        foreach (SPListItem item in list.Items)
                        {
                            if (item.File.CheckedOutByUser != null)
                            {
                                Page page = HttpContext.Current.Handler as Page;
                                SPLongOperation operation = new SPLongOperation(page);
                                operation.Begin();
                                try
                                {
                                    operation.End("javascript:if(!alert('Cannot activate the feature of tracking, master page: " + Convert.ToString(item["Name"]) + " is checked out by user: "******" (" + item.File.CheckedOutByUser.LoginName + ").')) document.location = window.location.href.substring(0, window.location.href.indexOf('_layouts')) + '_catalogs/masterpage/Forms/AllItems.aspx';", SPRedirectFlags.Static, HttpContext.Current, null);
                                }
                                catch (ThreadAbortException ex)
                                {
                                    Logger.WriteLog(Logger.Category.Information, "Piwik Master page is checked out: " + Convert.ToString(item["Name"]), ex.Message);
                                }
                                catch (Exception ex) { throw ex; }
                            }
                        }

                        foreach (SPListItem item in list.Items)
                        {
                            if (Convert.ToString(item["Name"]).ToLower().EndsWith(".master"))
                            {
                                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                                EventDisabler eventDisabler   = new EventDisabler();
                                SPFile file            = item.File;
                                byte[] byteArrayOfFile = file.OpenBinary();
                                if (byteArrayOfFile.Length > 0)
                                {
                                    string strFileContentsBefore = enc.GetString(byteArrayOfFile);
                                    //check if javascript exists
                                    PropertyBagOperations pbos = new PropertyBagOperations();
                                    string trackerJSScriptUrl  = pbos.GetPropertyValueFromListByKey("piwik_trackerjsscripturl");
                                    if (!strFileContentsBefore.ToLower().Contains(trackerJSScriptUrl.ToLower()))
                                    {
                                        if (item.File.CheckOutType == SPFile.SPCheckOutType.None)
                                        {
                                            SPFileLevel oldLevel = item.File.Level;
                                            string newStr        = AddJSRefToFile(strFileContentsBefore, trackerJSScriptUrl);
                                            byte[] byteArrayFileContentsAfter = null;
                                            if (!newStr.Equals(""))
                                            {
                                                //after binary to string there are ??? chars at the first line, this is the action to replace it:
                                                if (newStr.Substring(0, 3).Equals("???"))
                                                {
                                                    newStr = newStr.Replace("???", "");
                                                }
                                                byteArrayFileContentsAfter = enc.GetBytes(newStr);
                                                eventDisabler.DisableEvents();
                                            }

                                            if (list.ForceCheckout)
                                            {
                                                item.File.CheckOut();
                                            }

                                            item.File.SaveBinary(byteArrayFileContentsAfter);
                                            item.File.Update();

                                            if (list.ForceCheckout)
                                            {
                                                if (item.File.Level == SPFileLevel.Checkout)
                                                {
                                                    if (oldLevel == SPFileLevel.Published)
                                                    {
                                                        item.File.CheckIn("", SPCheckinType.MajorCheckIn);
                                                    }
                                                    else
                                                    {
                                                        item.File.CheckIn("", SPCheckinType.MinorCheckIn);
                                                    }
                                                }
                                            }

                                            try
                                            {
                                                if (oldLevel == SPFileLevel.Published)
                                                {
                                                    if (item.File.DocumentLibrary.EnableModeration)
                                                    {
                                                        item.File.Approve("");
                                                    }
                                                    else
                                                    {
                                                        item.File.Publish("");
                                                    }
                                                }
                                            }
                                            catch (Exception exp)
                                            {
                                                Logger.WriteLog(Logger.Category.Unexpected, "Piwik FeatureActivating publish or approve master", exp.Message);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        CreateOrUpdateValueInPropertyBag("false", web, web.Properties, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);

                        web.AllowUnsafeUpdates = oldWebAllowUnsafe;
                    }
                    bool ifWasntDeactivatingAndActive = true;
                    PropertyBagOperations pbo         = new PropertyBagOperations();
                    Configuration cfg = new Configuration();

                    using (SPSite elevatedSite = new SPSite(cfg.PiwikAdminSiteUrl))
                    {
                        ClientContext context        = new ClientContext(pbo.GetPropertyValueFromListByKey(ConfigValues.PiwikPro_PropertyBag_AdminSiteUrl));
                        ListProcessor sdlo           = new ListProcessor(context, cfg, new SPLogger());
                        ifWasntDeactivatingAndActive = sdlo.AddOrUpdateElementInList(osite.RootWeb.Title, ConfigValues.PiwikPro_SiteDirectory_Column_Status_New, osite.RootWeb.Url, "", osite.RootWeb.ServerRelativeUrl, "");
                    }
                    if (!ifWasntDeactivatingAndActive)
                    {
                        using (SPSite elevatedSite = new SPSite(osite.ID))
                        {
                            var web = elevatedSite.RootWeb;
                            CreateOrUpdateValueInPropertyBag("true", web, web.Properties, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);
                        }
                    }
                }
                catch (Exception exc)
                {
                    Logger.WriteLog(Logger.Category.Unexpected, "Piwik FeatureActivating Full in elevated", exc.Message);
                }
            });
        }
        /// <summary>Initializes a new instance of the <see cref="CustomRecordListItems"/> class.</summary>
        /// <param name="url">The url.</param>
        /// <param name="sourceFolder">The source folder.</param>
        /// <param name="destinationFolder">The destination folder.</param>
        public CustomRecordListItems(string url, string sourceFolder, string destinationFolder)
        {
            if (String.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(url, "Inavild url");
            }

            if (String.IsNullOrEmpty(sourceFolder))
            {
                throw new ArgumentNullException(sourceFolder, "Invalid folder");
            }

            if (String.IsNullOrEmpty(destinationFolder))
            {
                throw new ArgumentNullException(destinationFolder, "Invalid folder");
            }

            this.DocumentsSourceFolder = sourceFolder;
            this.DocumentsFinalFolder  = destinationFolder;

            using (SPSite spSite = new SPSite(url))
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    // EcmDoc
                    EcmDocumentRoutingWeb ecmDocumentRoutingWeb = new EcmDocumentRoutingWeb(spWeb);

                    // current user specs
                    this.LoginName     = System.Threading.Thread.CurrentPrincipal.Identity.Name;
                    this.DocumentsUser = SPContext.Current.Web.CurrentUser;

                    // screening the source folder
                    SPList spList = spWeb.Lists[sourceFolder];
                    this.DocumentsFields = spList.Fields;
                    int fieldsLimit = spList.Fields.Count;

                    // viewing all items in source folder
                    SPView spView = spList.Views["All Items"];

                    // current view fields on all items in source folder
                    this.DocumentsViewFields = spView.ViewFields;
                    int viewFieldsLimit = spView.ViewFields.Count;

                    // screening the item collection for each item
                    this.DocumentsItems = spList.Items;

                    foreach (SPListItem spListItem in this.DocumentsItems)
                    {
                        SPContentType               spContentType               = spListItem.ContentType;
                        SPCopyFieldMask             spCopyFieldMask             = spListItem.CopyFieldMask;
                        SPCopyDestinationCollection spCopyDestinationCollection = spListItem.CopyDestinations;
                        string                      displayName       = spListItem.DisplayName;
                        SPBasePermissions           spBasePermissions = spListItem.EffectiveBasePermissions;
                        SPFieldCollection           spFieldCollection = spListItem.Fields;
                        SPFile                      spFile            = spListItem.File;
                        SPFolder                    spFolder          = spListItem.Folder;
                        SPFileLevel                 spFileLevel       = spListItem.Level;
                        string                      name       = spListItem.Name;
                        Hashtable                   properties = spListItem.Properties;
                        string                      title      = spListItem.Title;
                        string                      strUrl     = spListItem.Url;
                        SPListItemVersionCollection spListItemVersionCollection = spListItem.Versions;
                        string                      xml = spListItem.Xml;
                    }
                }
        }