Ejemplo n.º 1
0
        public static OutputQueue ExecuteInstallerJob(string jobName, int timeout)
        {
            // Minimum 15 Minutes
            if (timeout < 900000)
            {
                timeout = 900000;
            }

            if (jobName.Equals(RecycleJobName, StringComparison.OrdinalIgnoreCase))
            {
                return(ExecuteRecycleTimerJob(timeout));
            }

            var output = new OutputQueue();

            try
            {
                // Ensure NewsGator.Install.Jobs.wsp is deployed
                if (LocalFarm.Get().Solutions[SolutionName] == null ||
                    !LocalFarm.Get().Solutions[SolutionName].Deployed)
                {
                    throw new InvalidOperationException(NewsGator.Install.Resources.Exceptions.RestartServicesMissingSolution);
                }

                if (LocalFarm.Get().FeatureDefinitions[FeatureId] == null)
                {
                    LocalFarm.Get().FeatureDefinitions.Add("NewsGator.Install.Jobs_InstallJobs\\Feature.xml", LocalFarm.Get().Solutions[SolutionName].Id, true);
                    Thread.Sleep(30000);
                }

                // Ensure Installer Jobs Farm Feature is activated
                if (SPWebService.AdministrationService.Features[FeatureId] == null)
                {
                    output.Add(NewsGator.Install.Resources.Tasks.TaskDetails_RestartServices_ActivatingFarmFeature);
                    SPWebService.AdministrationService.Features.Add(FeatureId);
                    Thread.Sleep(30000);
                }

                // Run the Restart Services timer job
                var timerService = LocalFarm.Get().Services.Where(p => p is SPTimerService).First() as SPTimerService;
                var jobIds       = timerService.JobDefinitions.Where(p => (p.Name.IndexOf(jobName, StringComparison.OrdinalIgnoreCase) > -1)).Select(q => q.Id);

                if (jobIds == null || jobIds.Count() == 0)
                {
                    if (SPWebService.AdministrationService.Features[FeatureId] != null)
                    {
                        SPWebService.AdministrationService.Features.Remove(FeatureId);
                        Thread.Sleep(30000);
                    }

                    SPWebService.AdministrationService.Features.Add(FeatureId);
                    Thread.Sleep(30000);

                    timerService = LocalFarm.Get().Services.Where(p => p is SPTimerService).First() as SPTimerService;
                    jobIds       = timerService.JobDefinitions.Where(p => (p.Name.IndexOf(jobName, StringComparison.OrdinalIgnoreCase) > -1)).Select(q => q.Id);

                    if (jobIds == null || jobIds.Count() == 0)
                    {
                        throw new InvalidOperationException(Exceptions.JobsNotFoundException);
                    }
                }

                var propertyIds = new Collection <string>();

                timerService = LocalFarm.Get().Services.Where(p => p is SPTimerService).First() as SPTimerService;
                foreach (var jobId in jobIds)
                {
                    var job        = timerService.JobDefinitions.Where(p => p.Id == jobId).First();
                    var serverName = job.Server != null ? job.Server.Address : string.Empty;

                    try
                    {
                        output.Add(string.Format(CultureInfo.CurrentUICulture, NewsGator.Install.Resources.Tasks.TaskDetails_StartingJob, serverName));

                        var propertyId = "ng-run-" + jobId.ToString();

                        SPSecurity.RunWithElevatedPrivileges(() =>
                        {
                            if (!LocalFarm.Get().Properties.ContainsKey(propertyId))
                            {
                                LocalFarm.Get().Properties.Add(propertyId, propertyId);
                            }
                        });

                        propertyIds.Add(propertyId);
                    }
                    catch (Exception exception)
                    {
                        output.Add(string.Format(CultureInfo.CurrentUICulture, NewsGator.Install.Resources.Exceptions.TimerJobExceptionOn, serverName, exception.Message), OutputType.Error, exception.ToString(), exception);
                    }
                }

                LocalFarm.Get().TryUpdate();
                Thread.Sleep(10000);

                var timeoutTime = DateTime.Now.AddMilliseconds(timeout * 0.95);
                var complete    = false;

                while (!complete)
                {
                    var jobRunning = false;

                    foreach (var propertyId in propertyIds)
                    {
                        try
                        {
                            if (LocalFarm.Get().Properties.ContainsKey(propertyId))
                            {
                                jobRunning = true;
                            }
                        }
                        catch { }
                    }

                    if (!jobRunning)
                    {
                        complete = true;
                    }

                    if (!complete)
                    {
                        if (DateTime.Now > timeoutTime)
                        {
                            throw new System.TimeoutException();
                        }
                        else
                        {
                            LocalFarm.Get().TryUpdate();
                            Thread.Sleep(10000);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                output.Add(string.Format(CultureInfo.CurrentUICulture, NewsGator.Install.Resources.Exceptions.TimerJobException, exception.Message), OutputType.Error, exception.ToString(), exception);
            }

            var keysToRemove = new List <string>();

            foreach (var propertyKey in LocalFarm.Get().Properties.Keys)
            {
                var key = propertyKey as string;
                if (!string.IsNullOrEmpty(key))
                {
                    if (key.StartsWith("ng-run-", StringComparison.OrdinalIgnoreCase))
                    {
                        keysToRemove.Add(key);
                    }
                }
            }
            foreach (var key in keysToRemove)
            {
                LocalFarm.Get().Properties.Remove(key);
            }

            LocalFarm.Get().TryUpdate();

            return(output);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Crea una relacion automática hacia la lista Correspondencia de Entrada
        /// </summary>
        /// <param name="properties"></param>
        private void EventoAsociarCorrespondenciaEntrante(SPItemEventProperties properties)
        {
            SPSite sitioAdm = null;
            SPWeb  webAdm   = null;

            try
            {
                string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"];

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {//Como usuario administrador
                    sitioAdm = new SPSite(UrlFPC);
                    webAdm   = sitioAdm.OpenWeb();
                });

                SPListItem itemSalida = properties.ListItem;
                SPListItem itemEntrada;
                SPFieldLookupValueCollection enlacesSalida =
                    (SPFieldLookupValueCollection)itemSalida["En respuesta a"];
                SPFieldLookupValueCollection enlacesEntrada;

                #region Definir la lista usada
                string listaCorreoUsada = "";
                if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                  CORREO_SALIDA_FUNDAPRO, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_FUNDAPRO;
                }
                else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                       CORREO_SALIDA_EDUCAPRO, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO;
                }
                else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                       CORREO_SALIDA_EDUCAPRO_CB, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_CB;
                }
                else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                       CORREO_SALIDA_EDUCAPRO_SC, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_SC;
                }
                #endregion

                #region Crear relacion sobre este elemento
                foreach (SPFieldLookupValue enlaceSalida in enlacesSalida)
                {
                    itemEntrada = webAdm.Lists[listaCorreoUsada].Items.GetItemById(
                        enlaceSalida.LookupId);
                    enlacesEntrada = (SPFieldLookupValueCollection)itemEntrada["Respuesta"];

                    SPFieldLookupValue enlaceEntrada = new SPFieldLookupValue(itemSalida.ID,
                                                                              itemSalida["CITE"].ToString());

                    if (!enlacesEntrada.Contains(enlaceEntrada))
                    {
                        enlacesEntrada.Add(enlaceEntrada);
                    }

                    itemEntrada["Respuesta"] = enlacesEntrada;

                    using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                    {
                        itemEntrada.SystemUpdate();
                    }
                }
                #endregion
            }
            finally
            {
                if (webAdm != null)
                {
                    webAdm.Dispose();
                }
                if (sitioAdm != null)
                {
                    sitioAdm.Dispose();
                }
            }
        }
        private void AddTimerJob(SPItemEventProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                base.EventFiringEnabled    = false;
                GridGanttSettings settings = new GridGanttSettings(properties.List);

                bool isSecure = false;
                try
                {
                    isSecure = settings.BuildTeamSecurity;
                }
                catch { }


                int priority = 1;
                if (isSecure)
                {
                    priority = 0;
                }

                using (var sqlConnection = new SqlConnection(CoreFunctions.getConnectionString(properties.Web.Site.WebApplication.Id)))
                {
                    sqlConnection.Open();
                    using (var sqlCommand = new SqlCommand("INSERT INTO ITEMSEC (SITE_ID, WEB_ID, LIST_ID, ITEM_ID, USER_ID, priority) VALUES (@siteid, @webid, @listid, @itemid, @userid, @priority)", sqlConnection))
                    {
                        sqlCommand.Parameters.AddWithValue("@siteid", properties.SiteId);
                        sqlCommand.Parameters.AddWithValue("@webid", properties.Web.ID);
                        sqlCommand.Parameters.AddWithValue("@listid", properties.ListId);
                        sqlCommand.Parameters.AddWithValue("@itemid", properties.ListItemId);
                        sqlCommand.Parameters.AddWithValue("@userid", properties.CurrentUserId);
                        sqlCommand.Parameters.AddWithValue("@priority", priority);
                        sqlCommand.ExecuteNonQuery();
                    }
                }
                SPUser orignalUser = properties.Web.AllUsers.GetByID(properties.CurrentUserId);

                if (isSecure)
                {
                    SPListItem li = properties.ListItem;

                    string safeTitle = !string.IsNullOrEmpty(li.Title) ? GetSafeGroupTitle(li.Title) : string.Empty;

                    properties.Web.AllowUnsafeUpdates = true;

                    SPFieldLookup assignedTo = null;
                    try
                    {
                        assignedTo = properties.List.Fields.GetFieldByInternalName("AssignedTo") as SPFieldLookup;
                    }
                    catch { }

                    object assignedToFv = null;
                    string sAssignedTo  = string.Empty;
                    try
                    {
                        assignedToFv = li["AssignedTo"];
                    }
                    catch { }
                    if (assignedToFv != null)
                    {
                        sAssignedTo = assignedToFv.ToString();
                    }

                    if (string.IsNullOrEmpty(sAssignedTo))
                    {
                        li["AssignedTo"] = new SPFieldUserValue(properties.Web, orignalUser.ID, orignalUser.LoginName);

                        try
                        {
                            li.SystemUpdate();
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }
                base.EventFiringEnabled = true;
            });
        }
