Exemplo n.º 1
0
        internal static OutputQueue ExecuteAdminServiceJobs(int timeOut)
        {
            var output = new OutputQueue();

            try
            {
                Parallel.ForEach(LocalFarm.Get().Servers.Where(p => Server.ValidSPServerRole(p.Role)),
                                 server =>
                {
                    ServiceController[] machineServices = ServiceController.GetServices(server.Address);

                    try
                    {
                        var service = machineServices.FirstOrDefault(s => s.ServiceName == AdminServiceName);
                        if (service != null)
                        {
                            output.Add(string.Format(CultureInfo.InvariantCulture, "Stopping {0} on {1}", AdminServiceName, server.Address));
                            if (service.Status == ServiceControllerStatus.Running && service.CanStop)
                            {
                                service.Stop();
                                service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(90));
                            }
                        }
                    }
                    catch (InvalidOperationException) { }
                    catch (Exception exception)
                    {
                        output.Add(exception.Message, OutputType.Error, exception.ToString(), exception);
                    }

                    var command = string.Format(CultureInfo.InvariantCulture, @"{0} -o execadmsvcjobs", SPUtility.GetGenericSetupPath(@"bin\stsadm.exe"));

                    output.Add(string.Format(CultureInfo.CurrentUICulture, UserDisplay.RunningCommandOn, command, server.Address));

                    try
                    {
                        var processWMI = new Threading.ProcessWMI();
                        processWMI.ExecuteRemoteProcessWMI(server.Address, command, timeOut);
                    }
                    catch (Exception exception)
                    {
                        output.Add(string.Format(CultureInfo.CurrentUICulture, Exceptions.ExceptionRunningCommandOn, command, server.Address, exception.Message), OutputType.Error, exception.ToString(), exception);
                    }

                    // Start Admin Service
                    machineServices = ServiceController.GetServices();

                    try
                    {
                        var service = machineServices.FirstOrDefault(s => s.ServiceName == AdminServiceName);
                        if (service != null)
                        {
                            output.Add(string.Format(CultureInfo.InvariantCulture, "Starting {0} on {1}", AdminServiceName, server.Address));
                            if (service.Status == ServiceControllerStatus.Stopped)
                            {
                                service.Start();
                                service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(90));
                            }
                        }
                    }
                    catch (InvalidOperationException) { }
                    catch (Exception exception)
                    {
                        output.Add(exception.Message, OutputType.Error, exception.ToString(), exception);
                    }
                });
            }
            catch (Exception exception)
            {
                output.Add(exception.Message, OutputType.Error, exception.ToString(), exception);
            }

            return(output);
        }