Ejemplo n.º 4
0
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                btnCreate.Text = "One Moment...";
            }
            using (SPLongOperation siteIsProvisioning = new SPLongOperation(this.Page))
            {
                siteIsProvisioning.LeadingHTML  = "Provisioning your new site...";
                siteIsProvisioning.TrailingHTML = "You will be directed to your site shortly.";
                siteIsProvisioning.Begin();

                Project project = new Project();

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        bool siteCreated              = false;
                        project.ProjectId             = Utility.generateSiteId(_parentWebUrl);
                        project.ProjectName           = txtProjectName.Text.ToString();
                        project.ProjectDescription    = txtProjectDesc.Text.ToString();
                        project.ProjectLeadSPUser     = Utility.retrieveUsersFromPeoplePicker(ppProjectLead, _parentWebUrl).FirstOrDefault();
                        project.ProjectLead           = project.ProjectLeadSPUser.Name;
                        project.ProjectStatus         = ddStatus.Text.ToString();
                        List <SPUser> additionalUsers = Utility.retrieveUsersFromPeoplePicker(ppAdditionalMembers, _parentWebUrl);
#if DEBUG
                        project.ProjectId = "test"; siteCreated = true;
#endif

#if !DEBUG
                        SPUtility.ValidateFormDigest();
                        using (var web = new SPSite(_parentWebUrl).OpenWeb())
                        {
                            try
                            {
                                web.AllowUnsafeUpdates = true;
                                siteCreated            = provisioning.createSiteFromTemplateSolution(project, _templateSolutionName);
                                web.AllowUnsafeUpdates = false;
                            }
                            catch (Exception ex)
                            { throw new SPException("Your request to create a Project Site '" + txtProjectName.Text.ToString() + "' could not be completed.", ex); }
                        }
#endif
                        if (siteCreated)
                        {
                            using (var web = new SPSite(_parentWebUrl + "/" + project.ProjectId).OpenWeb())
                            {
                                siteIsProvisioning.LeadingHTML = "Setting site properties...";
                                SPUtility.ValidateFormDigest();
                                web.AllowUnsafeUpdates                   = true;
                                web.AllProperties["Site_Created"]        = DateTime.Now.ToString("g");
                                web.AllProperties["Project_ID"]          = project.ProjectId;
                                web.AllProperties["Project_Name"]        = project.ProjectName;
                                web.AllProperties["Project_Description"] = project.ProjectDescription;
                                web.AllProperties["Project_Status"]      = project.ProjectStatus;
                                web.AllProperties["Project_Lead"]        = project.ProjectLead;

                                //provisioning.updateProperties(project);  //not working?
                                web.Update();
                                siteIsProvisioning.LeadingHTML = "Assigning users to site...";
                                provisioning.setSiteSecurity(project,
                                                             "Litigation Management Owners",
                                                             "Site Manager",
                                                             "Read Only Users",
                                                             "Additional Contributors");

                                if (additionalUsers.Count > 0)
                                {
                                    SPUtility.ValidateFormDigest();
                                    SPGroup grpAdditionalUsers = web.SiteGroups[project.ProjectId + " - Additional Contributors"];
                                    foreach (SPUser user in additionalUsers)
                                    {
                                        grpAdditionalUsers.AddUser(user);
                                    }
                                    web.AllowUnsafeUpdates = false;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Utility.HandleException(ex, Controls);
                    }
                });
                siteIsProvisioning.End(_parentWebUrl + "/" + project.ProjectId);
            }
        }
        private void StatisticList(SPUser logUser)
        {
            string lstNames = WebPartObj.ListName;

            if (lstNames == "")
            {
                kpiDiv.InnerHtml = "尚未指定任何列表名称进行数据统计!";
            }
            else
            {
                string[]  lstName = WebPartObj.ListName.Split(';');
                SPQuery   oQuery;
                SPList    sList;
                int[]     itmCounts = new int[6];
                DataTable datatable = newTable();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                        {
                            string myac  = "";
                            string lName = "";
                            //设置sharepoint时间格式
                            SPTimeZone timeZone = web.RegionalSettings.TimeZone;
                            string listsHtml    = "<fieldset style='border: 1px dotted #ff4500; padding: 5px;'><legend style='text-align:center;background-color: #ff4500; color:#f5fffa;padding:5px'>活动量化明细表</legend><table class='mytable'>";
                            listsHtml          += "<tr><th rowspan='2'>KPI</th><th rowspan='2'>由我发布</th><th colspan='2'>今日更新</th><th colspan='2'>本周更新</th><th rowspan='2'>站内总数</th></tr>";
                            listsHtml          += "<tr><td>本人</td><td>本站</td><td>本人</td><td>本站</td></tr>";
                            itmCounts           = NewsCount;//微博
                            listsHtml          += "<tr>";
                            listsHtml          += "<th><a href='" + web.Url + "/newsfeed.aspx' target='_blank'>微 博</a></th>";
                            listsHtml          += "<td>" + itmCounts[0].ToString() + "</td>";
                            listsHtml          += "<td>" + itmCounts[2].ToString() + "</td>";
                            listsHtml          += "<td>" + itmCounts[3].ToString() + "</td>";
                            listsHtml          += "<td>" + itmCounts[4].ToString() + "</td>";
                            listsHtml          += "<td>" + itmCounts[5].ToString() + "</td>";
                            listsHtml          += "<td>" + itmCounts[1].ToString() + "</td>";
                            listsHtml          += "</tr>";
                            datatable.Rows.Add("微 博", itmCounts[0], itmCounts[1]);
                            if (itmCounts[4] == 0)
                            {
                                if (myac != "")
                                {
                                    myac += "、";
                                }
                                myac += "“<b><a href='" + SPContext.Current.Web.Url + "/newsfeed.aspx' target='_blank'>微 博</a></b>”";
                            }

                            foreach (string mList in lstName)
                            {
                                try
                                {
                                    if (mList == "Posts" && WebPartObj.SubWebUrl != "")//统计备忘录
                                    {
                                        SPWeb subWeb = web.Webs[WebPartObj.SubWebUrl];
                                        sList        = subWeb.Lists.TryGetList(mList);
                                    }
                                    else
                                    {
                                        sList = web.Lists.TryGetList(mList);
                                    }
                                    lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>" + mList + "</a>";


                                    if (mList == "Posts")
                                    {
                                        lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>备忘录</a>";
                                    }

                                    if (mList == "讨论列表")
                                    {
                                        lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>讨 论</a>";
                                    }
                                    if (mList == "文档")
                                    {
                                        lName = "<a href='" + sList.DefaultViewUrl + "' target='_blank'>文 档</a>";
                                    }

                                    oQuery = new SPQuery();
                                    oQuery.ViewAttributes         = "Scope='RecursiveAll'";
                                    oQuery.Query                  = "<Where><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq></Where>";
                                    SPListItemCollection lstItems = sList.GetItems(oQuery);
                                    itmCounts[0]                  = lstItems.Count;  //个人
                                    itmCounts[1]                  = sList.ItemCount; //全部

                                    /***********今日更新******************/
                                    oQuery = new SPQuery();
                                    DateTime currentDate          = DateTime.Now;
                                    DateTime yesterdayDate        = currentDate.AddDays(-1);
                                    DateTime yesterdayUTCDate     = timeZone.LocalTimeToUTC(yesterdayDate);
                                    string yesterdayUTCDateString = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(yesterdayUTCDate.ToString()));
                                    oQuery.ViewAttributes         = "Scope='RecursiveAll'";
                                    oQuery.Query = "<Where><And><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + yesterdayUTCDateString + "</Value></Geq></And></Where>";
                                    lstItems     = sList.GetItems(oQuery);
                                    itmCounts[2] = lstItems.Count;//个人当日更新

                                    oQuery = new SPQuery();
                                    oQuery.ViewAttributes = "Scope='RecursiveAll'";
                                    oQuery.Query          = "<Where><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + yesterdayUTCDateString + "</Value></Geq></Where>";
                                    lstItems     = sList.GetItems(oQuery);
                                    itmCounts[3] = lstItems.Count;//站内当日更新

                                    /***********本周更新******************/
                                    DateTime lastWeekDate        = currentDate.AddDays(-7);
                                    DateTime lastWeekUTCDate     = timeZone.LocalTimeToUTC(lastWeekDate);
                                    string lastWeekUTCDateString = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Parse(lastWeekUTCDate.ToString()));
                                    oQuery = new SPQuery();
                                    oQuery.ViewAttributes = "Scope='RecursiveAll'";
                                    oQuery.Query          = "<Where><And><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + lastWeekUTCDateString + "</Value></Geq></And></Where>";
                                    lstItems     = sList.GetItems(oQuery);
                                    itmCounts[4] = lstItems.Count;//个人本周更新

                                    oQuery = new SPQuery();
                                    oQuery.ViewAttributes = "Scope='RecursiveAll'";
                                    oQuery.Query          = "<Where><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + lastWeekUTCDateString + "</Value></Geq></Where>";
                                    lstItems     = sList.GetItems(oQuery);
                                    itmCounts[5] = lstItems.Count;//站内本周更新

                                    listsHtml += "<tr>";
                                    listsHtml += "<th>" + lName + "</th>";
                                    listsHtml += "<td>" + itmCounts[0].ToString() + "</td>";
                                    listsHtml += "<td>" + itmCounts[2].ToString() + "</td>";
                                    listsHtml += "<td>" + itmCounts[3].ToString() + "</td>";
                                    listsHtml += "<td>" + itmCounts[4].ToString() + "</td>";
                                    listsHtml += "<td>" + itmCounts[5].ToString() + "</td>";
                                    listsHtml += "<td>" + itmCounts[1].ToString() + "</td>";
                                    listsHtml += "</tr>";
                                    datatable.Rows.Add(lName, itmCounts[0], itmCounts[1]);
                                    if (itmCounts[4] == 0)
                                    {
                                        if (myac != "")
                                        {
                                            myac += "、";
                                        }
                                        myac += "“<b>" + lName + "</b>”";
                                    }
                                }
                                catch
                                { }
                            }

                            listsHtml += "</table></fieldset>";

                            if (myac != "")
                            {
                                listsHtml = "<div class='kpidiv'>亲,你好。<br/>系统发现你近一周都没有参与发布过:" + myac + ",<br/>快快参与站内活动赢取积分赶超其它小伙伴吧!</div>" + listsHtml;
                            }
                            kpiDiv.InnerHtml = listsHtml;
                            if (datatable.Rows.Count > 0)
                            {
                            }
                        }
                    }
                });
            }
        }
Ejemplo n.º 6
0
 //I Get DataTable information of target list (folder in sharepoint)
 private DataTable GetDataTable(string ListName, string Condition, string Sort)
 {
     try
     {
         SPSite    oSPsite;
         string    SharedPointSite = SPContext.Current.Site.Url;
         DataTable dt = new DataTable();
         SPSecurity.RunWithElevatedPrivileges(delegate
         {
             //I New sharepoint site object by current sharepoint site url
             using (oSPsite = new SPSite(SharedPointSite))
             {
                 //I New object sharepoint web by method open web
                 using (SPWeb oSPWeb = oSPsite.OpenWeb())
                 {
                     //I Unknow
                     oSPWeb.AllowUnsafeUpdates = true;
                     //I Get List information by target list name (folder in sharepoint)
                     SPList oList = oSPWeb.Lists[ListName];
                     //I New object of query for get target data from target list of sharepoint
                     //I Unused
                     SPQuery myquery = new SPQuery();
                     //I Maybe class of data type for get data from target list of sharepoint
                     SPListItemCollection ListSPListItem = oList.GetItems();
                     //I Maybe get item of target list to DataTable
                     dt = ListSPListItem.GetDataTable();
                     //I Check dataTable to null or empty
                     if (!DataTableIsNullOrEmpty(dt))
                     {
                         //I Maybe used for dummy dataTable for convert data in dataTable
                         DataView dv = new DataView();
                         //I Current condition to be "" (empty)
                         if (!string.IsNullOrEmpty(Condition.Trim()))
                         {
                             //I Incase condition valid
                             //I Unknow
                             dv           = dt.Copy().DefaultView;
                             dv.RowFilter = Condition;
                             dt           = dv.ToTable();
                         }
                         //I Check sorting
                         if (!string.IsNullOrEmpty(Sort.Trim()))
                         {
                             //I Incase sorting valid
                             dv      = dt.Copy().DefaultView;
                             dv.Sort = Sort;
                             dt      = dv.ToTable();
                         }
                     }
                     //I Unknow
                     oSPWeb.AllowUnsafeUpdates = false;
                 }
             }
         });
         //I Return dataTable
         return(dt);
     }
     catch (Exception)
     {
         return(null);
     }
 }
        protected void btnSaveNotification_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        site.CatchAccessDeniedException = false;
                        using (SPWeb currWeb = site.OpenWeb())
                        {
                            currWeb.AllowUnsafeUpdates = true;

                            //--EPML 1901
                            string sNotificationOptedOutUsers = string.Empty;
                            if (currWeb.Properties.ContainsKey("EPMLiveNotificationOptedOutUsers"))
                            {
                                sNotificationOptedOutUsers = currWeb.Properties["EPMLiveNotificationOptedOutUsers"];
                            }

                            string sCurrUser = SPContext.Current.Site.RootWeb.CurrentUser.ID + ";#" + SPContext.Current.Site.RootWeb.CurrentUser.Name;

                            ArrayList arrOptedOutUsers = new ArrayList(sNotificationOptedOutUsers.Split('|'));
                            bool found = false;
                            foreach (string user in arrOptedOutUsers)
                            {
                                string[] userinfo = user.Replace(";#", "\n").Split('\n');
                                if (userinfo[0] == SPContext.Current.Site.RootWeb.CurrentUser.ID.ToString())
                                {
                                    found = true;
                                }
                            }
                            if (chkTask.Checked)
                            {
                                if (found)
                                {
                                    arrOptedOutUsers.Remove(sCurrUser);
                                }
                                currWeb.Properties["EPMLiveNotificationOptedOutUsers"] = String.Join("|", (string[])arrOptedOutUsers.ToArray(typeof(string)));
                                currWeb.Properties.Update();
                            }
                            else
                            {
                                if (!found)
                                {
                                    arrOptedOutUsers.Add(sCurrUser);
                                }
                                currWeb.Properties["EPMLiveNotificationOptedOutUsers"] = String.Join("|", (string[])arrOptedOutUsers.ToArray(typeof(string)));
                                currWeb.Properties.Update();
                            }

                            //--End EPML 1901

                            //if (chkTask.Checked == true)
                            //{
                            //    ArrayList arrUsers = new ArrayList(sNotificationUsers.Split('|'));
                            //    bool found = false;
                            //    foreach (string user in arrUsers)
                            //    {
                            //        string[] userinfo = user.Replace(";#", "\n").Split('\n');
                            //        if (userinfo[0] == SPContext.Current.Site.RootWeb.CurrentUser.ID.ToString())
                            //            found = true;
                            //    }
                            //    if (!found)
                            //        arrUsers.Add(sCurrUser);

                            //    currWeb.Properties["EPMLiveNotificationUsers"] = String.Join("|", (string[])arrUsers.ToArray(typeof(string)));
                            //    currWeb.Properties.Update();
                            //}
                            //else
                            //{
                            //    ArrayList arrUsers = new ArrayList(sNotificationUsers.Split('|'));
                            //    ArrayList arrNewUsers = new ArrayList();
                            //    foreach (string user in arrUsers)
                            //    {
                            //        string[] userinfo = user.Replace(";#", "\n").Split('\n');
                            //        if (userinfo[0] != SPContext.Current.Site.RootWeb.CurrentUser.ID.ToString() && user != "")
                            //        {
                            //            arrNewUsers.Add(user);
                            //        }
                            //    }

                            //    currWeb.Properties["EPMLiveNotificationUsers"] = String.Join("|", (string[])arrNewUsers.ToArray(typeof(string)));
                            //    currWeb.Properties.Update();
                            //}
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
            }

            Response.Redirect(SPContext.Current.Web.ServerRelativeUrl);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string strAction = Request["action"];
            string period    = Request["period"];

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Expires = -1;

            data = "";

            string fEmail = SPContext.Current.Web.CurrentUser.Email;

            SPSite site = SPContext.Current.Site;
            //using ()
            {
                //using ()
                SPWeb web = SPContext.Current.Web;
                {
                    try
                    {
                        SqlConnection cn = null;
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            cn = new SqlConnection(EPMLiveCore.CoreFunctions.getConnectionString(site.WebApplication.Id));
                            cn.Open();

                            string requestedUser = Page.Request["duser"];

                            if (requestedUser != null && requestedUser != "")
                            {
                                if (SharedFunctions.canUserImpersonate(username, requestedUser, SPContext.Current.Site.RootWeb, out resName))
                                {
                                    username = requestedUser;
                                }
                                else
                                {
                                    impFailed = true;
                                }
                            }
                            bool.TryParse(EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSLiveHours"), out liveHours);
                        });
                        if (impFailed)
                        {
                            data = "Error: Impersonation Failed";
                        }
                        else
                        {
                            if (cn != null)
                            {
                                SqlCommand cmd;

                                int           iperiod;
                                SqlDataReader dr;

                                switch (strAction)
                                {
                                case "deleteTS":
                                    if (web.CurrentUser.IsSiteAdmin)
                                    {
                                        string[] tsuids = Request["ts_uids"].Split(',');
                                        foreach (string tsuidData in tsuids)
                                        {
                                            cmd = new SqlCommand("DELETE FROM TSTIMESHEET where ts_uid=@ts_uid", cn);
                                            cmd.Parameters.AddWithValue("@ts_uid", tsuidData);
                                            cmd.ExecuteNonQuery();
                                        }
                                        data = "Success";
                                    }
                                    else
                                    {
                                        data = "Error: Access Denied";
                                    }
                                    break;

                                case "closePeriod":
                                    cmd = new SqlCommand("update tsperiod set locked=1 where period_id=@periodid and site_id=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.Parameters.AddWithValue("@periodid", period);
                                    cmd.ExecuteNonQuery();
                                    data = period;
                                    break;

                                case "openPeriod":
                                    cmd = new SqlCommand("update tsperiod set locked=0 where period_id=@periodid and site_id=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.Parameters.AddWithValue("@periodid", period);
                                    cmd.ExecuteNonQuery();
                                    data = period;
                                    break;

                                case "submitTime":
                                    cmd = new SqlCommand("update TSTIMESHEET set submitted=1,approval_status=0,lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@ts_uid", cn);
                                    cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]);
                                    cmd.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName);
                                    cmd.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name);
                                    cmd.ExecuteNonQuery();
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        SPWeb tweb = SPContext.Current.Web;
                                        {
                                            SharedFunctions.processResources(cn, Request["ts_uid"], tweb, username);
                                        }
                                    });

                                    if (EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSDisableApprovals").ToLower() == "true")
                                    {
                                        approve(Request["ts_uid"], SPContext.Current.Web, Request["Period"]);
                                    }
                                    else
                                    {
                                        string actualWork = "";
                                        //SPSecurity.RunWithElevatedPrivileges(delegate()
                                        //{
                                        //    actualWork = EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSActualWork");
                                        //});
                                        //if (actualWork != "")
                                        //{
                                        if (!liveHours)
                                        {
                                            data = SharedFunctions.processActualWork(cn, Request["ts_uid"], site, false, true);
                                        }
                                        //}
                                    }

                                    if (data == "")
                                    {
                                        data = "Success";
                                    }

                                    cmd = new SqlCommand("select ts_item_uid,web_uid,list_uid,item_id,project from TSITEM where TS_UID=@ts_uid", cn);
                                    cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]);
                                    DataSet        ds = new DataSet();
                                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                                    da.Fill(ds);

                                    SPList pList    = null;
                                    SPWeb  iWeb     = null;
                                    SPList iList    = null;
                                    Guid   webGuid  = Guid.Empty;
                                    Guid   listGuid = Guid.Empty;

                                    foreach (DataRow dataRow in ds.Tables[0].Rows)
                                    {
                                        try
                                        {
                                            Guid wGuid = new Guid(dataRow["WEB_UID"].ToString());
                                            Guid lGuid = new Guid(dataRow["LIST_UID"].ToString());

                                            if (webGuid != wGuid)
                                            {
                                                if (iWeb != null)
                                                {
                                                    iWeb.Close();
                                                    iWeb = site.OpenWeb(wGuid);
                                                }
                                                else
                                                {
                                                    iWeb = site.OpenWeb(wGuid);
                                                }
                                                webGuid = iWeb.ID;
                                            }
                                            if (listGuid != lGuid)
                                            {
                                                iList = iWeb.Lists[lGuid];
                                                try
                                                {
                                                    pList = SharedFunctions.getProjectCenterList(iList);
                                                }
                                                catch { }
                                                listGuid = iList.ID;
                                            }
                                            SPListItem li = iList.GetItemById(int.Parse(dataRow["ITEM_ID"].ToString()));
                                            SharedFunctions.processMeta(iWeb, iList, li, new Guid(dataRow["ts_item_uid"].ToString()), dataRow["project"].ToString(), cn, pList);
                                        }
                                        catch { }
                                    }
                                    break;

                                case "unsubmitTime":
                                    cmd = new SqlCommand("update TSTIMESHEET set submitted=0,approval_status=0,lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@ts_uid", cn);
                                    cmd.Parameters.AddWithValue("@ts_uid", Request["ts_uid"]);
                                    cmd.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName);
                                    cmd.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name);
                                    cmd.ExecuteNonQuery();
                                    if (EPMLiveCore.CoreFunctions.getConfigSetting(SPContext.Current.Site.RootWeb, "EPMLiveTSDisableApprovals").ToLower() == "true" && !liveHours)
                                    {
                                        data = SharedFunctions.processActualWork(cn, Request["ts_uid"], site, true, true);
                                    }
                                    if (data == "")
                                    {
                                        data = "Success";
                                    }
                                    break;

                                case "deletePeriod":
                                    cmd = new SqlCommand("delete from tsperiod where period_id=@periodid and site_id=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.Parameters.AddWithValue("@periodid", period);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "addPeriod":
                                    cmd = new SqlCommand("select top 1 period_id from tsperiod where site_id=@siteid order by period_id desc", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    dr      = cmd.ExecuteReader();
                                    iperiod = 1;
                                    if (dr.Read())
                                    {
                                        iperiod = dr.GetInt32(0) + 1;
                                    }
                                    dr.Close();

                                    cmd = new SqlCommand("insert into tsperiod (period_start,period_end,period_id,site_id) values (@periodstart,@periodend,@period_id,@siteid)", cn);
                                    cmd.Parameters.AddWithValue("@periodstart", Request["start"]);
                                    cmd.Parameters.AddWithValue("@periodend", Request["end"]);
                                    cmd.Parameters.AddWithValue("@period_id", iperiod);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "addPeriods":
                                    var periods    = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(Request[JsonDataParameter]);
                                    var createdIds = CreatePeriods(cn, periods);
                                    data = string.Format("Success,{0},{1}", strAction, string.Join(",", createdIds));
                                    break;

                                case "addType":
                                    cmd = new SqlCommand("select top 1 tstype_id from tstype where site_uid=@siteid order by tstype_id desc", cn);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    dr      = cmd.ExecuteReader();
                                    iperiod = 1;
                                    if (dr.Read())
                                    {
                                        iperiod = dr.GetInt32(0) + 1;
                                    }
                                    dr.Close();

                                    cmd = new SqlCommand("insert into tstype (tstype_id,tstype_name,site_uid) values (@tstype_id,@tstype_name,@siteid)", cn);
                                    cmd.Parameters.AddWithValue("@tstype_name", Request["typename"]);
                                    cmd.Parameters.AddWithValue("@tstype_id", iperiod);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "editType":
                                    cmd = new SqlCommand("update tstype set tstype_name = @tstype_name where tstype_id=@tstype_id and site_uid=@siteid", cn);
                                    cmd.Parameters.AddWithValue("@tstype_name", Request["typename"]);
                                    cmd.Parameters.AddWithValue("@tstype_id", Request["typeid"]);
                                    cmd.Parameters.AddWithValue("@siteid", SPContext.Current.Site.ID);
                                    cmd.ExecuteNonQuery();
                                    data = "Success";
                                    break;

                                case "approveTS":
                                {
                                    approve(Request["ts_uids"].ToString(), SPContext.Current.Web, Request["Period"]);

                                    if (data == "")
                                    {
                                        data = "Success";
                                    }
                                }
                                break;

                                case "rejectTS":
                                {
                                    string[] tsuids = Request["ts_uids"].Split(',');
                                    foreach (string tsuidData in tsuids)
                                    {
                                        string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update TSTIMESHEET set approval_status=2,approval_notes=@notes where ts_uid=@ts_uid", cn);
                                        cmd.Parameters.AddWithValue("@ts_uid", tsuid[0]);
                                        cmd.Parameters.AddWithValue("@notes", tsuid[1]);
                                        cmd.ExecuteNonQuery();

                                        data += SharedFunctions.processActualWork(cn, tsuid[0], site, true, true);
                                    }

                                    if (data == "")
                                    {
                                        data = "Success";
                                    }
                                }
                                break;

                                case "unlockTS":
                                {
                                    string[] tsuids = Request["ts_uids"].Split(',');
                                    foreach (string tsuidData in tsuids)
                                    {
                                        string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update TSTIMESHEET set approval_status=0 where ts_uid=@ts_uid", cn);
                                        cmd.Parameters.AddWithValue("@ts_uid", tsuid[0]);
                                        cmd.ExecuteNonQuery();
                                    }
                                    data = "Success";
                                }
                                break;

                                case "rejectEmail":
                                {
                                    string[] tsuids = Request["ts_uids"].Split(',');
                                    foreach (string tsuid in tsuids)
                                    {
                                        cmd = new SqlCommand("select username,approval_notes,period_start,period_end from vwTSApprovalNotes where ts_uid=@ts_uid", cn);
                                        cmd.Parameters.AddWithValue("@ts_uid", tsuid);
                                        dr = cmd.ExecuteReader();
                                        if (dr.Read())
                                        {
                                            string username = dr.GetString(0);
                                            string notes    = dr.GetString(1);
                                            try
                                            {
                                                SPUser user = web.AllUsers[username];
                                                if (user.Email != "")
                                                {
                                                    System.Net.Mail.MailMessage mailMsg = new MailMessage();
                                                    mailMsg.From = new MailAddress(fEmail);
                                                    mailMsg.To.Add(new MailAddress(user.Email));
                                                    mailMsg.Subject      = web.Title + " Timesheet approval notice";
                                                    mailMsg.Body         = "Your timesheet for period (" + dr.GetDateTime(2).ToShortDateString() + " - " + dr.GetDateTime(3).ToShortDateString() + ") has been rejected:<br>" + notes;
                                                    mailMsg.IsBodyHtml   = true;
                                                    mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                                                    mailMsg.Priority     = MailPriority.Normal;

                                                    // Configure the mail server
                                                    SmtpClient smtpClient = new SmtpClient();
                                                    SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;
                                                    string sMailSvr = spWebAdmin.OutboundMailServiceInstance.Server.Name;
                                                    smtpClient.Host = sMailSvr;
                                                    smtpClient.Send(mailMsg);
                                                }
                                            }
                                            catch { }
                                        }
                                        dr.Close();
                                    }
                                }
                                    data = "Success";
                                    break;

                                case "autoadd":
                                    //string flagfield = "";
                                    string lists = "";
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        using (SPSite uSite = SPContext.Current.Site)
                                        {
                                            //flagfield = EPMLiveCore.CoreFunctions.getConfigSetting(uSite.RootWeb, "EPMLiveTSFlag");
                                            lists = EPMLiveCore.CoreFunctions.getConfigSetting(uSite.RootWeb, "EPMLiveTSLists");
                                        }
                                    });
                                    autoAdd(cn, Request["ts_uid"], web, lists);
                                    data = "Success";
                                    break;

                                case "approvePM":
                                {
                                    string[] tsitemuids = Request["tsitemuids"].Split(',');

                                    foreach (string tsitemuid in tsitemuids)
                                    {
                                        //string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update tsitem set approval_status=1 where ts_item_uid=@tsitemuid", cn);
                                        cmd.Parameters.AddWithValue("@tsitemuid", tsitemuid);
                                        cmd.ExecuteNonQuery();
                                    }
                                    data = "Success";
                                }
                                break;

                                case "rejectPM":
                                {
                                    string[] tsitemuids = Request["tsitemuids"].Split(',');

                                    foreach (string tsitemuid in tsitemuids)
                                    {
                                        //string[] tsuid = tsuidData.Split('|');
                                        cmd = new SqlCommand("update tsitem set approval_status=2 where ts_item_uid=@tsitemuid", cn);
                                        cmd.Parameters.AddWithValue("@tsitemuid", tsitemuid);
                                        cmd.ExecuteNonQuery();
                                    }
                                }
                                    data = "Success";
                                    break;

                                default:
                                    data = "Error: Invalid Command";
                                    break;
                                }
                                ;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        data = "Error: " + ex.Message;
                    }
                }
            }
        }
        private void autoAdd(SqlConnection cn, string tsuid, SPWeb web, string rolluplists)
        {
            SqlConnection cnwss = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite s = SPContext.Current.Site;
                {
                    string dbCon = s.ContentDatabase.DatabaseConnectionString;
                    cnwss        = new SqlConnection(dbCon);
                    cnwss.Open();
                }
            });
            if (cnwss.State == ConnectionState.Open)
            {
                string period  = Request["period"];
                string siteurl = web.ServerRelativeUrl.Substring(1);

                if (tsuid == null || tsuid == "")
                {
                    tsuid = Guid.NewGuid().ToString();
                    SqlCommand cmd1 = new SqlCommand("INSERT INTO TSTIMESHEET (TS_UID,USERNAME,PERIOD_ID,SITE_UID,resourcename) VALUES (@TS_UID,@USERNAME,@PERIOD_ID,@SITE_UID,@resourcename)", cn);
                    cmd1.Parameters.AddWithValue("@TS_UID", tsuid);
                    cmd1.Parameters.AddWithValue("@USERNAME", username);
                    cmd1.Parameters.AddWithValue("@resourcename", resName);
                    cmd1.Parameters.AddWithValue("@PERIOD_ID", period);
                    cmd1.Parameters.AddWithValue("@SITE_UID", web.Site.ID);
                    cmd1.ExecuteNonQuery();
                }

                SharedFunctions.processResources(cn, tsuid, web, username);

                SqlCommand cmd = new SqlCommand("SELECT period_start,period_end from TSPERIOD where site_id=@siteid and period_id=@period_id", cn);
                cmd.Parameters.AddWithValue("@siteid", web.Site.ID);
                cmd.Parameters.AddWithValue("@period_id", period);
                SqlDataReader dr = cmd.ExecuteReader();
                dr.Read();
                DateTime pstart = dr.GetDateTime(0);
                DateTime pend   = dr.GetDateTime(1);
                dr.Close();

                foreach (string rlist in rolluplists.Replace("\r\n", "\n").Split('\n'))
                {
                    string lists = "";
                    string query = "";
                    if (siteurl == "")
                    {
                        query = "SELECT     dbo.AllLists.tp_ID FROM         dbo.Webs INNER JOIN dbo.AllLists ON dbo.Webs.Id = dbo.AllLists.tp_WebId WHERE     (dbo.Webs.FullUrl LIKE '" + siteurl + "%' OR dbo.Webs.FullUrl = '" + siteurl + "') AND (dbo.AllLists.tp_Title like '" + rlist.Replace("'", "''") + "')";
                    }
                    else
                    {
                        query = "SELECT     dbo.AllLists.tp_ID FROM         dbo.Webs INNER JOIN dbo.AllLists ON dbo.Webs.Id = dbo.AllLists.tp_WebId WHERE     (dbo.Webs.FullUrl LIKE '" + siteurl + "/%' OR dbo.Webs.FullUrl = '" + siteurl + "') AND (dbo.AllLists.tp_Title like '" + rlist.Replace("'", "''") + "')";
                    }


                    cmd = new SqlCommand(query, cnwss);

                    dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        lists += "<List ID='" + dr.GetGuid(0).ToString() + "'/>";
                    }
                    dr.Close();

                    if (lists != "")
                    {
                        SPUser u = web.Site.RootWeb.AllUsers[username];

                        SPSiteDataQuery dq = new SPSiteDataQuery();
                        dq.ViewFields = "<FieldRef Name='Title' Nullable='TRUE'/><FieldRef Name='Project' Nullable='TRUE'/>";
                        dq.Webs       = "<Webs Scope='Recursive'/>";
                        dq.Lists      = "<Lists>" + lists + "</Lists>";
                        dq.Query      = "<Where><And><And><And><Eq><FieldRef Name=\"AssignedTo\"  LookupId='True'/><Value Type=\"User\">" + u.ID.ToString() + "</Value></Eq><Eq><FieldRef Name=\"Timesheet\" /><Value Type=\"Boolean\">1</Value></Eq></And><Geq><FieldRef Name=\"DueDate\" /><Value Type=\"DateTime\">" + pstart.ToString("u") + "</Value></Geq></And><Leq><FieldRef Name=\"StartDate\" /><Value Type=\"DateTime\">" + pend.ToString("u") + "</Value></Leq></And></Where>";

                        DataTable dt = web.GetSiteData(dq);

                        Guid   webGuid  = new Guid();
                        Guid   listGuid = new Guid();
                        SPWeb  iWeb     = null;
                        SPSite iSite    = web.Site;
                        SPList iList    = null;
                        SPList pList    = null;


                        foreach (DataRow dRow in dt.Rows)
                        {
                            cmd = new SqlCommand("SELECT * FROM TSITEM where WEB_UID=@web_uid and LIST_UID = @list_uid and item_id=@item_id and ts_uid=@ts_uid", cn);
                            cmd.Parameters.AddWithValue("@WEB_UID", dRow["WEBID"]);
                            cmd.Parameters.AddWithValue("@LIST_UID", dRow["LISTID"]);
                            cmd.Parameters.AddWithValue("@ITEM_ID", dRow["ID"]);
                            cmd.Parameters.AddWithValue("@ts_uid", tsuid);
                            dr = cmd.ExecuteReader();
                            bool found = false;
                            if (dr.Read())
                            {
                                found = true;
                            }
                            dr.Close();

                            if (!found)
                            {
                                Guid wGuid = new Guid(dRow["WEBID"].ToString());
                                Guid lGuid = new Guid(dRow["LISTID"].ToString());

                                if (webGuid != wGuid)
                                {
                                    pList = null;
                                    if (iWeb != null)
                                    {
                                        iWeb.Close();
                                        iWeb = iSite.OpenWeb(wGuid);
                                    }
                                    else
                                    {
                                        iWeb = iSite.OpenWeb(wGuid);
                                    }
                                    webGuid = iWeb.ID;
                                }
                                if (listGuid != lGuid)
                                {
                                    iList    = iWeb.Lists[lGuid];
                                    pList    = pList = SharedFunctions.getProjectCenterList(iList);
                                    listGuid = iList.ID;
                                }

                                SPListItem li         = iList.GetItemById(int.Parse(dRow["ID"].ToString()));
                                string     project    = "";
                                string     project_id = "";
                                try
                                {
                                    //project = iList.Fields["Project"].GetFieldValueAsText(dRow["Project"].ToString());

                                    try
                                    {
                                        SPFieldLookupValue lv = new SPFieldLookupValue(li["Project"].ToString());
                                        project    = lv.LookupValue;
                                        project_id = lv.LookupId.ToString();
                                        if (project == null)
                                        {
                                            project    = "";
                                            project_id = "0";
                                        }
                                    }
                                    catch { }
                                }
                                catch { }
                                Guid newTS = Guid.NewGuid();

                                cmd = new SqlCommand("INSERT INTO TSITEM (TS_UID,TS_ITEM_UID,WEB_UID,LIST_UID,ITEM_TYPE,ITEM_ID,TITLE,PROJECT,LIST,PROJECT_ID,PROJECT_LIST_UID) VALUES (@TS_UID,@TS_ITEM_UID,@WEB_UID,@LIST_UID,@ITEM_TYPE,@ITEM_ID,@TITLE,@PROJECT,@LIST,@PROJECT_ID,@projectlistuid)", cn);
                                cmd.Parameters.AddWithValue("@TS_UID", tsuid);
                                cmd.Parameters.AddWithValue("@TS_ITEM_UID", newTS);
                                cmd.Parameters.AddWithValue("@WEB_UID", dRow["WEBID"].ToString());
                                cmd.Parameters.AddWithValue("@LIST_UID", dRow["LISTID"].ToString());
                                cmd.Parameters.AddWithValue("@ITEM_TYPE", 1);
                                cmd.Parameters.AddWithValue("@ITEM_ID", dRow["ID"].ToString());
                                cmd.Parameters.AddWithValue("@TITLE", dRow["Title"].ToString());
                                cmd.Parameters.AddWithValue("@PROJECT", project);
                                cmd.Parameters.AddWithValue("@PROJECT_ID", project_id);
                                cmd.Parameters.AddWithValue("@LIST", rlist);
                                if (pList != null)
                                {
                                    cmd.Parameters.AddWithValue("@projectlistuid", pList.ID);
                                }
                                else
                                {
                                    cmd.Parameters.AddWithValue("@projectlistuid", DBNull.Value);
                                }
                                cmd.ExecuteNonQuery();

                                SharedFunctions.processMeta(iWeb, iList, li, newTS, project, cn, pList);

                                //processMeta(cn, iWeb, iList, li, newTS, project, pList);
                            }
                        }
                    }
                }
                SqlCommand cmd2 = new SqlCommand("UPDATE TSTIMESHEET set lastmodifiedbyu=@u,lastmodifiedbyn=@n where ts_uid=@TS_UID", cn);
                cmd2.Parameters.AddWithValue("@TS_UID", tsuid);
                cmd2.Parameters.AddWithValue("@u", SPContext.Current.Web.CurrentUser.LoginName);
                cmd2.Parameters.AddWithValue("@n", SPContext.Current.Web.CurrentUser.Name);
                cmd2.ExecuteNonQuery();
                cnwss.Close();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="docLibName">Name of the document library.</param>
        /// <param name="fUpload">The fupload.</param>
        /// <param name="viewStateName">Name of the view state.</param>
        /// <param name="gv">The GridView.</param>
        /// <param name="type">The type.</param>
        private void AddWorkFile(SPWeb web, string docLibName, FileUpload fUpload, String viewStateName, GridView gv, int type)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite elevatedsiteColl = new SPSite(MySite.ID))
                    {
                        using (SPWeb elevatedSite = elevatedsiteColl.OpenWeb(MyWeb.ID))
                        {
                            string urlStr = elevatedSite.Url;
                            elevatedSite.AllowUnsafeUpdates = true;
                            SPList list = elevatedSite.Lists.TryGetList(docLibName);
                            //如果没有文档库,生成文档库
                            if (list == null)
                            {
                                list   = ProjectDll.DAL.ProjectFileDAL.CreateList(docLibName);
                                urlStr = urlStr + "\\" + docLibName;
                            }
                            var docLib = (SPDocumentLibrary)list;
                            if (fUpload.HasFile)
                            {
                                //数据库

                                //判断是否存在
                                if (JudgeSize(fUpload.PostedFile.ContentLength))//判断文件大小是否超出限制
                                {
                                    ProjectDll.DAL.Common.ShowMessage(this.Page, this.GetType(), "超出上传文档大小限制!");
                                }
                                else
                                {
                                    string fname = type.ToString().PadLeft(2, '0') + DateTime.Now.Year + ddlSubjectC.SelectedValue.PadLeft(4, '0') + "-" + ProjectDll.BLL.User.GetAccount() + "-" + Path.GetFileName(fUpload.PostedFile.FileName);
                                    Stream stm   = fUpload.PostedFile.InputStream;
                                    int iLength  = (int)stm.Length;
                                    if (iLength > 0)
                                    {
                                        SPFolder rootFolder = docLib.RootFolder;
                                        Byte[] filecontent  = new byte[iLength];
                                        stm.Read(filecontent, 0, iLength);
                                        try
                                        {
                                            SPFile f;
                                            //如果在文档库中有,删除文档库中同名文档后,上传文档
                                            bool isDocHave = false;
                                            isDocHave      = ProjectDll.DAL.ProjectFileDAL.JudgeIsExistInDocLib(docLib, fname, type);

                                            proj_ProjectFile pFile = ProjectDll.DAL.ProjectFileDAL.JudgeIsExistInDb(fname, currentUserId);
                                            //判断文档库
                                            if (isDocHave)
                                            {
                                                ProjectDll.DAL.Common.ShowMessage(this.Page, this.GetType(), "请注意,该文件已存在,上传后自动覆盖已有文件!");
                                                DelList(fname, type.ToString());
                                                f = rootFolder.Files.Add(fname, filecontent, true);
                                            }
                                            else
                                            {
                                                f = rootFolder.Files.Add(fname, filecontent, true);
                                            }
                                            urlStr += "\\" + fname;

                                            ////判断数据库
                                            //if (isDBHave)
                                            //{
                                            //    //如果数据库中有,更新数据库
                                            //}
                                            //else
                                            //{
                                            //    //如果没有插入数据库

                                            //    //数据库

                                            //}
                                        }
                                        catch (Exception ex)
                                        {
                                            ProjectDll.DAL.Common.Alert(ex.ToString());
                                        }
                                        finally
                                        {
                                            stm.Close();
                                        }
                                    }
                                }
                            }
                            elevatedSite.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ProjectDll.DAL.Common.Alert(ex.ToString());
                // DAL.Common.ShowMessage(this.Page, this.GetType(), "出错了,请报告给管理员!");
            }
            finally
            {
            }
            //BindGridView((DataTable)ViewState[viewStateName], gv);
        }
        /// Returns true if the correct version of the file exists in SharePoint.
        /// NOTE: This method checks file availability using elevated privileges. Be
        /// cautious when using this information in messages displayed to the user.
        private static bool FileExistsInSharePoint(string location)
        {
            SharePointFileLocation spFileLocation;
            bool fileExists = true;    // assume it exists

            if (SharePointFileLocation.TryParse(location, out spFileLocation))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // If the site does not exist, this throws FileNotFound
                    using (SPSite spSite = new SPSite(spFileLocation.SiteId, SPContext.Current.Site.Zone))
                    {
                        // If the web does not exist, this throws FileNotFound
                        using (SPWeb spWeb = spSite.OpenWeb(spFileLocation.WebId))
                        {
                            SPFile spFile = spWeb.GetFile(spFileLocation.FileId);
                            if (!spFile.Exists)
                            {
                                fileExists = false;
                                return;
                            }
                            // The file exists. Now check if the right version exists.
                            DateTime lastModified;
                            if ((spFile.Versions.Count == 0) || spFile.UIVersion == spFileLocation.VersionId)
                            {
                                // The requested version is the currect one
                                if (spFile.UIVersion != spFileLocation.VersionId)
                                {
                                    fileExists = false;
                                    return;
                                }
                                // It exists: check its timestamp
                                lastModified = spFile.TimeLastModified;
                            }
                            else
                            {
                                // The specified version isn't the current one
                                SPFileVersion spFileVersion = spFile.Versions.GetVersionFromID(spFileLocation.VersionId);

                                if (spFileVersion == null)
                                {
                                    fileExists = false;
                                    return;
                                }

                                // There is no 'last modified' of a version, so use the time the version was created.
                                lastModified = spFileVersion.Created;
                            }

                            // If the timestamps are not the same, the file has been modified, so return false
                            if (lastModified.CompareTo(spFileLocation.Timestamp) != 0)
                            {
                                fileExists = false;
                                return;
                            }
                        }
                    }
                });
            }
            return(fileExists);
        }