Exemplo n.º 2
0
        // construct the CAML query based on user criteria
        private string CriteriaQuery()
        {
            string       qry      = string.Empty;
            QueryBuilder qBuilder = new QueryBuilder();

            //----------------------------------------------------------------------------------------------------------
            // By Type
            if (DocTypeSelection == FilterType.MSOffice)
            {
                // first condition is without op parameter

                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>doc</Value>
                                            </Eq>");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>docx</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>xls</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>xlsx</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>ppt</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>pptx</Value>
                                            </Eq>", "OR");
            }

            else if (DocTypeSelection == FilterType.AdobePDF)
            {
                // first condition is without op parameter
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>pdf</Value>
                                            </Eq>");
            }

            else if (DocTypeSelection == FilterType.Images)
            {
                // first condition is without op parameter
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>jpg</Value>
                                            </Eq>");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>jpeg</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>bmp</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>png</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>gif</Value>
                                            </Eq>", "OR");
            }

            else if (DocTypeSelection == FilterType.Videos)
            {
                // first condition is without op parameter
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>avi</Value>
                                            </Eq>");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>mpg</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>wmv</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>mp4</Value>
                                            </Eq>", "OR");
            }

            else if (DocTypeSelection == FilterType.Audio)
            {
                // first condition is without op parameter
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>mp3</Value>
                                            </Eq>");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>wav</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>wma</Value>
                                            </Eq>", "OR");
            }
            else if (DocTypeSelection == FilterType.Web)
            {
                // first condition is without op parameter
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>htm</Value>
                                            </Eq>");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>aspx</Value>
                                            </Eq>", "OR");
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='DocIcon' />
                                                <Value Type='Computed'>xml</Value>
                                            </Eq>", "OR");
            }

            else if (DocTypeSelection == FilterType.Custom)
            {
                // first condition is without op parameter
                qBuilder.addCondition(@"<Eq>
                                                  <FieldRef Name='DocIcon' />
                                                  <Value Type='Computed'>" + CusDocType + @"</Value>
                                             </Eq>");
            }

            // All types
            else
            {
                // dummy first condition for All Types
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='FSObjType'/>
                                                <Value Type='Lookup'>0</Value>
                                              </Eq>");
            }
            //----------------------------------------------------------------------------------------------------------
            // for retrieving files only not folders
            qBuilder.addCondition(@"<Eq>
                                              <FieldRef Name='FSObjType'/>
                                              <Value Type='Lookup'>0</Value>
                                          </Eq>", "AND");
            //----------------------------------------------------------------------------------------------------------
            // by User
            if (UserSelection == FilterUser.SpecificCreatedByUser)
            {
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='Author' LookupId='TRUE' />
                                                <Value Type='User'>" + user.ID + @"</Value>
                                              </Eq>", "AND");
            }
            if (UserSelection == FilterUser.SpecifiModifiedByUSer)
            {
                qBuilder.addCondition(@"<Eq>
                                                <FieldRef Name='Editor' LookupId='TRUE' />
                                                <Value Type='User'>" + user.ID + @"</Value>
                                              </Eq>", "AND");
            }

            //----------------------------------------------------------------------------------------------------------

            // by Size
            qBuilder.addCondition(@"<Geq>
                                            <FieldRef Name='File_x0020_Size' />
                                            <Value Type='Lookup'>" + DocSize.ToString() + @"</Value>
                                          </Geq>", "AND");

            //----------------------------------------------------------------------------------------------------------


            // by Date
            if (DocDateSelection == FilterDate.SpecificCreatedDate)
            {
                qBuilder.addCondition(@"<Geq>
                                                <FieldRef Name='Created' />
                                                <Value Type='DateTime'>" + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DocBeginDate) + @"</Value>
                                              </Geq>", "AND");
                qBuilder.addCondition(@"<Leq>
                                                <FieldRef Name='Created' />
                                                <Value Type='DateTime'>" + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DocEndDate) + @"</Value>
                                              </Leq>", "AND");
            }
            else if (DocDateSelection == FilterDate.SpecificModifiedDate)
            {
                qBuilder.addCondition(@"<Geq>
                                                <FieldRef Name='Modified' />
                                                <Value Type='DateTime'>" + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DocBeginDate) + @"</Value>
                                              </Geq>", "AND");
                qBuilder.addCondition(@"<Leq>
                                                <FieldRef Name='Modified' />
                                                <Value Type='DateTime'>" + SPUtility.CreateISO8601DateTimeFromSystemDateTime(DocEndDate) + @"</Value>
                                              </Leq>", "AND");
            }

            //----------------------------------------------------------------------------------------------------------

            // by Text
            if (NameTextSelection == FilterText.SpecificText)
            {
                qBuilder.addCondition(@"<Contains>
                                                <FieldRef Name='FileLeafRef'/>
                                                <Value Type='Text'>" + TextinName + @"</Value>
                                              </Contains>", "AND");
            }


            //----------------------------------------------------------------------------------------------------------

            qry = qBuilder.constructQuery();

            return(qry);
        }
Exemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            btnOK.Attributes.Add("onclick", string.Format("javascript:{0}.disabled=true;", btnOK.ClientID));

            if (!IsPostBack)
            {
                var projectInfo = _spProjectUtility.RequestProjectInfo();

                switch (projectInfo.StatusCode)
                {
                case HttpStatusCode.Forbidden:
                    SPUtility.Redirect("accessdenied.aspx", SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current);
                    break;

                default:
                    var workspaceInfo = _spProjectUtility.RequestWorkspaceInfo(
                        new Guid(Request["List"]),
                        int.Parse(Request["id"]));

                    listName = workspaceInfo.ListName;
                    strName  = workspaceInfo.WorkspaceName;

                    URL     = projectInfo.ServerRelativeUrl;
                    baseURL = projectInfo.BaseUrl;

                    foreach (DictionaryEntry dictionaryEntry in projectInfo.PopulatedTemplates)
                    {
                        var li = new ListItem(dictionaryEntry.Key.ToString(), dictionaryEntry.Value.ToString());
                        DdlGroup.Items.Add(li);
                    }

                    inpName.Title = "Workspace Name";
                    txtTitle.Text = strName;
                    txtURL.Text   = strName.ToLower().Replace(" ", string.Empty);
                    btnOK.Text    = "Create Workspace";

                    if (projectInfo.IsNavigationEnabled.HasValue)
                    {
                        rdoTopLinkYes.Checked = projectInfo.IsNavigationEnabled == true;
                        rdoTopLinkNo.Checked  = projectInfo.IsNavigationEnabled == false;
                        rdoTopLinkNo.Enabled  = false;
                        rdoTopLinkYes.Enabled = false;
                    }

                    if (projectInfo.IsUnique.HasValue)
                    {
                        rdoUnique.Checked  = projectInfo.IsUnique == true;
                        rdoInherit.Checked = projectInfo.IsUnique == false;
                        rdoUnique.Enabled  = false;
                        rdoInherit.Enabled = false;
                    }

                    if (projectInfo.IsWorkspaceExisting == false)
                    {
                        wsTypeNew      = "checked disabled=\"true\"";
                        wsTypeExisting = " disabled=\"true\"";
                    }
                    else if (projectInfo.IsWorkspaceExisting == true)
                    {
                        wsTypeNew      = " disabled=\"true\"";
                        wsTypeExisting = "checked disabled=\"true\"";
                        Page.RegisterStartupScript("existingws", "<script>existingWorkspace();</script>");
                    }
                    break;
                }
            }
        }
 protected void AddList_Click(object sender, EventArgs e)
 {
     SPUtility.Redirect("/epmlive/SetupListMapping.aspx", SPRedirectFlags.RelativeToLayoutsPage,
                        HttpContext.Current);
 }
Exemplo n.º 5
0
 public static void LogError(Exception ex, bool transferToErrorPage)
 {
     LogError(ex);
     SPUtility.TransferToErrorPage(ex.Message);
 }
Exemplo n.º 6
0
        private void ProcessList(SPList list)
        {
            if (FilterCheck.Checked)
            {
                if (!Helper.Instance.IsUrlStartingWith(list.ParentWeb.Url, SquadronContext.Url))
                {
                    return;
                }
            }

            if (UniquePermissionsCheck.Checked)
            {
                if (!list.HasUniqueRoleAssignments)
                {
                    _discardedCount++;
                    return;
                }
            }

            if (list.Hidden)
            {
                if (!IncludeHiddenCheck.Checked)
                {
                    _discardedCount++;
                    return;
                }
            }

            string type = "List";

            if (list is SPDocumentLibrary)
            {
                type = "Library";
            }

            string permissionType = GetPermissionType(list);

            var pinfo = new PermissionInfo()
            {
                Type           = type,
                Title          = list.Title,
                Url            = SPUtility.GetFullUrl(list.ParentWeb.Site, list.DefaultViewUrl),
                PermissionType = permissionType
            };

            _result.Add(pinfo);

            if (!permissionType.Equals("UNIQUE"))
            {
                if (!ExpandInheritedCheck.Checked)
                {
                    _result[_result.Count - 1].RoleAssignments = GetPermissionParentUrl(list.ParentWeb);
                    return;
                }
            }


            string roleAssignment = string.Empty;
            int    count          = 0;

            foreach (SPRoleAssignment rolea in list.RoleAssignments)
            {
                roleAssignment = rolea.Member.ToString();

                string permissionLevels = string.Empty;
                foreach (SPRoleDefinition roledef in rolea.RoleDefinitionBindings)
                {
                    permissionLevels += roledef.Name + "; ";
                }

                _result.Add(new PermissionInfo()
                {
                    RoleAssignments = roleAssignment, PermissionLevels = permissionLevels, UsersInGroup = GetUsersInGroup(roleAssignment, list.ParentWeb)
                });
                count++;
            }

            if (count == 0)
            {
                _result.Add(new PermissionInfo()
                {
                    RoleAssignments = "(no assignments)"
                });
            }
        }
Exemplo n.º 7
0
 protected void cancelButton_OnClick(object sender, EventArgs e)
 {
     SPUtility.Redirect("settings.aspx", SPRedirectFlags.RelativeToLayoutsPage, Context);
 }
        private void GotoBackToSettingsPage()
        {
            string queryStr = string.Format("List={0}", this.ListId);

            SPUtility.Redirect("listedit.aspx", SPRedirectFlags.Static | SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current, queryStr);
        }
Exemplo n.º 9
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);
            }
        }
        //protected override bool RequireSiteAdministrator
        //{
        //    get { return true; }
        //}

        protected override void OnLoad(EventArgs e)
        {
            // get user info
            string userName       = this.Request.QueryString["USERNAME"];
            string token          = this.Request.QueryString["token"];
            string linkExpireTime = Request.QueryString["linkExpireTime"];
            string emailInLower   = Request.QueryString["email"].Trim().ToLower();
            //SPUser spuser = null;
            //try
            //{
            //    spuser = this.Web.AllUsers[Utils.EncodeUsername(userName)];
            //}
            //catch
            //{

            //}
            MembershipUser user = Utils.BaseMembershipProvider().GetUser(userName, false);

            if (user != null)
            {
                if (!Page.IsPostBack)
                {
                    // load user props
                    //if (spuser != null)
                    //{
                    //    txtEmail.Text = spuser.Email;
                    //    txtFullName.Text = spuser.Name;
                    //}
                    //else
                    //{
                    txtEmail.Text    = user.Email;
                    txtFullName.Text = user.UserName;
                    //}
                    txtUsername.Text = user.UserName;
                    isActive.Checked = user.IsApproved;
                    isLocked.Checked = user.IsLockedOut;
                    isLocked.Enabled = user.IsLockedOut;

                    //if (string.Concat(user.UserName.ToLower(), user.Email.ToLower(), MyCustomMessageHandler.SecretGuid,linkExpireTime).GetHashCode().ToString().Equals(token))
                    if (string.Concat(user.UserName.ToLower(), emailInLower, MyCustomMessageHandler.SecretGuid, linkExpireTime).GetHashCode().ToString().Equals(token))
                    {
                        if (DateTime.UtcNow.Ticks > long.Parse(linkExpireTime))
                        {
                            SPUtility.TransferToErrorPage(LocalizedString.GetGlobalString("MyResource", "LinkExpired"));
                        }

                        user.Email      = emailInLower;
                        user.Comment    = MyCustomMessageHandler.OneTimeDynamicPassword(user.UserName);
                        user.IsApproved = true;
                        Utils.BaseMembershipProvider().UpdateUser(user);
                        //TODO:这里还要加个WorkItemTimerJob, 用来同步membership Email 变化到SharePoint UserInfoList

                        //SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource | SPRedirectFlags.DoNotEndResponse, this.Context);
                        //string SignInUrl = Encoding.Default.GetString(Convert.FromBase64String(Request.QueryString["SignInUrl"]));

                        //SPUtility.Redirect(SignInUrl, SPRedirectFlags.DoNotEndResponse, this.Context); ;
                        //Uri SignIn = new Uri(SignInUrl, UriKind.RelativeOrAbsolute);
                        //string path;
                        //string query;
                        //if (SignIn.IsAbsoluteUri)
                        //{
                        //    path = SignIn.GetLeftPart(UriPartial.Path);
                        //    query = SignIn.Query;
                        //}
                        //else
                        //{
                        //    int num = SignInUrl.IndexOf('?');
                        //    path = num < 0 ? SignInUrl : SignInUrl.Substring(0, num);
                        //    query = num < 0 ? string.Empty : SignInUrl.Substring(num + 1, SignInUrl.Length - num - 1);
                        //}

                        //FBADiagnosticsService.Local.WriteTrace(0, FBADiagnosticsService.FBADiagnosticsCategory.General, Microsoft.SharePoint.Administration.TraceSeverity.Verbose, string.Concat("RedirectTo:", SignInUrl, ";   Path:", path, ";   QueryString:", query));
                        SPUtility.Redirect(this.Context.Request.RawUrl, SPRedirectFlags.UseSource | SPRedirectFlags.DoNotEndResponse, this.Context);

                        //Response.Redirect(SignInUrl);
                    }
                    else
                    {
                        SPUtility.TransferToErrorPage(LocalizedString.GetGlobalString("MyResource", "InvalidToken"));
                    }
                }
            }
            else
            {
                SPUtility.TransferToErrorPage(LocalizedString.GetGlobalString("FBAPackWebPages", "UserNotFound"));
            }
        }
 public object ExecuteRegisteredProxyOperation(string assemblyName, string typeName, SPProxyOperationArgs args)
 {
     return(SPUtility.ExecuteRegisteredProxyOperation(assemblyName, typeName, args));
 }
 protected void OnDeleteUser(object sender, EventArgs e)
 {
     SPUtility.Redirect(string.Format("FBA/Management/UserDelete.aspx?UserName={0}&Source={1}", this.Request.QueryString["USERNAME"], SPHttpUtility.UrlKeyValueEncode(SPUtility.OriginalServerRelativeRequestUrl)), SPRedirectFlags.RelativeToLayoutsPage, this.Context);
 }
        //这个没用,可以注释掉,Onload 成功后直接就 Redirect 掉了 ,除非以后成功后还容许在这个界面上设置一些用户属性
        protected void OnSubmit(object sender, EventArgs e)
        {
            // get user info
            string userName = this.Request.QueryString["USERNAME"];
            SPUser spuser   = null;

            // This could be done with EnsureUsers, which won't throw an exception if the user hasn't logged on to the site.
            try
            {
                spuser = this.Web.AllUsers[Utils.EncodeUsername(userName)];
            }
            catch
            {
            }
            MembershipUser user = Utils.BaseMembershipProvider().GetUser(userName, false);

            // check user exists
            if (user != null)
            {
                try
                {
                    // TODO: If we want the Email to be used for the user account, we need to delete the user and create a new one with the new email address.
                    // This will mean we need to iterate over the groups that the user is a member of, in all site collections in all web apps, and add the new user
                    // to those groups.  In the meantime, we allow the email to be changed, but this won't update the account username.

                    // update membership provider info
                    user.Email      = txtEmail.Text;
                    user.IsApproved = isActive.Checked;

                    //Unlock Account
                    if (user.IsLockedOut && !isLocked.Checked)
                    {
                        user.UnlockUser();
                    }
                    try
                    {
                        Utils.BaseMembershipProvider().UpdateUser(user);
                    }
                    catch (System.Configuration.Provider.ProviderException ex)
                    {
                        lblMessage.Text = ex.Message;
                        return;
                    }


                    // update sharepoint user info
                    if (spuser != null)
                    {
                        spuser.Email = txtEmail.Text;
                        spuser.Name  = txtFullName.Text;
                        spuser.Update();
                    }

                    SPUtility.Redirect("FBA/Management/UsersDisp.aspx", SPRedirectFlags.RelativeToLayoutsPage | SPRedirectFlags.UseSource, this.Context);
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex, true);
                }
            }
            else
            {
                SPUtility.TransferToErrorPage(LocalizedString.GetGlobalString("FBAPackWebPages", "UserNotFound"));
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Clear all session and redirect home page
 /// </summary>
 protected void OnLogout()
 {
     UserPermission.SetEmployeeInfo(null);
     //Response.Redirect(StringConstant.PageLoginURL);
     SPUtility.Redirect(StringConstant.PageLoginURL, SPRedirectFlags.DoNotEndResponse | SPRedirectFlags.Trusted, HttpContext.Current);
 }
        private string GetWebProperty(string val, string opt)
        {
            string[] tmp;

            switch (val)
            {
            case "id":
            case "guid":
                return(web.ID.ToString("B").ToUpper());

            case "name":
                return(web.Name);

            case "title":
                return(web.Title);

            case "description":
                return(web.Description);

            case "authenticationmode":
                return(web.AuthenticationMode.ToString());

            case "localename":
                return(web.Locale.Name);

            case "localelcid":
                return(web.Locale.LCID.ToString());

            case "lcid":
                return(web.Language.ToString());

            case "zone":
                return(web.Site.Zone.ToString());

            case "folderurl":
                return(System.IO.Path.GetDirectoryName(this.Context.Request.Url.AbsolutePath).Replace("\\", "/"));

            case "folderurlfull":
                return(SPUtility.GetUrlDirectory(this.Context.Request.Url.ToString()));

            case "weburl":
                return(web.ServerRelativeUrl);

            case "weburlfull":
                return(web.Url);

            case "siteurl":
                return(web.Site.ServerRelativeUrl);

            case "siteurlfull":
                return(web.Site.Url);

            case "urlscheme":
                return(this.Context.Request.Url.Scheme);

            case "urlhost":
                return(this.Context.Request.Url.Host);

            case "layoutsurl":
                return((web.ServerRelativeUrl + "/_layouts").Replace("//", "/"));

            case "layoutsurlfull":
                return(web.Url + "/_layouts");

            case "clientname":
            case "clientnamefull":
                try
                {
                    string pcname = System.Net.Dns.GetHostEntry(Context.Request.ServerVariables["remote_addr"]).HostName;
                    if (val == "clientname")
                    {
                        tmp = pcname.Split(new Char[] { '.' });
                        return(tmp[0]);
                    }
                    else
                    {
                        return(pcname);
                    }
                }
                catch { }
                return("?");

            case "clientip":
                try
                {
                    return(Context.Request.ServerVariables["remote_addr"]);
                }
                catch {
                    return("?");
                }

            case "servername":
                return(Environment.MachineName);

            case "serverip":
                return(Context.Request.ServerVariables["local_addr"]);

            case "osversion":
                return(Environment.OSVersion.VersionString);

            case "date":
                return(dtNow.Date.ToShortDateString());

            case "time":
                return(dtNow.ToShortTimeString());

            case "datetime":
                return(dtNow.ToString());

            case "username":
                return(user.Name);

            case "useremail":
            case "usermail":
                return(user.Email);

            case "userloginfull":
                return(user.LoginName);

            case "userlogin":
            case "userdomain":
                tmp = user.LoginName.Split(new char[] { '\\', '|' });
                if (tmp.Length >= 2)
                {
                    if (val == "userlogin")
                    {
                        return(tmp[1]);
                    }
                    else
                    {
                        return(tmp[0]);
                    }
                }
                else
                {
                    return("??");
                }

            case "issiteadmin":
                return(web.UserIsSiteAdmin.ToString());

            case "ismemberofgroup":
                try
                {
                    SPGroup grp = web.Groups[opt];
                    return(web.IsCurrentUserMemberOfGroup(grp.ID).ToString());
                }
                catch
                {
                    return(false.ToString());
                }

            default:
                return(string.Format("### unknow value: {0} ###", val));
            }
        }
Exemplo n.º 16
0
        public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext)
        {
            var modelHost      = modelHostContext.ModelHost;
            var model          = modelHostContext.Model;
            var childModelType = modelHostContext.ChildModelType;
            var action         = modelHostContext.Action;

            var webModelHost = modelHost.WithAssertAndCast <WebModelHost>("modelHost", value => value.RequireNotNull());
            var web          = webModelHost.HostWeb;

            var listDefinition = model as ListDefinition;

            if (web != null && listDefinition != null)
            {
                // This is very important line ->  adding new 'fake list'
                //
                // Nintex workflow deployment web service updates the list, so that version of the list becomes +4
                // Current SPWeb has not been updated, current list will be 4 versions behind so you will have 'Save conflict' exception
                //
                // We try to add new list, so SPListCollection is invalidated.
                // Surely, we won't save this list.
                try
                {
                    var tmpListId = web.Lists.Add(Guid.NewGuid().ToString(), string.Empty, Microsoft.SharePoint.SPListTemplateType.GenericList);
                    var tmpList   = web.Lists[tmpListId];
                    tmpList.Delete();
                }
                catch (Exception)
                {
                }

                var list = web.GetList(SPUtility.ConcatUrls(web.ServerRelativeUrl, listDefinition.GetListUrl()));

                var listModelHost = new ListModelHost
                {
                    HostList = list
                };

                if (childModelType == typeof(ModuleFileDefinition))
                {
                    var folderModelHost = new FolderModelHost
                    {
                        CurrentLibrary       = list as SPDocumentLibrary,
                        CurrentLibraryFolder = list.RootFolder,

                        CurrentList     = (list as SPDocumentLibrary != null) ? null : list,
                        CurrentListItem = null,
                    };

                    action(folderModelHost);
                }
                else if (childModelType == typeof(FolderDefinition))
                {
                    var folderModelHost = new FolderModelHost
                    {
                        CurrentLibrary       = list as SPDocumentLibrary,
                        CurrentLibraryFolder = list.RootFolder,

                        CurrentList     = (list as SPDocumentLibrary != null) ? null : list,
                        CurrentListItem = null,
                    };

                    action(folderModelHost);
                }
                else if (typeof(PageDefinitionBase).IsAssignableFrom(childModelType))
                {
                    var folderModelHost = new FolderModelHost
                    {
                        CurrentLibrary       = list as SPDocumentLibrary,
                        CurrentLibraryFolder = list.RootFolder,

                        CurrentList     = (list as SPDocumentLibrary != null) ? null : list,
                        CurrentListItem = null,
                    };

                    action(folderModelHost);
                }
                else
                {
                    action(listModelHost);
                }

                if (listModelHost.ShouldUpdateHost)
                {
                    list.Update();
                }
            }
            else
            {
                action(modelHost);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Browser detection and redirecting to error page
            if (Request.Browser.Browser.ToLower() == "ie" && Convert.ToDouble(Request.Browser.Version) < 7)
            {
                SPUtility.TransferToErrorPage("To view this report use later versions of IE 6.0");
            }
            else
            {
                try
                {
                    string SiteUrl = MyUtilities.ProjectServerInstanceURL(SPContext.Current);

                    var Resource_Svc = new Resource();
                    var Project_Svc  = new Project();

                    Resource_Svc.UseDefaultCredentials = true;
                    Project_Svc.UseDefaultCredentials  = true;

                    Resource_Svc.Url = SiteUrl + "/_vti_bin/psi/resource.asmx";
                    Project_Svc.Url  = SiteUrl + "/_vti_bin/psi/project.asmx";

                    Resource_Svc.AllowAutoRedirect = true;
                    Project_Svc.AllowAutoRedirect  = true;

                    if (MyUtilities.IndividualPages)
                    {
                        LnkConfigButton.PostBackUrl = SiteUrl + "/_layouts/ITXProjectGovernanceReport/ITXPGReport.aspx";
                    }
                    else
                    {
                        LnkConfigButton.Visible = false;
                    }

                    // setting current user uid
                    LblCurUserUId.Text = Resource_Svc.GetCurrentUserUid().ToString();

                    // For Group Repeater control

                    var GroupTable = new DataTable();
                    GroupTable.Columns.Add("title");
                    GroupTable.Columns.Add("grpid");

                    // impersonation here
                    try
                    {
                        var wik = WindowsIdentity.Impersonate(IntPtr.Zero);
                    }
                    catch (Exception)
                    {
                    }

                    MyUtilities.ModifyConnectionString(SiteUrl);

                    using (IObjectScope scope = ObjectScopeProvider1.GetNewObjectScope())
                    {
                        // creating the user account into db if not exists
                        List <Users> userses = (from c in scope.GetOqlQuery <Users>().ExecuteEnumerable()
                                                where c.ResourceUID.Equals(LblCurUserUId.Text)
                                                select c).ToList();
                        if (userses.Count == 0)
                        {
                            scope.Transaction.Begin();
                            var new_user = new Users();
                            new_user.ResourceUID = LblCurUserUId.Text;
                            scope.Add(new_user);
                            scope.Transaction.Commit();

                            userses = (from c in scope.GetOqlQuery <Users>().ExecuteEnumerable()
                                       where c.ResourceUID.Equals(LblCurUserUId.Text)
                                       select c).ToList();
                        }

                        List <Groups> groups = (from c in scope.GetOqlQuery <Users>().ExecuteEnumerable()
                                                from d in c.groups
                                                where
                                                c.ResourceUID.Equals(LblCurUserUId.Text) &&
                                                !d.UID.Equals(Guid.Empty.ToString())
                                                select d).ToList();
                        foreach (var group in groups)
                        {
                            var new_row = GroupTable.NewRow();
                            new_row["title"] = group.name;
                            new_row["grpid"] = group.UID;
                            GroupTable.Rows.Add(new_row);
                        }

                        RptrGroupnames.DataSource = GroupTable;
                        RptrGroupnames.DataBind();

                        // For Project name Repeater Control
                        var ProjectTable = MyUtilities.GetProjects_DataTable(SiteUrl, new Guid(LblCurUserUId.Text));

                        groups = (from c in scope.GetOqlQuery <Users>().ExecuteEnumerable()
                                  from d in c.groups
                                  where c.ResourceUID.Equals(LblCurUserUId.Text) && d.UID.Equals(Guid.Empty.ToString())
                                  select d).ToList();

                        if (groups.Count == 0)
                        {
                            if (userses.Count > 0)
                            {
                                scope.Transaction.Begin();
                                var new_group = new Groups();
                                new_group.name = "Not Grouped.";
                                new_group.UID  = Guid.Empty.ToString();
                                userses[0].groups.Add(new_group);
                                scope.Add(userses[0]);
                                scope.Transaction.Commit();
                            }
                            groups = (from c in scope.GetOqlQuery <Users>().ExecuteEnumerable()
                                      from d in c.groups
                                      where
                                      c.ResourceUID.Equals(LblCurUserUId.Text) &&
                                      d.UID.Equals(Guid.Empty.ToString())
                                      select d).ToList();
                        }

                        // Checking and adding missed projects to the user
                        foreach (DataRow row in ProjectTable.Rows)
                        {
                            var count = (from c in scope.GetOqlQuery <Users>().ExecuteEnumerable()
                                         from d in c.groups
                                         from f in d.projects
                                         where
                                         c.ResourceUID.Equals(LblCurUserUId.Text) &&
                                         f.uid.Equals(row["ProjectUID"].ToString())
                                         select e).Count();
                            if (count == 0 && groups.Count > 0)
                            {
                                scope.Transaction.Begin();
                                var new_proj_row = new Projects();
                                new_proj_row.name = row["Title"].ToString();
                                new_proj_row.uid  = row["ProjectUID"].ToString();
                                groups[0].projects.Add(new_proj_row);
                                scope.Add(groups[0]);
                                scope.Transaction.Commit();
                            }
                        }

                        RptrProjectnames.DataSource = (from c in scope.GetOqlQuery <Users>().ExecuteEnumerable()
                                                       from d in c.groups
                                                       from f in d.projects
                                                       where
                                                       c.ResourceUID.Equals(LblCurUserUId.Text) &&
                                                       d.UID.Equals(Guid.Empty.ToString())
                                                       select f).AsEnumerable();
                        RptrProjectnames.DataBind();
                    }
                }
                catch (Exception ex)
                {
                    MyUtilities.ErrorLog("Error at Project Group Congure load due to " + ex.Message,
                                         EventLogEntryType.Error);
                    if (MyUtilities.DevelopMode)
                    {
                        Response.Write(ex.Message);
                    }
                }
            }
        }
        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)
                            {
                            }
                        }
                    }
                });
            }
        }