Ejemplo n.º 12
0
        //static readonly SPUser currentUser = SPContext.Current.Web.CurrentUser;
        //static readonly string loginName = currentUser.LoginName;
        //readonly string currentAccount = loginName.Substring(loginName.IndexOf('\\') + 1);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InitControl();

                SPUser currentUser = SPContext.Current.Web.CurrentUser;
                string loginName   = currentUser.LoginName;
                loginName = loginName.Substring(loginName.IndexOf('\\') + 1);

                string  account = loginName.Replace(@"i:0#.w|", "");
                DataSet ds      = DAL.User.GetUserByAccount(account);
                if (ds.Tables[0].Rows.Count > 0) //数据库中已有该账户信息,则直接从数据库中读取
                {
                    DataRow dr = ds.Tables[0].Rows[0];
                    //string[] drcolStrings = drRow..ToString();
                    lbName.Text  = dr["Name"].ToString();
                    txtName.Text = dr["Name"].ToString();

                    lbID.Text  = dr["IDCard"].ToString();
                    txtId.Text = dr["IDCard"].ToString();

                    if (dr["Sex"].ToString() == "True")
                    {
                        lbSex.Text = "男";
                    }
                    else if (dr["Sex"].ToString() == "False")
                    {
                        lbSex.Text = "女";
                    }
                    if (dr["SchoolID"].ToString() != "")
                    {
                        int     sId = int.Parse(dr["SchoolID"].ToString());
                        DataSet sds = DAL.User.GetSchoolById(sId);
                        if (sds.Tables[0].Rows.Count > 0)
                        {
                            lbSchool.Text = sds.Tables[0].Rows[0]["SchoolName"].ToString();
                        }
                    }
                    lbPhone.Text      = dr["Telephone"].ToString();
                    txtTelephone.Text = dr["Telephone"].ToString();
                    lbEmail.Text      = dr["Email"].ToString();
                    txtEmail.Text     = dr["Email"].ToString();
                }
                else //该用户信息只在AD中存在,用户信息从AD中读取
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        DirectoryEntry adUser = ADHelper.GetDirectoryEntryByAccount(account);
                        if (adUser != null)
                        {
                            txtName.Text = adUser.Properties["displayName"][0].ToString();
                            if (adUser.Properties.Contains("telephoneNumber"))
                            {
                                txtTelephone.Text = adUser.Properties["telephoneNumber"][0].ToString();
                            }
                            if (adUser.Properties.Contains("mail"))
                            {
                                txtEmail.Text = adUser.Properties["mail"][0].ToString();
                            }
                        }
                    });
                }
            }
            btnSave.Click += btnSave_Click;
            ddlProvince.SelectedIndexChanged += ddlProvince_SelectedIndexChanged;
            ddlCity.SelectedIndexChanged     += ddlCity_SelectedIndexChanged;
        }
Ejemplo n.º 13
0
 public static void RunWithElevatedPrivileges(SPSecurity.CodeToRunElevated codeToRunElevated)
 {
     RunWithoutAccessDenied(() => SPSecurity.RunWithElevatedPrivileges(codeToRunElevated));
 }
Ejemplo n.º 14
0
        protected void GetConnSettings()
        {
            try
            {
                txtConnString.Text = "";
                SPWebApplication webApp = WebApplicationSelector1.CurrentItem;
                webappid = webApp.Id.ToString();
                string sConn = CoreFunctions.getConnectionString(webApp.Id);

                if (!string.IsNullOrWhiteSpace(sConn))
                {
                    txtConnString.Text = sConn;
                    lblStatusDyn.Text  = "Active";

                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        try
                        {
                            var curVersion = "";
                            using (var cn = new SqlConnection(sConn))
                            {
                                cn.Open();
                                using (var cmd = new SqlCommand("SELECT TOP 1 VERSION FROM VERSIONS order by dtInstalled DESC", cn))
                                {
                                    using (var dr = cmd.ExecuteReader())
                                    {
                                        if (dr.Read())
                                        {
                                            curVersion = dr.GetString(0);
                                        }
                                    }
                                }
                            }

                            lblVersion.Text = curVersion;
                            if (curVersion != CoreFunctions.GetFullAssemblyVersion())
                            {
                                btnUpgrade.Visible   = true;
                                lblVersion.BackColor = Color.Red;
                            }
                        }
                        catch (Exception ex)
                        {
                            lblStatusDyn.Text = "Error: " + ex.Message;
                        }
                    });
                }
                else
                {
                    lblStatusDyn.Text    = "No connection string configured.";
                    con1.Visible         = false;
                    con3.Visible         = false;
                    btnInstallDB.Visible = true;
                }

                ReportAuth _chrono = webApp.GetChild <ReportAuth>("ReportAuth");
                if (_chrono != null)
                {
                    txtUsername.Text = _chrono.Username;
                }

                if (SPFarm.Local.Solutions[new Guid("55aca119-d7c7-494a-b5a7-c3ade07d06eb")].DeployedWebApplications.Contains(webApp))
                {
                    sCoreStatus = "Deployed";
                }
                else
                {
                    sCoreStatus = "Not Deployed";
                }

                if (SPFarm.Local.Solutions[new Guid("98e5c373-e1a0-45ce-8124-30c203cd8003")].DeployedWebApplications.Contains(webApp))
                {
                    sWPStatus = "Deployed";
                }
                else
                {
                    sWPStatus = "Not Deployed";
                }

                if (SPFarm.Local.Solutions[new Guid("1858d521-0375-4a61-9281-f5210854bc12")].DeployedWebApplications.Contains(webApp))
                {
                    sTSStatus = "Deployed";
                }
                else
                {
                    sTSStatus = "Not Deployed";
                }

                if (SPFarm.Local.Solutions[new Guid("8f916fa9-1c2d-4416-8036-4a272256e23d")].DeployedWebApplications.Contains(webApp))
                {
                    sDashboardStatus = "Deployed";
                }
                else
                {
                    sDashboardStatus = "Not Deployed";
                }

                if (SPFarm.Local.Solutions[new Guid("5a3fe24c-2dc5-4a1c-aec1-6ce942825ceb")].DeployedWebApplications.Contains(webApp))
                {
                    sPFEStatus = "Deployed";
                }
                else
                {
                    sPFEStatus = "Not Deployed";
                }
            }
            catch (Exception exception)
            {
                lblStatusDyn.Text      = "Error: " + exception.Message;
                lblStatusDyn.BackColor = System.Drawing.Color.Red;
            }


            try
            {
                txtReportServer.Text   = CoreFunctions.getWebAppSetting(new Guid(WebApplicationSelector1.CurrentId), "ReportingServicesURL");
                txtDefaultPath.Text    = CoreFunctions.getWebAppSetting(new Guid(WebApplicationSelector1.CurrentId), "ReportsRootFolder");
                chkIntegrated.Checked  = bool.Parse(CoreFunctions.getWebAppSetting(new Guid(WebApplicationSelector1.CurrentId), "ReportsUseIntegrated"));
                chkWindowsAuth.Checked = bool.Parse(CoreFunctions.getWebAppSetting(new Guid(WebApplicationSelector1.CurrentId), "ReportsWindowsAuthentication"));
            }
            catch { }
        }
Ejemplo n.º 15
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            strSent = "";

            string emails = hdnEmails.Value;
            string names  = hdnNames.Value;

            SPWeb web = SPContext.Current.Web;

            {
                string fromEmail = web.CurrentUser.Email;
                if (fromEmail == "")
                {
                    fromEmail = "*****@*****.**";
                }

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    // Mail server objects
                    SmtpClient smtpClient = new SmtpClient();
                    SPAdministrationWebApplication spWebAdmin = Microsoft.SharePoint.Administration.SPAdministrationWebApplication.Local;

                    string[] semails = emails.Split(',');
                    string[] snames  = names.Split(',');

                    string body = txtBody.Text + "<br><br>Go To Site: <a href=\"" + web.Url + "\">" + web.Title + "</a>";

                    if (spWebAdmin.OutboundMailServiceInstance != null)
                    {
                        for (int i = 0; i < semails.Length; i++)
                        {
                            if (semails[i] != "")
                            {
                                try
                                {
                                    System.Net.Mail.MailMessage mailMsg = new MailMessage();
                                    mailMsg.From = new MailAddress(spWebAdmin.OutboundMailSenderAddress, web.CurrentUser.Name);
                                    mailMsg.To.Add(new MailAddress(semails[i]));
                                    mailMsg.Subject      = txtSubject.Text;
                                    mailMsg.Body         = body;
                                    mailMsg.IsBodyHtml   = true;
                                    mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                                    mailMsg.Priority     = MailPriority.Normal;

                                    //Email Sent process.
                                    string sMailSvr = spWebAdmin.OutboundMailServiceInstance.Server.Name;
                                    smtpClient.Host = sMailSvr;
                                    smtpClient.Send(mailMsg);
                                    strSent += snames[i] + " (" + semails[i] + ")...Success<br>";
                                }
                                catch (Exception ex)
                                {
                                    strSent += "<font color=\"red\">" + snames[i] + " (" + semails[i] + ")...Failed: " + ex.Message + "</font><br>";
                                }
                            }
                        }
                    }
                    else
                    {
                        strSent = "<font color=\"red\"> Email Failure: Outbound Email service is not configured on this server, please contact your System Administrator. </font><br>";
                    }
                });
            }

            pnlMain.Visible = false;
            pnlSent.Visible = true;
        }
Ejemplo n.º 16
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                ClubCloud.Common.RemoteAdministrator.Enable();

                //using (new SPMonitoredScope("Common Feature Cleaning"))
                //{
                //    FeatureCleaning(properties);
                //    SetCustomPages(properties);
                //}

                configurationproperties = properties.Feature.Properties;
                if (properties.Feature.Parent.GetType() == typeof(SPWebApplication))
                {
                    webApp = properties.Feature.Parent as SPWebApplication;
                    SPWebApplication wap = SPWebService.ContentService.WebApplications[webApp.Id];

                    List <SPWebConfigModification> process = new List <SPWebConfigModification>();
                    process.AddRange(ClubCloud.Common.Common.Modifications);
                    //process.AddRange(Syncfusion.Modifications);
                    process.AddRange(Ajax.Modifications);
                    //process.AddRange(CrossSiteScripting.Modifications);

                    foreach (SPWebConfigModification mod in process)
                    {
                        using (new SPMonitoredScope("Common Feature Activated"))
                        {
                            try
                            {
                                if (!wap.WebConfigModifications.Contains(mod))
                                {
                                    wap.WebConfigModifications.Add(mod);
                                }

                                if (!SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Contains(mod))
                                {
                                    SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Add(mod);
                                }
                            }
                            catch (Exception ex)
                            {
                                diagSvc.WriteEvent(0,
                                                   new SPDiagnosticsCategory("ClubCloud", TraceSeverity.Monitorable, EventSeverity.Warning),
                                                   EventSeverity.Error,
                                                   "Exception occured {0}", new object[] { ex });
                            }
                        }
                    }
                    using (new SPMonitoredScope("Common Feature Activated"))
                    {
                        try
                        {
                            wap.Update(false);
                            SPWebService.ContentService.WebApplications[wap.Id].Update(false);
                            SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                            //webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                            wap.WebConfigModifications.Clear();
                            wap.Update(false);
                        }
                        catch (Exception ex)
                        {
                            diagSvc.WriteEvent(0,
                                               new SPDiagnosticsCategory("ClubCloud", TraceSeverity.Monitorable, EventSeverity.Warning),
                                               EventSeverity.Error,
                                               "Exception occured {0}", new object[] { ex });
                        }
                    }
                }
            });
        }
Ejemplo n.º 17
0
        //I Get data in format DataTable for navigation bar
        private DataTable GetDataNavigation()
        {
            #region     Unused statement

            //I Class site of sharepoint
            SPSite oSPsite;
            //I Object of data for return
            DataTable dt_group = new DataTable();
            //I Setting column
            dt_group.Columns.Add("GroupID");
            dt_group.Columns.Add("GroupName");
            //I Url of sharepoint site

            //I Unknow statement
            //I Get group id block
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                string SharedPointSite = SPContext.Current.Site.Url;
                //I New object of sharepoint site
                using (oSPsite = new SPSite(SharedPointSite))
                {
                    //I Maybe open target web site
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        //I Unknow
                        for (int i = 0; i < oSPWeb.Groups.Count; i++)
                        {
                            SPGroup Group = oSPWeb.Groups[i];
                            dt_group.Rows.Add(Group.ID, Group.Name);
                        }
                    }
                }
            });
            //I Maybe string for keep group id of current user
            string filter = string.Empty;
            //I Get row in any group
            foreach (DataRow dr_group in dt_group.Rows)
            {
                //I Check current user to be member of group in current row
                if (IsMemberOfGroup(dr_group["GroupName"].ToString(), GetLogOnName()))
                {
                    //I Assign group id to filter string
                    filter += string.Format("'{0}',", dr_group["GroupID"].ToString());
                }
            }
            //I Remove last comma in case filter valid
            if (!string.IsNullOrEmpty(filter))
            {
                filter = filter.Remove(filter.Length - 1, 1);
            }

            #endregion  Unused statement

            #region   Used for get data
            //I Get information in format DataTable of target list of sharepoint
            DataTable dt = GetDataTable("Navigation", "", "Sequence ASC");
            //I Check empty
            if (!DataTableIsNullOrEmpty(dt))
            {
                //I Maybe forming DataTable to target column
                dt = dt.Copy().DefaultView.ToTable(true, new string[] { "NodeID", "ParentNodeID", "Title", "Url", "Level",
                                                                        "AudienceName", "Sequence", "AudienceID" });
            }
            //I Return result
            return(dt);

            #endregion
        }
Ejemplo n.º 18
0
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                ClubCloud.Common.RemoteAdministrator.Enable();

                //FeatureCleaning(properties);
                configurationproperties = properties.Feature.Properties;
                if (properties.Feature.Parent.GetType() == typeof(SPWebApplication))
                {
                    webApp = properties.Feature.Parent as SPWebApplication;
                    SPWebApplication wap = SPWebService.ContentService.WebApplications[webApp.Id];

                    List <SPWebConfigModification> process = new List <SPWebConfigModification>();
                    process.AddRange(ClubCloud.Common.Common.Modifications);
                    //process.AddRange(Syncfusion.Modifications);
                    process.AddRange(Ajax.Modifications);
                    //process.AddRange(CrossSiteScripting.Modifications);

                    foreach (SPWebConfigModification mod in process)
                    {
                        using (new SPMonitoredScope("Common Feature Deactivating"))
                        {
                            try
                            {
                                if (wap.WebConfigModifications.Contains(mod))
                                {
                                    wap.WebConfigModifications.Remove(mod);
                                }

                                if (SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Contains(mod))
                                {
                                    SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Remove(mod);
                                }
                            }
                            catch (Exception ex)
                            {
                                diagSvc.WriteEvent(0,
                                                   new SPDiagnosticsCategory("ClubCloud", TraceSeverity.Monitorable, EventSeverity.Warning),
                                                   EventSeverity.Error,
                                                   "Exception occured {0}", new object[] { ex });
                            }
                        }
                    }
                    using (new SPMonitoredScope("Common Feature Deactivating"))
                    {
                        try
                        {
                            wap.Update(false);
                            SPWebService.ContentService.WebApplications[wap.Id].Update(false);
                            SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                            //webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                            wap.WebConfigModifications.Clear();
                            wap.Update();
                        }
                        catch (Exception ex)
                        {
                            diagSvc.WriteEvent(0,
                                               new SPDiagnosticsCategory("ClubCloud", TraceSeverity.Monitorable, EventSeverity.Warning),
                                               EventSeverity.Error,
                                               "Exception occured {0}", new object[] { ex });
                        }
                    }

                    //FeatureUninstalling(properties);
                    //List<SPWebConfigModification> toDelete = new List<SPWebConfigModification>();

                    /*
                     * foreach (SPWebConfigModification mod in webApp.WebConfigModifications)
                     * {
                     *  string name = mod.Name;
                     *  string owner = mod.Owner;
                     *  string path = mod.Path;
                     *  Microsoft.SharePoint.Administration.SPWebConfigModification.SPWebConfigModificationType type = mod.Type;
                     *  string value = mod.Value;
                     *
                     *  if (mod.Name == "ClubCloudSaveControls")
                     *  {
                     *      mod.Name = "SafeControl[@Assembly='ClubCloud.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=144fd205e283172e'][@Namespace='ClubCloud.Common.Controls'][@TypeName='*'][@Safe='True'][SafeAgainstScript='True']";
                     *      mod.Value = "<SafeControl Assembly='ClubCloud.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=144fd205e283172e' Namespace='ClubCloud.Common.Controls' TypeName='*' Safe='True' SafeAgainstScript='True' />";
                     *
                     *      //toDelete.Add(mod);
                     *  }
                     *
                     * }
                     */
                    /*
                     * foreach (SPWebApplication wap in SPWebService.ContentService.WebApplications)
                     * {
                     *  List<SPWebConfigModification> toDelete = new List<SPWebConfigModification>();
                     *  try
                     *  {
                     *      Debug.Write(wap.Name);
                     *      //Console.WriteLine(wap.Name);
                     *      //Console.WriteLine("==========================================================");
                     *      foreach (SPWebConfigModification mod in wap.WebConfigModifications)
                     *      {
                     *          string name = mod.Name;
                     *          string owner = mod.Owner;
                     *          string path = mod.Path;
                     *          Microsoft.SharePoint.Administration.SPWebConfigModification.SPWebConfigModificationType type = mod.Type;
                     *          string value = mod.Value;
                     *
                     *          //Console.WriteLine(mod.ToString());
                     *          Debug.Write(mod.ToString());
                     *          if (mod.Owner.Contains("ClubCloud") || mod.Owner.Contains("Syncfusion") || mod.Owner.Contains("ajax") || mod.Owner.Contains("Ajax")) // == "ClubCloudCommonSaveControls" || mod.Owner == "ClubCloudCommonControls")
                     *          {
                     *              toDelete.Add(mod);
                     *          }
                     *      }
                     *
                     *      foreach (SPWebConfigModification mod in toDelete)
                     *      {
                     *              wap.WebConfigModifications.Remove(mod);
                     *              SPWebService.ContentService.WebApplications[wap.Id].WebConfigModifications.Remove(mod);
                     *      }
                     *
                     *      SPWebService.ContentService.WebApplications[wap.Id].Update();
                     *      SPWebService.ContentService.WebApplications[wap.Id].WebService.ApplyWebConfigModifications();
                     *
                     *
                     *      Console.WriteLine("==========================================================");
                     *
                     *  }
                     *  catch(Exception ex)
                     *  {
                     *      Debug.Write(ex.ToString());
                     *  }
                     *
                     * }
                     */
                    /*
                     * foreach (SPWebConfigModification mod in toDelete)
                     * {
                     *
                     *  webApp.WebConfigModifications.Remove(mod);
                     *  SPWebService.ContentService.WebApplications[webApp.Id].WebConfigModifications.Remove(mod);
                     * }
                     */
                    /*
                     * try
                     * {
                     *  webApp.Update();
                     *  SPWebService.ContentService.WebApplications[webApp.Id].Update();
                     *  SPWebService.ContentService.WebApplications[webApp.Id].WebService.ApplyWebConfigModifications();
                     * }
                     * catch { };
                     */
                }
            });
        }