Exemplo n.º 19
0
        protected void OK_Click(object sender, EventArgs e)
        {
            try
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;
                SPAdministrationWebApplication caWebApp = SPAdministrationWebApplication.Local;
                AppData.Local.Entries[AppData.SELECTED_INDEX] = lstSchedule.SelectedIndex.ToString();
                AppData.Local.Update();

                //Delete any existing jobs
                string jobName = "Check License";
                foreach (SPJobDefinition job in caWebApp.JobDefinitions)
                {
                    if (job.Name.ToUpper().Equals(jobName.ToUpper()))
                    {
                        job.Delete();
                    }
                }

                //Schedule new job
                switch (lstSchedule.SelectedIndex)
                {
                case 1:    //Immediate
                    SPOneTimeSchedule schedule1 = new SPOneTimeSchedule(DateTime.Now);
                    LicenseChecker    newJob1   = new LicenseChecker(jobName, caWebApp);
                    newJob1.Schedule = schedule1;
                    newJob1.Update();
                    break;

                case 2:    //Daily
                    SPDailySchedule schedule2 = new SPDailySchedule();
                    schedule2.BeginHour = 2;
                    schedule2.EndHour   = 6;
                    LicenseChecker newJob2 = new LicenseChecker(jobName, caWebApp);
                    newJob2.Schedule = schedule2;
                    newJob2.Update();
                    break;

                case 3:    //Weekly
                    SPWeeklySchedule schedule3 = new SPWeeklySchedule();
                    schedule3.BeginDayOfWeek = DayOfWeek.Saturday;
                    schedule3.EndDayOfWeek   = DayOfWeek.Saturday;
                    schedule3.BeginHour      = 2;
                    schedule3.EndHour        = 6;
                    LicenseChecker newJob3 = new LicenseChecker(jobName, caWebApp);
                    newJob3.Schedule = schedule3;
                    newJob3.Update();
                    break;

                case 4:    //Monthly
                    SPMonthlySchedule schedule4 = new SPMonthlySchedule();
                    schedule4.BeginDay  = 1;
                    schedule4.EndDay    = 1;
                    schedule4.BeginHour = 2;
                    schedule4.EndHour   = 6;
                    LicenseChecker newJob4 = new LicenseChecker(jobName, caWebApp);
                    newJob4.Schedule = schedule4;
                    newJob4.Update();
                    break;
                }

                SPContext.Current.Web.AllowUnsafeUpdates = false;
                SPUtility.Redirect(caWebApp.Sites[0].Url, SPRedirectFlags.Default, HttpContext.Current);
            }
            catch (Exception x)
            {
                lblMessages.Text = x.Message;
            }
        }
Exemplo n.º 20
0
 public void AddEqual(Guid fieldId, DateTime value)
 {
     this.AddEqual(fieldId, SPUtility.CreateISO8601DateTimeFromSystemDateTime(value), "DateTime");
 }
Exemplo n.º 21
0
 protected void Cancel_Click(object sender, EventArgs e)
 {
     SPUtility.Redirect(Helper.GetListSettingsURL(SPContext.Current.List), SPRedirectFlags.Default, HttpContext.Current);
 }
Exemplo n.º 22
0
 public void AddNotEqual(string name, DateTime value)
 {
     this.AddNotEqual(name, SPUtility.CreateISO8601DateTimeFromSystemDateTime(value), "DateTime");
 }
Exemplo n.º 23
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            bool success = true;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Hashtable hshProps = new Hashtable();
                hshProps.Add("IDColumn", ddlIDColumn.SelectedValue);
                hshProps.Add("SPColumn", ddlSPColumn.SelectedValue);
                if (ddlSharePointMatch.SelectedValue == "")
                {
                    hshProps.Add("ItemMatch", "");
                }
                else
                {
                    hshProps.Add("ItemMatch", ddlSharePointMatch.SelectedValue + "|" + ddlIntegrationMatch.SelectedValue);
                }

                hshProps.Add("SecMatch", ddlSecMatch.SelectedValue);

                intcore.SaveProperties(intlistid, hshProps);

                hshProps = new Hashtable();
                hshProps.Add("intlistid", intlistid);
                intcore.ExecuteQuery("Delete from INT_COLUMNS where INT_LIST_ID=@intlistid", hshProps, false);

                foreach (DropDownList ddl in ArrControls)
                {
                    if (ddl.SelectedValue != "")
                    {
                        hshProps = new Hashtable();
                        hshProps.Add("intlistid", intlistid);
                        hshProps.Add("SharePointColumn", ddl.ID);
                        hshProps.Add("IntegrationColumn", ddl.SelectedValue);

                        intcore.ExecuteQuery("INSERT INTO INT_COLUMNS (INT_LIST_ID, SharePointColumn, IntegrationColumn) VALUES (@intlistid, @SharePointColumn, @IntegrationColumn)", hshProps, false);
                    }
                }



                if (Request["wizard"] == "1")
                {
                    hshProps = new Hashtable();
                    hshProps.Add("intlistid", intlistid);

                    string message = "";


                    if (intcore.InstallIntegration(intlistid, new Guid(Request["List"]), out message))
                    {
                        intcore.ExecuteQuery("UPDATE INT_LISTS set active=1 where INT_LIST_ID=@intlistid", hshProps, true);
                    }
                    else
                    {
                        success          = false;
                        lblError.Text    = message + "<br>";
                        lblError.Visible = true;
                    }
                }

                if (chkCleanup.Checked)
                {
                    intcore.ExecuteQuery("UPDATE INT_LISTS set lastsynch=null where INT_LIST_ID=@intlistid", hshProps, true);
                }

                intcore.CloseConnection(true);
            });
            if (success)
            {
                if (Request["ret"] == "Manage")
                {
                    SPUtility.Redirect("epmlive/integration/manage.aspx", SPRedirectFlags.RelativeToLayoutsPage, System.Web.HttpContext.Current);
                }
                else
                {
                    SPUtility.Redirect("epmlive/integration/integrationlist.aspx?LIST=" + Request["List"], SPRedirectFlags.RelativeToLayoutsPage, System.Web.HttpContext.Current);
                }
            }
        }