Ejemplo n.º 19
0
        //I Get all group from user name
        private DataTable GetGroupByUserNameAndDomainName()
        {
            DataTable dtReturn = new DataTable();

            dtReturn.Columns.Add("Name");
            dtReturn.Columns.Add("ID");
            try
            {
                #region  " Get and validate data "

                string Uname      = GetLogOnName();
                string DomainName = GetDomainName();

                #region  " Validate current domain and user name "
                if (Uname == null)
                {
                    //I Error
                    return(null);
                }
                if (Uname.Trim().Equals(""))
                {
                    //I Error
                    return(null);
                }
                if (DomainName == null)
                {
                    //I Error
                    return(null);
                }
                #endregion Validate current domain and user name --- End

                DataTable dtAllGroup = GetAllGroup();
                if (dtAllGroup == null)
                {
                    //I Error
                    return(null);
                }
                if (dtAllGroup.Rows.Count < 1)
                {
                    //I Error
                    return(null);
                }

                #endregion Get and validate data --- End

                #region  " Get group from current user name "
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    {
                        #region  " For by all group in sharepoint "
                        for (int i1 = 0; i1 < dtAllGroup.Rows.Count; i1++)
                        {
                            SPGroup oGroup = SPContext.Current.Web.Groups[dtAllGroup.Rows[i1]["Name"].ToString()];
                            if (dtAllGroup.Rows[i1]["Name"].ToString().Contains("spimportal visitors"))
                            {
                                SPUser user = oGroup.Users[0];
                                string str  = user.Name;
                            }
                            foreach (SPUser user in oGroup.Users)
                            {
                                if (user.Name.ToUpper().Contains("DOMAIN USERS"))
                                {
                                    string[] users = user.Name.Split('\\');
                                    if (users.Length == 2)
                                    {
                                        if (users != null)
                                        {
                                            if (!users[0].Trim().Equals(""))
                                            {
                                                if (users[0].Trim().ToUpper().Equals(DomainName.ToUpper().Trim()))
                                                {
                                                    dtReturn.Rows.Add(dtAllGroup.Rows[i1]["Name"].ToString(),
                                                                      dtAllGroup.Rows[i1]["ID"].ToString());
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    string[] users = user.LoginName.Split('\\');
                                    if (users.Length == 2)
                                    {
                                        if (users[1].Trim().ToLower() != "system")
                                        {
                                            if (users[1].ToString().ToUpper().Equals(Uname.ToUpper()))
                                            {
                                                dtReturn.Rows.Add(dtAllGroup.Rows[i1]["Name"].ToString(),
                                                                  dtAllGroup.Rows[i1]["ID"].ToString());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion For by all group in sharepoint --- End
                    }
                });
                #endregion Get group from current user name --- End

                return(dtReturn);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Ejemplo n.º 20
0
        /// </summary>
        /// <param name="ListName">列表名称连接的字符串</param>
        /// <param name="subWebUrl">子网站Url</param>
        /// <returns>统计的各项活动积分数组</returns>
        private int[] StatisticAllList(string ListName, string subWebUrl)
        {
            SPQuery oQuery;
            SPList  sList;

            string[] lstName   = ListName.Split(';');
            string[] qr        = QR.Split(';');
            string[] ppr       = PPR.Split(';');
            int[]    itmCounts = new int[lstName.Length + 1];
            int[]    scores    = new int[lstName.Length + 1];
            SPUser   logUser   = SPContext.Current.Web.CurrentUser;

            if (logUser == null)//获取所有用户的信息
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                        {
                            itmCounts[0] = GetTotalNewsFeeds();//微博
                            scores[0]    = itmCounts[0] * int.Parse(qr[0]) * int.Parse(ppr[0]);
                            int i        = 0;
                            int j        = 0;
                            foreach (string mList in lstName)
                            {
                                try
                                {
                                    if (mList == "Posts" && subWebUrl != "")//统计备忘录
                                    {
                                        SPWeb subWeb = web.Webs[subWebUrl];
                                        sList        = subWeb.Lists.TryGetList(mList);
                                    }
                                    else
                                    {
                                        sList = web.Lists.TryGetList(mList);
                                    }
                                    i      = i + 1;
                                    oQuery = new SPQuery();
                                    oQuery.ViewAttributes = "Scope='RecursiveAll'";
                                    //oQuery.Query = "<Where><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq></Where>";
                                    SPListItemCollection lstItems = sList.GetItems(oQuery);
                                    j = lstItems.Count;//个人
                                    EnumerateList(ref j, web, mList, "");
                                    itmCounts[i] = j;
                                    scores[i]    = itmCounts[i] * int.Parse(qr[i]) * int.Parse(ppr[i]);
                                }
                                catch
                                { }
                            }
                        }
                    }
                });
            }
            else
            {
                //int i = 1;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                        {
                            itmCounts[0] = GetTotalNewsFeeds();//微博
                            scores[0]    = itmCounts[0] * int.Parse(qr[0]) * int.Parse(ppr[0]);
                            int i        = 0;
                            int j        = 0;
                            foreach (string mList in lstName)
                            {
                                try
                                {
                                    if (mList == "Posts" && subWebUrl != "")//统计备忘录
                                    {
                                        SPWeb subWeb = web.Webs[subWebUrl];
                                        sList        = subWeb.Lists.TryGetList(mList);
                                    }
                                    else
                                    {
                                        sList = web.Lists.TryGetList(mList);
                                    }
                                    i      = i + 1;
                                    oQuery = new SPQuery();
                                    oQuery.ViewAttributes         = "Scope='RecursiveAll'";
                                    oQuery.Query                  = "<Where><Eq><FieldRef Name='Author'/><Value Type='Text'>" + logUser.Name + "</Value></Eq></Where>";
                                    SPListItemCollection lstItems = sList.GetItems(oQuery);
                                    j = lstItems.Count;//个人
                                    EnumerateList(ref j, web, mList, logUser.Name);
                                    itmCounts[i] = j;
                                    scores[i]    = itmCounts[i] * int.Parse(qr[i]) * int.Parse(ppr[i]);
                                }
                                catch
                                { }
                            }
                        }
                    }
                });
            }

            return(scores);
        }
Ejemplo n.º 21
0
        private static XElement GetTemplateByName(string name)
        {
            XElement templatebyName = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID, SPUrlZone.Internet))
                    {
                        using (SPWeb web = currentSite.OpenWeb(SPContext.Current.Web.ID))
                        {
                            SPDocumentLibrary SiteAssets = null;
                            SPFolder Templates           = null;
                            SPFile Aanmelden             = null;

                            XElement template = null;

                            SPList assets = web.Lists.TryGetList("SiteAssets");

                            if (assets == null)
                            {
                                assets = web.Lists.TryGetList("Siteactiva");
                            }

                            if (assets != null)
                            {
                                SiteAssets = (SPDocumentLibrary)assets;
                            }

                            if (SiteAssets != null)
                            {
                                Templates = SiteAssets.RootFolder.SubFolders["Templates"];
                            }

                            if (Templates != null && Templates.Exists)
                            {
                                Aanmelden = Templates.Files["template.xsl"];
                            }

                            if (Aanmelden != null && Aanmelden.Exists)
                            {
                                template = XElement.Load(Aanmelden.OpenBinaryStream());
                            }

                            if (template == null)
                            {
                                throw new FileNotFoundException("Template not Found", Aanmelden.Url);
                            }

                            templatebyName = template.Elements("{http://www.w3.org/1999/XSL/Transform}template").Where(temp => temp.Attribute("name").Value == name).FirstOrDefault();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message);
                }
            });
            return(templatebyName);
        }
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            this.EventFiringEnabled = false;
            SPListItem       item = null;
            SPList           list = null;
            MembershipStatus status;

            try
            {
                item = properties.ListItem;
                if (item != null)
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(item.Web.Site.ID, item.Web.Site.Zone))
                        {
                            using (SPWeb web = site.OpenWeb(item.Web.ID))
                            {
                                if (web != null)
                                {
                                    site.AllowUnsafeUpdates = true;
                                    web.AllowUnsafeUpdates  = true;

                                    list   = item.ParentList;
                                    status = (MembershipStatus)Utils.GetChoiceIndex(list.Fields.GetFieldByInternalName(MembershipReviewListFields.STATUS) as SPFieldChoice, item[MembershipReviewListFields.STATUS].ToString());
                                    switch (status)
                                    {
                                    case MembershipStatus.Approved:
                                        // TODO: rdcpro: if CreateUser in the ApproveMembership call fails, the user in the MemberShipRequest list needs to be marked somehow so that the approver knows what the problem is.
                                        // Maybe the list should have the "LastError" field which will get the error info, or else the status can have an extra error value in addition to pending | approved | rejected
                                        // Then in the calling code, we must not delete the item from the list!
                                        // It would have been better if ApproveMembership returned a status code, rather than use exception handling, but here we are.
                                        MembershipRequest.ApproveMembership(GetMembershipRequest(web, item), web);
                                        item.Delete();
                                        list.Update();

                                        break;

                                    case MembershipStatus.Pending:
                                        break;

                                    case MembershipStatus.Rejected:
                                        if (!MembershipRequest.RejectMembership(GetMembershipRequest(web, item), web))
                                        {
                                            throw new Exception("Error rejecting membership");
                                        }
                                        //bms Removed Delete from Reject Membership to allow administrators to approve user later and delete with UI
                                        //item.Delete();
                                        //list.Update();
                                        break;
                                    }
                                }
                            }
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error updating item in Membership Request List", ex);
            }
            finally
            {
                this.EventFiringEnabled = true;
            }
        }
Ejemplo n.º 23
0
        static void Track(string url, string SPListURLDir, string SPListItemId, string Folder, HttpContext context)
        {
            SPUserToken userToken = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        string body;
                        using (var reader = new StreamReader(context.Request.InputStream))
                            body = reader.ReadToEnd();

                        var fileData = new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(body);
                        try
                        {
                            var userList = (System.Collections.ArrayList)fileData["users"];
                            var userID   = Int32.Parse(userList[0].ToString());

                            var users = web.AllUsers;
                            for (int i = 0; i < users.Count; i++)
                            {
                                if (users[i].ID == userID)
                                {
                                    userToken = users[i].UserToken;
                                    break;
                                }
                            }
                            if (userToken == null)
                            {
                                userToken = web.AllUsers[0].UserToken;
                            }
                        }
                        catch (Exception ex) {
                            Log.LogError(ex.Message);
                            userToken = web.AllUsers[0].UserToken;
                        }

                        try
                        {
                            SPSite s = new SPSite(url, userToken);
                            SPWeb w  = s.OpenWeb();

                            SPList list     = w.GetList(SPListURLDir);
                            SPListItem item = list.GetItemById(Int32.Parse(SPListItemId));

                            //save file to SharePoint
                            if ((int)fileData["status"] == 2)
                            {
                                var req = (string)fileData["url"];

                                var replaceExistingFiles = true;

                                var fileName = item.File.Name;

                                w.AllowUnsafeUpdates = true; //for list update in SharePoint necessary AllowUnsafeUpdates = true
                                w.Update();

                                byte[] fileDataArr = null;
                                using (var wc = new WebClient())
                                    fileDataArr = wc.DownloadData(req);

                                if (Folder != "")
                                {
                                    SPFolder folder = w.GetFolder(Folder);
                                    folder.Files.Add(fileName, fileDataArr, replaceExistingFiles);
                                    folder.Update();
                                }
                                else
                                {
                                    list.RootFolder.Files.Add(fileName, fileDataArr, replaceExistingFiles);
                                    list.Update();
                                }

                                w.AllowUnsafeUpdates = false;
                                w.Update();
                            }
                            context.Response.Write("{\"error\":0}");
                        }
                        catch (Exception ex)
                        {
                            Log.LogError(ex.Message);
                        }
                    }
                }
            });
        }