Exemplo n.º 24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String teamSiteCollectionURL = WBFarm.Local.TeamSitesSiteCollectionUrl;

            SPUtility.Redirect(teamSiteCollectionURL + "/_layouts/WorkBoxFramework/TeamManagement.aspx", SPRedirectFlags.Static, Context);
        }
Exemplo n.º 25
0
 public static string GetAbsoluteURL(SPWeb web, string path)
 {
     return(SPUtility.ConcatUrls(web.Url, path));
 }
Exemplo n.º 26
0
        public static SPFolder AddFolder(this SPList list, string folderName, bool ignoreIfExists = false, string parentFolderUrl = "")
        {
            if (parentFolderUrl.StartsWith(list.RootFolder.ServerRelativeUrl))
            {
                parentFolderUrl = parentFolderUrl.Substring(list.RootFolder.ServerRelativeUrl.Length);
            }

            if (ignoreIfExists)
            {
                string folderUrl = SPUtility.ConcatUrls(list.RootFolder.ServerRelativeUrl, SPUtility.ConcatUrls(parentFolderUrl, folderName));

                SPFolder existingFolder = list.ParentWeb.GetFolder(folderUrl);
                if (existingFolder.Exists)
                {
                    return(existingFolder);
                }
            }

            SPListItem item = list.AddItem(SPUtility.ConcatUrls(list.RootFolder.ServerRelativeUrl, parentFolderUrl),
                                           SPFileSystemObjectType.Folder, folderName);

            item.Update();
            return(item.Folder);
        }
        public DataTable ExecuteQuery(string list, QueryInfo query)
        {
            CheckDisposed();

            //
            // Construct the query ready for consumption by the SharePoint Object Model, without <Query> root element.
            //
            StringBuilder     queryBuilder = new StringBuilder();
            XmlWriterSettings settings     = new XmlWriterSettings();

            settings.OmitXmlDeclaration = true;
            settings.ConformanceLevel   = ConformanceLevel.Auto;
            using (XmlWriter xw = XmlWriter.Create(queryBuilder, settings))
            {
                if (query.Where != null && query.Where.ChildNodes.Count != 0)
                {
                    query.Where.WriteTo(xw);
                }
                if (query.Order != null)
                {
                    query.Order.WriteTo(xw);
                }
                if (query.Grouping != null)
                {
                    query.Grouping.WriteTo(xw);
                }
                xw.Flush();
            }

            //
            // Make the SharePoint SPQuery object.
            //
            SPQuery q = new SPQuery();

            q.Query = queryBuilder.ToString();
            q.IncludeMandatoryColumns = false;
            q.DatesInUtc = true;

            //
            // Include projection fields if a projection clause has been parsed.
            //
            if (query.Projection != null)
            {
                q.ViewFields = query.Projection.InnerXml;
            }

            //
            // In case a row limit (Take) was found, set the limit on the query.
            //
            if (query.Top != null)
            {
                uint top = (uint)query.Top.Value;
                if (top == 0)
                {
                    return(new DataTable());
                }
                else
                {
                    q.RowLimit = top;
                }
            }

            //
            // Execute the query via the SPList object.
            //
            SPListItemCollection items;
            SPList lst = _site.RootWeb.Lists[list];

            try
            {
                items = lst.GetItems(q);
            }
            catch (Exception ex)
            {
                throw RuntimeErrors.ConnectionExceptionSp(_site.Url, ex);
            }

            DataTable tbl = new DataTable();

            tbl.Locale = CultureInfo.InvariantCulture;

            Debug.Assert(query.Projection != null);

            //
            // Set projection columns.
            //
            foreach (XmlNode node in query.Projection.ChildNodes)
            {
                tbl.Columns.Add(XmlConvert.DecodeName(node.Attributes["Name"].Value));
            }

            //
            // Retrieve data rows.
            //
            foreach (SPListItem item in items)
            {
                DataRow row = tbl.NewRow();
                foreach (DataColumn col in tbl.Columns)
                {
                    object o = item[col.ColumnName];
                    if (o is DateTime)
                    {
                        o = SPUtility.CreateISO8601DateTimeFromSystemDateTime((DateTime)o);
                    }
                    row[col] = o;
                }
                tbl.Rows.Add(row);
            }

            return(tbl);
        }
Exemplo n.º 28
0
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            //Ausführen des folgenden Codes nur, wenn ein XML vorhanden ist
            if (properties.ListItem.Name.Contains(".xml"))
            {
                //Durch folgende Zeile wird der enthaltene Code als SHAREPOINT\System ausgeführt und nicht unter dem Kontext des Benutzers, der den Auftrag unterschrieben hat
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    //Laden des aktuellen Webs; das ist nötig, um alle möglichen Operationen mit Bibliotheken und Elementen auszuführen
                    //dieses wird wieder geschlossen bzw. freigegeben, wenn die geschweifte Klammer von "using" geschlossen wird
                    using (SPSite site = new SPSite(properties.WebUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            string orderNumberCol      = "FileLeafRef";
                            string orderPdfLibraryName = "Auftragszettel-Archiv";
                            string attachmentClm       = "Anlagen/Begründung";
                            string attachmentVIClm     = "Anlagen/Begründung (VI)";
                            string attachmentDesc      = "öffnen";

                            SPListItem _currentItem = properties.ListItem;
                            string title            = _currentItem.Title.ToString();
                            string logFile          = @"C:\Bestellung\Logs\EventReceivers\OrderPdfArchived\" + title + ".log";
                            StringBuilder sb        = new StringBuilder();
                            sb.AppendLine("OrderForm " + title + " was added");
                            string orderNumber = Path.GetFileNameWithoutExtension(_currentItem[orderNumberCol].ToString());

                            SPList orderPdfLibrary = web.Lists.TryGetList(orderPdfLibraryName);
                            sb.AppendLine("Got list '" + orderPdfLibrary.Title + "'");
                            string folder = _currentItem.File.ParentFolder.ToString();
                            sb.AppendLine("Try getting folder '" + folder + "'...");
                            var nFolder = web.GetFolder(String.Format("{0}/Auftragsformular-Archiv/" + folder, web.Url));
                            sb.AppendLine("Got folder '" + nFolder.Url + "'");

                            sb.AppendLine("Querying for archived pdf... ");
                            SPQuery query = new SPQuery();
                            query.Query   = "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Text'>" + orderNumber + ".pdf</Value></Eq></Where>";
                            query.Folder  = nFolder;
                            SPListItemCollection queriedOrderPdfsItems = orderPdfLibrary.GetItems(query);
                            int count = queriedOrderPdfsItems.Count;
                            sb.AppendLine("Found archived pdfs... " + count.ToString());
                            if (count == 1)
                            {
                                sb.AppendLine("Changing URLs for one pdf... ");
                                string attachmentUrl = SPUtility.ConcatUrls(web.ServerRelativeUrl, "/_layouts/FormServer.aspx?XMLLocation=/bestellung/" + folder + "/" + orderNumber + ".xml&OpenIn=Browser&DefaultView=Anlagen&Source=/bestellung/SitePages/Schliessen.aspx");
                                SPFieldUrlValue url  = new SPFieldUrlValue();
                                url.Description      = attachmentDesc;
                                url.Url = attachmentUrl;

                                string attachmentUrlVI = SPUtility.ConcatUrls(web.ServerRelativeUrl, "/_layouts/FormServer.aspx?XMLLocation=/bestellung/" + folder + "/" + orderNumber + ".xml&OpenIn=Browser&DefaultView=AnlagenWeitergabe&Source=/bestellung/SitePages/Schliessen.aspx");
                                SPFieldUrlValue urlVI  = new SPFieldUrlValue();
                                urlVI.Description      = attachmentDesc;
                                urlVI.Url = attachmentUrlVI;

                                sb.AppendLine("Url for collumn " + attachmentClm + " : " + url.Url.ToString());
                                sb.AppendLine("Url for collumn " + attachmentVIClm + " : " + urlVI.Url.ToString());

                                foreach (SPListItem orderPdf in queriedOrderPdfsItems)
                                {
                                    sb.AppendLine("Iterating through found pdfs, should be only one...");
                                    using (EventReceiverManager eventReceiverManager = new EventReceiverManager(true))
                                    {
                                        sb.AppendLine("Try updating item " + orderPdf.Title.ToString() + "...");
                                        orderPdf[attachmentClm]   = url;
                                        orderPdf[attachmentVIClm] = urlVI;
                                        orderPdf.SystemUpdate(false);
                                        sb.AppendLine("Item updated");
                                    }
                                }
                            }
                            else
                            {
                                sb.AppendLine("There we're found more or less than one archived pdf... do nothing and quit");
                            }
                            File.AppendAllText(logFile, sb.ToString());
                        }
                    }
                });
            }
        }