Ejemplo n.º 24
0
        //public static s_GridResult GetDataTable(string _search, string nd, int rows, int page, string sidx, string sord)

        public static s_GridResult GetDataTable(string nd, int rows, int page, string sidx, string sord)
        {
            try
            {
                string   _stdate           = HttpContext.Current.Request.QueryString["_stdate"].ToString();
                string   _enddate          = HttpContext.Current.Request.QueryString["_enddate"].ToString();
                DateTime _enddateformatted = Convert.ToDateTime(_enddate);
                string   siteurl           = HttpContext.Current.Request.UrlReferrer.ToString();
                var      url        = new Uri(siteurl);
                string   rbsurl     = url.Scheme + "://" + url.Host + ":" + url.Port + url.Segments[0] + url.Segments[1];
                int      startindex = (page - 1);
                int      endindex   = page;
                Guid     adminguid;
                var      resource_svc = new Resource();
                adminguid        = new Guid("6FF0A657-63BC-4390-8AAF-7EE5CE033088");
                resource_svc.Url = "http://jump/cimb/_vti_bin/psi/resource.asmx";

                if (url.Host.ToString() != "localhost")
                {
                    //var rbs = new ReadRBSValues(System.Net.CredentialCache.DefaultNetworkCredentials, "http://jump/cimb");
                    resource_svc.Url = rbsurl + "/_vti_bin/psi/resource.asmx";
                }
                //var rbs = new ReadRBSValues(System.Net.CredentialCache.DefaultNetworkCredentials, rbsurl);
                //var resuids = rbs.GetBottomLevelResouceUIDs();
                resource_svc.UseDefaultCredentials = true;
                resource_svc.AllowAutoRedirect     = true;
                Guid   currentuserid            = resource_svc.GetCurrentUserUid();
                string res_under_curr_user      = @"
                        SELECT		ResourceUID
                        FROM		dbo.MSP_EpmResource_UserView
                        WHERE		(RBS Like (	(
                                                SELECT	RBS
                                                FROM	dbo.MSP_EpmResource_UserView
                                                WHERE	ResourceUID = '"                         + currentuserid.ToString() + @"'
                                                )
                                            +'.%')
                                    ) AND ResourceIsActive = 1
                        ";
                WindowsImpersonationContext wik = null;
                wik = WindowsIdentity.Impersonate(IntPtr.Zero);
                SqlConnection con = new SqlConnection(MyConfiguration.GetDataBaseConnectionString(siteurl));
                con.Open();
                DataSet        filterresourcelist    = new DataSet();
                SqlDataAdapter filterresourceadapter = new SqlDataAdapter(res_under_curr_user, con);
                filterresourceadapter.Fill(filterresourcelist);
                string filterresource = "(";
                foreach (DataRow row in filterresourcelist.Tables[0].Rows)
                {
                    filterresource += "'" + row[0].ToString() + "',";
                }

                /*                foreach (var resuid in resuids)
                 *              {
                 *                  filterresource += "'" + resuid.ToString() + "',";
                 *              }
                 */
                filterresource = filterresource.Substring(0, filterresource.Length - 1) + ")";
                MyConfiguration.ErrorLog("RBS Resource List : " + filterresource, EventLogEntryType.Information);
                string       gridqry = @"
        SELECT		res.ResourceUID, res.ResourceName, res.RBS, tperiod.PeriodUID, tperiod.PeriodStatusID, tperiod.StartDate, tperiod.EndDate, tperiod.PeriodName,
                    tperiod.LCID, ISNULL(TM_Name.ResourceName, 'Not Assigned') AS TM_Name
        INTO        [#t1]
        FROM        MSP_EpmResource_UserView AS TM_Name RIGHT OUTER JOIN
                    MSP_EpmResource_UserView AS res ON TM_Name.ResourceUID = res.ResourceTimesheetManagerUID CROSS JOIN
                    MSP_TimesheetPeriod AS tperiod
        WHERE		(tperiod.StartDate BETWEEN (
                    (SELECT		CASE WHEN (TimeDayOfTheWeek = 2) THEN '"                 + _stdate + @"' WHEN (TimeDayOfTheWeek = 1) THEN DATEADD(d,1, '" + _stdate + @"' )
                                ELSE DATEADD(d,(2-TimeDayofTheWeek), '"                         + _stdate + @"' ) END AS stdate
                    FROM        MSP_TimeByDay
                    WHERE		(TimeByDay = CONVERT(DATETIME, '"                 + _stdate + @"' , 102)))
                    )
                    AND '"             + _enddate + @"' ) AND (res.ResourceUID IN " + filterresource + @")
        SELECT      [#t1].PeriodUID, [#t1].ResourceUID,[#t1].TM_Name, [#t1].RBS, [#t1].ResourceName, [#t1].PeriodName,
                    ISNULl(tstatus.Description,'Not Created') AS [TimeSheet Status], [#t1].StartDate, [#t1].EndDate
        INTO #t2
        FROM        MSP_TimesheetStatus AS tstatus INNER JOIN
                    MSP_Timesheet AS tsheet ON tstatus.TimesheetStatusID = tsheet.TimesheetStatusID INNER JOIN
                    MSP_TimesheetResource AS tres ON tsheet.OwnerResourceNameUID = tres.ResourceNameUID RIGHT OUTER JOIN
                    [#t1] ON [#t1].ResourceUID = tres.ResourceUID AND [#t1].PeriodUID = tsheet.PeriodUID
        drop table	#t1
        /*SELECT		PeriodName, TM_Name, ResourceName, COUNT(CASE WHEN ([TimeSheet Status] = 'In Progress') THEN [TimeSheet Status] END)
                    AS [In Progress], COUNT(CASE WHEN ([TimeSheet Status] = 'Not Created') THEN [TimeSheet Status] END) AS [Not Created],
                    COUNT(CASE WHEN ([TimeSheet Status] = 'Submitted') THEN [TimeSheet Status] END) AS Submitted
        FROM        [#t2]
        WHERE		([TimeSheet Status] <> 'Approved')
        GROUP BY	PeriodName, TM_Name, ResourceName
        ORDER BY	PeriodName, TM_Name, ResourceName
        */
        SELECT		PeriodName, COUNT(CASE WHEN ([TimeSheet Status] = 'In Progress') THEN [TimeSheet Status] END)
                    AS [In Progress], COUNT(CASE WHEN ([TimeSheet Status] = 'Not Created') THEN [TimeSheet Status] END) AS [Not Created],
                    COUNT(CASE WHEN ([TimeSheet Status] = 'Submitted') THEN [TimeSheet Status] END) AS Submitted,
                    COUNT(CASE WHEN ([TimeSheet Status] = 'Approved') THEN [TimeSheet Status] END) AS Approved
        FROM        [#t2]
        --WHERE		([TimeSheet Status] <> 'Approved')
        GROUP BY	PeriodName
        ORDER BY	PeriodName
        drop table	#t2
        ";
                s_GridResult result  = new s_GridResult();
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        DataSet dt             = new DataSet();
                        SqlDataAdapter adapter = new SqlDataAdapter(new SqlCommand(gridqry, con));
                        adapter.Fill(dt);
                        DataTable maintbl          = dt.Tables[0];
                        List <s_RowData> rowsadded = new List <s_RowData>();
                        int idx = 1;
                        try
                        {
                            foreach (DataRow row in maintbl.Rows)
                            {
                                s_RowData newrow = new s_RowData();
                                newrow.id        = idx++;
                                //Tabel Column List -- ResourceName - 0,TimeSheet Period - 1,TimeSheet Period Status - 2
                                newrow.cell    = new string[5];     //total number of columns
                                newrow.cell[0] = row[0].ToString(); //TimeSheet Period Name
                                newrow.cell[1] = row[1].ToString(); //In Progress
                                newrow.cell[2] = row[2].ToString(); //Not Created
                                newrow.cell[3] = row[3].ToString(); //Submitted
                                newrow.cell[4] = row[4].ToString(); //Approved
                                rowsadded.Add(newrow);
                            }
                        }
                        catch (Exception ex)
                        {
                            MyConfiguration.ErrorLog("Error At Manipulating Json Data" + ex.Message, EventLogEntryType.Error);
                        }
                        result.rows   = rowsadded.ToArray();
                        result.page   = page;
                        result.total  = dt.Tables[0].Rows.Count;
                        result.record = rowsadded.Count;
                    });
                }
                catch (Exception ex)
                {
                    MyConfiguration.ErrorLog("Error at SPSecurity Delegate :" + ex.Message, EventLogEntryType.Error);
                }
                return(result);
            }
            catch (Exception ex)
            {
                MyConfiguration.ErrorLog("Error at web method due to " + ex.Message, EventLogEntryType.Error);
            }
            return(new s_GridResult());
        }
        /// <summary>
        ///统计不同时间的个人用户和团队的新闻源
        /// </summary>
        /// MaxThreadCount最大值是100,即最多只能返回100,默认值是20,
        /// <returns>返回一维数组,0-个人总数,1-团队总数,2-当日更新,3-本周更新</returns>
        private int[] GetPublishdNews()
        {
            SPSocialFeedOptions socialOptions = new SPSocialFeedOptions();

            socialOptions.MaxThreadCount = int.MaxValue;
            int i = 0;
            int j = 0;

            int[] totalTimes = new int[6];

            try
            {
                string acountName = GetAccountName();
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        //this.Controls.Add(new LiteralControl("site:" + site.Url + "<br/>"));
                        using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
                        {
                            //this.Controls.Add(new LiteralControl("web:"+web.Url + "<br/>"));
                            SPServiceContext serviceContext = SPServiceContext.GetContext(site);
                            UserProfileManager upm          = new UserProfileManager(serviceContext);
                            string accountName = GetAccountName();
                            //this.Controls.Add(new LiteralControl("name:" + accountName + "<br/>"));
                            UserProfile u = upm.GetUserProfile(accountName);
                            SPSocialFeedManager feedManager = new SPSocialFeedManager(u, serviceContext);
                            SPSocialFeed feed        = feedManager.GetFeedFor(web.Url, socialOptions);
                            SPSocialThread[] threads = feed.Threads;
                            //this.Controls.Add(new LiteralControl("count:" + threads.Length + "<br/>"));
                            foreach (SPSocialThread thread in threads)
                            {
                                //只统计用户发布的新闻源,thread.Attributes.ToString() == "None"表示用户关注了哪些内容,这部分没有统计
                                if (thread.Attributes.ToString() != "None")
                                {
                                    string actorAccount;

                                    if (thread.Actors.Length == 1)
                                    {
                                        actorAccount = thread.Actors[0].AccountName;
                                    }
                                    else
                                    {
                                        actorAccount = thread.Actors[1].AccountName;
                                    }
                                    //string temp = "";
                                    //for (int k = 0; k < thread.Actors.Length; k++)
                                    //{
                                    //    temp += thread.Actors[k].AccountName+" 、 ";
                                    //}
                                    //this.Controls.Add(new LiteralControl("actorlength:" + thread.Actors.Length + ";actorAccount:" + temp + "<br/>"));
                                    //当前用户
                                    if (actorAccount.ToLower() == accountName.ToLower())
                                    {
                                        i = i + 1;
                                    }

                                    j = j + 1;
                                }
                            }
                            totalTimes[0] = i; //个人总数
                            //this.Controls.Add(new LiteralControl("my:" + i + "<br/>"));
                            totalTimes[1] = j; //团队总数
                            //this.Controls.Add(new LiteralControl("all:" + j + "<br/>"));

                            socialOptions = new SPSocialFeedOptions();
                            socialOptions.MaxThreadCount = int.MaxValue;
                            //this.Controls.Add(new LiteralControl("Now:" + DateTime.Now + "<br/>24小时前:" + DateTime.Now.AddHours(-24) + "<br/>一天前:" + DateTime.Now.AddDays(-1)));
                            socialOptions.NewerThan = DateTime.Now.AddHours(-32);//.Date.AddDays(-1).AddHours(8);
                            feed          = feedManager.GetFeedFor(web.Url, socialOptions);
                            threads       = feed.Threads;
                            totalTimes[3] = threads.Length;//团队当日更新
                            i             = 0; j = 0;
                            foreach (SPSocialThread thread in threads)
                            {
                                //只统计用户发布的新闻源,thread.Attributes.ToString() == "None"表示用户关注了哪些内容,这部分没有统计
                                if (thread.Attributes.ToString() != "None")
                                {
                                    string actorAccount;

                                    if (thread.Actors.Length == 1)
                                    {
                                        actorAccount = thread.Actors[0].AccountName;
                                    }
                                    else
                                    {
                                        actorAccount = thread.Actors[1].AccountName;
                                    }
                                    //string temp = "";
                                    //for (int k = 0; k < thread.Actors.Length; k++)
                                    //{
                                    //    temp += thread.Actors[k].AccountName+" 、 ";
                                    //}
                                    //this.Controls.Add(new LiteralControl("actorlength:" + thread.Actors.Length + ";actorAccount:" + temp + "<br/>"));
                                    //当前用户
                                    if (actorAccount.ToLower() == accountName.ToLower())
                                    {
                                        i = i + 1;
                                    }

                                    j = j + 1;
                                }
                            }
                            totalTimes[2] = i;//个人当日更新

                            socialOptions = new SPSocialFeedOptions();
                            socialOptions.MaxThreadCount = int.MaxValue;
                            socialOptions.NewerThan      = DateTime.Now.Date.AddDays(-6).AddHours(-8);//.AddHours(8);
                            feed = feedManager.GetFeedFor(web.Url, socialOptions);

                            threads       = feed.Threads;
                            totalTimes[5] = threads.Length;//团队本周更新

                            i = 0; j = 0;
                            foreach (SPSocialThread thread in threads)
                            {
                                //只统计用户发布的新闻源,thread.Attributes.ToString() == "None"表示用户关注了哪些内容,这部分没有统计
                                if (thread.Attributes.ToString() != "None")
                                {
                                    string actorAccount;

                                    if (thread.Actors.Length == 1)
                                    {
                                        actorAccount = thread.Actors[0].AccountName;
                                    }
                                    else
                                    {
                                        actorAccount = thread.Actors[1].AccountName;
                                    }
                                    //string temp = "";
                                    //for (int k = 0; k < thread.Actors.Length; k++)
                                    //{
                                    //    temp += thread.Actors[k].AccountName+" 、 ";
                                    //}
                                    //this.Controls.Add(new LiteralControl("actorlength:" + thread.Actors.Length + ";actorAccount:" + temp + "<br/>"));
                                    //当前用户
                                    if (actorAccount.ToLower() == accountName.ToLower())
                                    {
                                        i = i + 1;
                                    }

                                    j = j + 1;
                                }
                            }
                            totalTimes[4] = i;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                this.Controls.Add(new LiteralControl(ex.Message));
            }
            return(totalTimes);
        }
Ejemplo n.º 26
0
        private void BuildSiteMap()
        {
            urlset sitemap = new urlset();

            //Guid siteId = SPContext.Current.Site.ID;
            //Guid webId = SPContext.Current.Web.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteId))
                {
                    using (SPWeb web = site.OpenWeb(webId))
                    {
                        foreach (SPList list in web.Lists)
                        {
                            if (ContainsWebPageTypes(list))
                            {
                                SPListItemCollection items = null;

                                SPQuery query        = new SPQuery();
                                query.ViewAttributes = "Scope=\"Recursive\"";
                                query.Query          = "<Where><IsNotNull><FieldRef Name=\"PublishingPageDesign\" /></IsNotNull></Where>";
                                query.ViewFields     = "<FieldRef Name=\"Title\"/><FieldRef Name=\"EncodedAbsUrl\"/><FieldRef Name=\"FileRef\"/><FieldRef Name=\"ContentType\"/><FieldRef Name=\"Created\"/><FieldRef Name=\"Modified\"/>";
                                items = list.GetItems(query);

                                foreach (SPListItem item in items)
                                {
                                    List <SemanticUrl> entries = new List <SemanticUrl>();
                                    if (item.File.Exists && item.File.Level == SPFileLevel.Published)
                                    {
                                        entries = CheckSemantics(item.File.ServerRelativeUrl.ToLower().ToString());

                                        if (entries != null && entries.Count > 0)
                                        {
                                            foreach (SemanticUrl surl in entries)
                                            {
                                                tUrl url = new tUrl();
                                                url.changefreqSpecified = true;
                                                url.changefreq          = DetermineFrequency(item["Created"].ToString(), item["Modified"].ToString(), item.Versions.Count);
                                                url.lastmod             = DateTime.Parse(item["Modified"].ToString()).ToString("yyyy-MM-dd");//,.ToShortDateString();
                                                url.loc = surl.Semantic;
                                                url.prioritySpecified = true;
                                                url.priority          = new decimal(0.5f);
                                                if (!sitemap.url.Contains(url))
                                                {
                                                    sitemap.url.Add(url);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            tUrl url = new tUrl();
                                            url.changefreqSpecified = true;
                                            url.changefreq          = DetermineFrequency(item["Created"].ToString(), item["Modified"].ToString(), item.Versions.Count);
                                            url.lastmod             = DateTime.Parse(item["Modified"].ToString()).ToString("yyyy-MM-dd");//,.ToShortDateString();
                                            url.loc = item["EncodedAbsUrl"].ToString();
                                            url.prioritySpecified = true;
                                            url.priority          = new decimal(0.5f);
                                            if (!sitemap.url.Contains(url))
                                            {
                                                sitemap.url.Add(url);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });

            textWriter.Append(sitemap.Serialize(Encoding.UTF8));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Actualiza la relacion automática hacia la lista Correspondencia de Entrada
        /// </summary>
        /// <param name="properties"></param>
        private void EventoActualizarAsociarCorrespondenciaEntrante(SPItemEventProperties properties)
        {
            object enRespuestaAAntes   = properties.ListItem["En_x0020_respuesta_x0020_a"];
            object enRespuestaADespues = properties.AfterProperties["En_x0020_respuesta_x0020_a"];

            if (((SPFieldLookupValueCollection)enRespuestaAAntes).Count == 0 &&
                string.IsNullOrEmpty(enRespuestaADespues.ToString())) //Si el campo "En respuesta a" esta vacio
            {
                return;
            }

            SPSite sitioAdm = null;
            SPWeb  webAdm   = null;

            try
            {
                string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"];

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {//Como usuario administrador
                    sitioAdm = new SPSite(UrlFPC);
                    webAdm   = sitioAdm.OpenWeb();
                });

                SPFieldLookupValueCollection enlacesSalidaAntes =
                    (SPFieldLookupValueCollection)enRespuestaAAntes;
                SPFieldLookupValueCollection enlacesSalidaDespues =
                    new SPFieldLookupValueCollection(enRespuestaADespues.ToString());

                SPListItem itemEntrada;
                SPFieldLookupValueCollection enlacesEntrada;
                SPFieldLookupValueCollection enlacesEntrada2;

                #region Definir la lista usada
                string listaCorreoUsada = "";
                if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                  CORREO_SALIDA_FUNDAPRO, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_FUNDAPRO;
                }
                else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                       CORREO_SALIDA_EDUCAPRO, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO;
                }
                else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                       CORREO_SALIDA_EDUCAPRO_CB, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_CB;
                }
                else if (string.Equals(webAdm.Lists[properties.ListId].Title.Trim(),
                                       CORREO_SALIDA_EDUCAPRO_SC, StringComparison.CurrentCultureIgnoreCase))
                {
                    listaCorreoUsada = CORREO_ENTRADA_EDUCAPRO_SC;
                }
                #endregion

                #region Eliminar relacion existente sobre este elemento
                foreach (SPFieldLookupValue enlaceSalidaAntes in enlacesSalidaAntes)
                {
                    itemEntrada = webAdm.Lists[listaCorreoUsada].Items.GetItemById(
                        enlaceSalidaAntes.LookupId);
                    enlacesEntrada  = (SPFieldLookupValueCollection)itemEntrada["Respuesta"];
                    enlacesEntrada2 = (SPFieldLookupValueCollection)itemEntrada["Respuesta"];

                    for (int i = 0; i < enlacesEntrada.Count; i++)
                    {
                        if (enlacesEntrada[i].LookupId == properties.ListItemId)
                        {
                            enlacesEntrada2.RemoveAt(i);
                            break;
                        }
                    }

                    itemEntrada["Respuesta"] = enlacesEntrada2;

                    using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                    {
                        itemEntrada.SystemUpdate();
                    }
                }
                #endregion

                #region Crear relacion sobre este elemento
                foreach (SPFieldLookupValue enlaceSalidaDespues in enlacesSalidaDespues)
                {
                    itemEntrada = webAdm.Lists[listaCorreoUsada].Items.GetItemById(
                        enlaceSalidaDespues.LookupId);
                    enlacesEntrada = (SPFieldLookupValueCollection)itemEntrada["Respuesta"];
                    SPFieldLookupValue enlaceEntrada = new SPFieldLookupValue(properties.ListItemId,
                                                                              properties.ListItem["CITE"].ToString());

                    if (!enlacesEntrada.Contains(enlaceEntrada))
                    {
                        enlacesEntrada.Add(enlaceEntrada);
                    }

                    itemEntrada["Respuesta"] = enlacesEntrada;

                    using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                    {
                        itemEntrada.SystemUpdate();
                    }
                }
                #endregion
            }
            finally
            {
                if (webAdm != null)
                {
                    webAdm.Dispose();
                }
                if (sitioAdm != null)
                {
                    sitioAdm.Dispose();
                }
            }
        }
Ejemplo n.º 28
0
        private void BuildNewsMap()
        {
            News.urlset newsmap = new News.urlset();

            //Guid siteId = SPContext.Current.Site.ID;
            //Guid webId = SPContext.Current.Web.ID;

            string geo_location = string.Format("{0},{1},{2}", company.City, company.State, company.Country);;

            geo_location = geo_location.TrimStart(new char[] { ',' });
            geo_location = geo_location.TrimEnd(new char[] { ',' });

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteId))
                {
                    SPWebCollection webs = site.AllWebs;

                    foreach (SPWeb aweb in webs)
                    {
                        using (SPWeb web = site.OpenWeb(aweb.ID))
                        {
                            foreach (SPList list in web.Lists)
                            {
                                if (ContainsWebPageTypes(list))
                                {
                                    SPListItemCollection items = null;
                                    SPQuery query        = new SPQuery();
                                    query.ViewAttributes = "Scope=\"Recursive\"";
                                    query.Query          = "<Where><IsNotNull><FieldRef Name=\"PublishingPageDesign\" /></IsNotNull></Where>";
                                    query.ViewFields     = "<FieldRef Name=\"Title\"/><FieldRef Name=\"keywords\"/><FieldRef Name=\"EncodedAbsUrl\"/><FieldRef Name=\"FileRef\"/><FieldRef Name=\"ContentType\"/><FieldRef Name=\"Created\"/>";
                                    items = list.GetItems(query);

                                    try
                                    {
                                        foreach (SPListItem item in items)
                                        {
                                            List <SemanticUrl> entries = new List <SemanticUrl>();

                                            if (item.File.Exists && item.File.Level == SPFileLevel.Published && (item.File.TimeLastModified >= (DateTime.Now.AddDays(-3))))
                                            {
                                                try
                                                {
                                                    CultureInfo info = new CultureInfo((int)SPContext.Current.Web.RegionalSettings.LocaleId);
                                                    //CultureInfo info = System.Globalization.CultureInfo.GetCultureInfo((int)web.Language);
                                                    entries = CheckSemantics(item.File.ServerRelativeUrl.ToLower().ToString());

                                                    if (entries != null && entries.Count > 0)
                                                    {
                                                        foreach (SemanticUrl surl in entries)
                                                        {
                                                            News.tUrl url            = new News.tUrl();
                                                            url.loc                  = surl.Semantic;
                                                            url.news.accessSpecified = false;
                                                            url.news.genres          = DetermineGenres(item);

                                                            if (item.Fields.ContainsField("keywords"))
                                                            {
                                                                object words = item["keywords"];
                                                                if (words != null)
                                                                {
                                                                    url.news.keywords += GetAutoKeywords(words.ToString(), item);
                                                                }
                                                            }

                                                            url.news.publication.name     = web.Title.ToString();
                                                            url.news.accessSpecified      = false;
                                                            url.news.publication.language = info.TwoLetterISOLanguageName;
                                                            url.news.publication_date     = DateTime.Parse(item[SPBuiltInFieldId.Modified].ToString()).ToString("yyyy-MM-dd");

                                                            if (!String.IsNullOrEmpty(company.Stock))
                                                            {
                                                                url.news.stock_tickers = company.Stock;
                                                            }

                                                            if (!string.IsNullOrEmpty(geo_location))
                                                            {
                                                                url.news.geo_location = geo_location;
                                                            }

                                                            url.news.title = item[SPBuiltInFieldId.Title].ToString();
                                                            newsmap.url.Add(url);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        News.tUrl url            = new News.tUrl();
                                                        url.loc                  = item["EncodedAbsUrl"].ToString();
                                                        url.news.accessSpecified = false;
                                                        url.news.genres          = DetermineGenres(item);

                                                        if (item.Fields.ContainsField("keywords"))
                                                        {
                                                            object words = item["keywords"];
                                                            if (words != null)
                                                            {
                                                                url.news.keywords += GetAutoKeywords(words.ToString(), item);
                                                            }
                                                        }

                                                        url.news.publication.name     = web.Title.ToString();
                                                        url.news.accessSpecified      = false;
                                                        url.news.publication.language = info.TwoLetterISOLanguageName;
                                                        url.news.publication_date     = DateTime.Parse(item[SPBuiltInFieldId.Modified].ToString()).ToString("yyyy-MM-dd");

                                                        if (!String.IsNullOrEmpty(company.Stock))
                                                        {
                                                            url.news.stock_tickers = company.Stock;
                                                        }

                                                        if (!string.IsNullOrEmpty(geo_location))
                                                        {
                                                            url.news.geo_location = geo_location;
                                                        }

                                                        url.news.title = item[SPBuiltInFieldId.Title].ToString();
                                                        newsmap.url.Add(url);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    ex.ToString();
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.ToString();
                                    }
                                }
                            }
                        }
                        //<Query><Where><Geq><FieldRef Name="Modified" /><Value Type="DateTime">[4/12/2012 11:53:33 AM-30Day(s)]</Value></Geq></Where></Query>
                        //<Query><Where><And><Geq><FieldRef Name="Modified" /><Value Type="DateTime">[4/12/2012 11:28:42 AM-2Day(s)]</Value></Geq><IsNotNull><FieldRef Name=\"PublishingPageDesign\" /></IsNotNull><And></Where></Query>
                    }
                }
            });

            textWriter.Append(newsmap.Serialize(Encoding.UTF8));
        }
Ejemplo n.º 29
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Act act = new Act(Web);

                API.Integration.IntegrationCore integration = new API.Integration.IntegrationCore(Web.Site.ID, Web.ID);

                DataSet dsIntegrations = integration.GetIntegrations(act.IsOnline);

                StringBuilder sb = new StringBuilder();

                DataTable dtCat = dsIntegrations.Tables[0];

                foreach (DataRow drCat in dtCat.Rows)
                {
                    sb.Append("<div class=\"header-wrapper\">");
                    sb.Append("<h4>" + drCat["CATEGORY"].ToString() + "</h4>");
                    sb.Append("</div>");
                    sb.Append("<div style=\"width:100%;overflow: hidden;padding-bottom:30px;\">");


                    DataTable dtMods = dsIntegrations.Tables[drCat["INT_CAT_ID"].ToString()];

                    if (dtMods.Rows.Count == 0)
                    {
                        sb.Append("<div style=\"text-align:left;\">No integration modules available</div>");
                    }

                    foreach (DataRow dr in dtMods.Rows)
                    {
                        sb.Append("<div style=\"width:270px;float:left;padding-right:20px\">");

                        string icon = dr["Icon"].ToString();

                        if (icon == "")
                        {
                            icon = "/_layouts/epmlive/images/integration/base.png";
                        }
                        else
                        {
                            icon = "/_layouts/epmlive/images/integration/" + icon;
                        }

                        string desc = dr["Description"].ToString();


                        sb.Append("<TABLE border=0 cellSpacing=0 cellPadding=0 width=\"100%\" height=\"100%\"><tr>");
                        sb.Append("<td class=\"add-app-logo-box\">");
                        sb.Append("<img src=\"");
                        sb.Append(((Web.ServerRelativeUrl == "/") ? "" : Web.ServerRelativeUrl));
                        sb.Append(icon);
                        sb.Append("\"></td></tr><tr>");
                        sb.Append("<td class=\"titletd\"><b>");
                        sb.Append(dr["Title"].ToString());
                        sb.Append("</b>");
                        if (desc != "")
                        {
                            sb.Append("<div style=\"padding-top: 5px;padding-bottom:10px;padding-right:5px;work-wrap:break-word;\">");
                            sb.Append(desc);
                            sb.Append("</div>");
                        }
                        sb.Append("</td>");
                        sb.Append("</tr>");
                        sb.Append("<tr><td style=\"text-align:center;\">");
                        sb.Append("<a href=\"javascript:void(0);\" onclick=\"AddIntegration('");
                        sb.Append(dr["MODULE_ID"].ToString());
                        sb.Append("')\" class=\"btn btn-large btn-success\" style=\"text-decoration:none;\">Configure</a>");
                        sb.Append("</td></tr>");

                        sb.Append("</table>");

                        sb.Append("</div>");
                    }

                    sb.Append("</div>");
                }

                Integrations = sb.ToString();
            });
        }
Ejemplo n.º 30
0
        private HashSet <Guid> IsAuthorisedHashSet(Guid?securableParentUid, IEnumerable <Guid> securableObjectUids, params IRight[] requiredRights)
        {
            /// This user is a Glyma Security Manager, they have access to everything.
            if (Web.UserIsSiteAdmin)
            {
                return(new HashSet <Guid>(securableObjectUids));
            }

            IDbConnectionAbstraction securityDbConnection = GlymaSession.ConnectionFactory.CreateSecurityDbConnection();
            SecurityDBDataContext    dataContext          = null;
            SPSite elevatedSite = null;
            SPWeb  elevatedWeb  = null;

            try
            {
                GroupAssociationsOrderedByGroupSPId groupAssociations = new GroupAssociationsOrderedByGroupSPId();
                SecurableObjectGenealogyTracker     geneaologyTracker = new SecurableObjectGenealogyTracker();

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    dataContext = new SecurityDBDataContext(securityDbConnection.Connection);

                    if (securableParentUid != null)
                    {
                        IQueryable <SecurableObject> securableObjectInheritanceInfo = from securableObject in dataContext.SecurableObjects
                                                                                      where securableObject.SecurableContextId == SecurableContextId
                                                                                      select securableObject;

                        MultipleOrExpressionFilter <SecurableObject, Guid> securableObjectInheritanceInfoFilter = new MultipleOrExpressionFilter <SecurableObject, Guid>(securableObjectInheritanceInfo, securableObjectUids, "SecurableObjectUid");

                        IQueryable <SecurableObject> filteredSecurableObjectInheritanceInfo = securableObjectInheritanceInfoFilter.FilterResultSet();

                        geneaologyTracker.AddRange(securableParentUid, filteredSecurableObjectInheritanceInfo);

                        geneaologyTracker.AddRangeIfNotPreExisting(securableParentUid, securableObjectUids);
                    }
                    else
                    {
                        geneaologyTracker.AddRange(null, securableObjectUids);

                        IQueryable <GroupAssociation> groupsAssocationsWithBrokenInheritance = from securableObjectGroupAssocation in dataContext.GroupAssociations
                                                                                               where securableObjectGroupAssocation.SecurableContextId == SecurableContextId && securableObjectGroupAssocation.SecurableObject.BreaksInheritance == true
                                                                                               select securableObjectGroupAssocation;

                        MultipleOrExpressionFilter <GroupAssociation, Guid> securableObjectInheritanceInfoFilter = new MultipleOrExpressionFilter <GroupAssociation, Guid>(groupsAssocationsWithBrokenInheritance, securableObjectUids, "SecurableParentUid");

                        IQueryable <GroupAssociation> filteredSecurableObjectInheritanceInfo = securableObjectInheritanceInfoFilter.FilterResultSet();

                        groupAssociations.AddRange(filteredSecurableObjectInheritanceInfo);

                        foreach (GroupAssociation securableObjectWithBrokenInheritance in filteredSecurableObjectInheritanceInfo)
                        {
                            geneaologyTracker.Add(securableObjectWithBrokenInheritance.SecurableParentUid, securableObjectWithBrokenInheritance.SecurableObjectUid);
                        }
                    }

                    /// Get the group associations for only the securable objects.
                    IQueryable <GroupAssociation> allAccessibleGroupAssociations;

                    /// The following needs to be done as Linq doesn't detect the null value in Nullable types and so doesn't generate the correct "IS NULL" SQL.
                    if (securableParentUid.HasValue && geneaologyTracker.HasIndependentObjects && geneaologyTracker.HasInheritingObjects)
                    {
                        allAccessibleGroupAssociations = from securableObject in dataContext.GroupAssociations
                                                         where (securableObject.SecurableContextId == SecurableContextId && securableObject.SecurableParentUid == securableParentUid) || (securableObject.SecurableContextId == SecurableContextId && securableObject.SecurableParentUid == null)
                                                         select securableObject;
                    }
                    else if (securableParentUid.HasValue && geneaologyTracker.HasIndependentObjects)
                    {
                        allAccessibleGroupAssociations = from securableObject in dataContext.GroupAssociations
                                                         where securableObject.SecurableContextId == SecurableContextId && securableObject.SecurableParentUid == securableParentUid
                                                         select securableObject;
                    }
                    else /// This means the tracker has only either inheriting objects or domains.
                    {
                        allAccessibleGroupAssociations = from securableObject in dataContext.GroupAssociations
                                                         where securableObject.SecurableContextId == SecurableContextId && securableObject.SecurableParentUid == null
                                                         select securableObject;
                    }

                    MultipleOrExpressionFilter <GroupAssociation, Guid> groupAssocationFilter = new MultipleOrExpressionFilter <GroupAssociation, Guid>(allAccessibleGroupAssociations, geneaologyTracker.GetPermissionSources(), "SecurableObjectUid");

                    IQueryable <GroupAssociation> filteredGroupAssociations = groupAssocationFilter.FilterResultSet();

                    groupAssociations.AddRange(filteredGroupAssociations);
                });

                AccessibleObjectsBuilder accessibleObjects = new AccessibleObjectsBuilder();

                elevatedSite = GetElevatedSite();
                elevatedWeb  = GetElevatedWeb(elevatedSite);

                foreach (SPRoleAssignment roleAssignment in elevatedWeb.RoleAssignments)
                {
                    SPGroup elevatedGroup = roleAssignment.Member as SPGroup;

                    if (elevatedGroup != null)
                    {
                        SPGroup group = Web.Groups.GetByID(elevatedGroup.ID);

                        /// Check that we're actually looking at a group, and that this group is on the list of accessible groups, and that this group contains the current user.
                        if (group != null && group.ContainsCurrentUser)
                        {
                            /// Do a check that this group actually has the required right.
                            foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                            {
                                IRole role = GetRole(roleDefinition.Name);

                                IEnumerable <GroupAssociation> accessibleParentObjects;

                                if (groupAssociations.GetBySPId(group.ID, out accessibleParentObjects))
                                {
                                    if (role != null && role.HasRights(requiredRights))
                                    {
                                        IEnumerable <Guid> accessibleSecurableObjects = geneaologyTracker.GetSecurableObjectsByPermissionSources(accessibleParentObjects);
                                        accessibleObjects.AddRange(accessibleSecurableObjects);
                                    }
                                }
                            }
                        }
                    }
                }

                return(accessibleObjects.GetAccessibleObjects());
            }
            finally
            {
                if (dataContext != null)
                {
                    dataContext.Dispose();
                    dataContext = null;
                }

                if (elevatedWeb != null)
                {
                    elevatedWeb.Dispose();
                    elevatedWeb = null;
                }

                if (elevatedSite != null)
                {
                    elevatedSite.Dispose();
                    elevatedSite = null;
                }

                if (securityDbConnection != null)
                {
                    securityDbConnection.Dispose();
                    securityDbConnection = null;
                }
            }
        }