Exemplo n.º 29
0
        public static void PopulaResources(this object obj)
        {
            if (IsCollection(obj))
            {
                if (obj is IEnumerable)
                {
                    var ctype = obj.GetType();
                    if (ctype == typeof(List <string>))
                    {
                        //TODO - How ugly this code (.)(.)
                        List <string> arr = obj as List <string>;

                        for (int i = 0; i < arr.Count; i++)
                        {
                            string resource = arr[i];
                            resource = resource.TrimStart("\r\n ".ToCharArray()).TrimEnd("\r\n ".ToCharArray());
                            if (resource.StartsWith("$Resources:"))
                            {
                                arr[i] = SPUtility.GetLocalizedString(resource, string.Empty, 1033);
                            }
                        }
                    }
                    else
                    {
                        foreach (object o in (obj as IEnumerable))
                        {
                            o.PopulaResources();
                        }
                    }
                }
                else
                {
                    // reflect over item
                }
            }
            var type       = obj.GetType();
            var properties = type.GetProperties();

            if (obj != null && obj is string)
            {
                string resource = obj.ToString();
                resource = resource.TrimStart("\r\n ".ToCharArray()).TrimEnd("\r\n ".ToCharArray());
                if (resource.StartsWith("$Resources:"))
                {
                    obj = SPUtility.GetLocalizedString(resource, string.Empty, 1033);
                }
            }
            else
            {
                foreach (var item in properties)
                {
                    try
                    {
                        var data = obj.GetPropertyValue(item.Name);
                        if (IsCollection(data))
                        {
                            data.PopulaResources();
                        }
                        if (data != null && data is string)
                        {
                            string resource = data.ToString();
                            resource = resource.TrimStart("\r\n ".ToCharArray()).TrimEnd("\r\n ".ToCharArray());
                            if (resource.StartsWith("$Resources:"))
                            {
                                obj.SetProperty(item.Name, SPUtility.GetLocalizedString(resource, string.Empty, 1033));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Exemplo n.º 30
0
 /// <summary>
 /// Gets the feature resource path.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <returns>The feature path</returns>
 private static string GetFeatureResourcePath(string name)
 {
     return(string.Format("{0}\\FEATURES\\{1}\\Resources",
                          SPUtility.GetGenericSetupPath("Template"),
                          name));
 }