예제 #1
0
파일: frmTest.cs 프로젝트: gpanayir/sffwk
        private void domainUsers1_ObjectDomainChangeEvent(ADUser user)
        {
            _CurrentUser = user;

            txtUserFullName.Text = string .Concat (user.FirstName , " " , user.LastName);
            txtUserName.Text = user.LoginName; 
        }
예제 #2
0
 private void domainUsers1_ObjectDomainDoubleClickEvent(ADUser user)
 {
     using (frmUserDetails frm = new frmUserDetails())
     {
         frm.user = user;
         frm.ShowDialog();
     }
 }
예제 #3
0
 private void CollectScreenData()
 {
     _aDUser = new ADUser();
     _aDUser.UserFullName = tbx_UserFullName.Text;
     _aDUser.UserName = tbx_UserName.Text;
     _aDUser.Password = tbx_Password.Text;
     _aDUser.Mobile = tbx_Mobile.Text;
     _aDUser.Phone = tbx_Phone.Text;
     _aDUser.Email = tbx_Email.Text;
     _aDUser.Address = tbx_Address.Text;
     _aDUser.GroupID = Convert.ToInt32(cbx_Group.SelectedValue);
 }
예제 #4
0
 public SharePointUrlResolver(ADUser groupAdUser)
 {
     ArgumentValidator.ThrowIfNull("groupADUser", groupAdUser);
     this.groupADUser = groupAdUser;
 }
예제 #5
0
        public void UpdateUser(UsersObject updateUser, bool isSuperOrResellerAdmin)
        {
            CPDatabase database  = null;
            ADGroup    ldapGroup = null;
            ADUser     ldapUser  = null;

            try
            {
                database = new CPDatabase();

                // Get the user from the database
                var foundUser = (from u in database.Users
                                 where u.UserPrincipalName == updateUser.UserPrincipalName
                                 select u).FirstOrDefault();

                if (foundUser == null)
                {
                    ThrowEvent(AlertID.FAILED, "Unknown user " + updateUser.UserPrincipalName);
                }
                else
                {
                    this.logger.Debug("Found user " + foundUser.UserPrincipalName + " in the database. Continuing...");

                    // Update the user values
                    foundUser.Firstname   = updateUser.Firstname;
                    foundUser.Middlename  = updateUser.Middlename;
                    foundUser.Lastname    = updateUser.Lastname;
                    foundUser.DisplayName = updateUser.DisplayName;
                    foundUser.Department  = updateUser.Department;

                    // Update user in Active Directory
                    ldapUser = new ADUser(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                    ldapUser.UpdateUser(updateUser, StaticSettings.AllowCustomNameAttribute);

                    // Only update these values if super admin or reseller admin is modifying the user
                    if (isSuperOrResellerAdmin)
                    {
                        this.logger.Debug("Super admin or reseller is updating user so we can check comapny admin permissions and reseller permissions");

                        foundUser.IsCompanyAdmin  = updateUser.IsCompanyAdmin;
                        foundUser.IsResellerAdmin = updateUser.IsResellerAdmin;

                        // Get permissions from database
                        var userPermissions = (from p in database.UserPermissions
                                               where p.UserID == foundUser.ID
                                               select p).FirstOrDefault();


                        // If the user is no longer a company admin then remove permissions from the database
                        if (userPermissions != null && !updateUser.IsCompanyAdmin)
                        {
                            this.logger.Debug("User " + updateUser.UserPrincipalName + " is no longer a comapny admin. Need to remove rights from database and security group");

                            database.UserPermissions.Remove(userPermissions);

                            // Remove from Admins@ security group
                            ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                            ldapGroup.RemoveMember("Admins@" + updateUser.CompanyCode, updateUser.UserPrincipalName, "upn");
                        }
                        else if (userPermissions != null && updateUser.IsCompanyAdmin)
                        {
                            this.logger.Debug("User " + updateUser.UserPrincipalName + " is a company admin. Need to update company admin rights in database.");

                            // If user permissions was found and the user is company admin then update the values
                            userPermissions.EnableExchange        = updateUser.EnableExchangePerm;
                            userPermissions.DisableExchange       = updateUser.DisableExchangePerm;
                            userPermissions.AddDomain             = updateUser.AddDomainPerm;
                            userPermissions.DeleteDomain          = updateUser.DeleteDomainPerm;
                            userPermissions.EnableAcceptedDomain  = updateUser.EnableAcceptedDomainPerm;
                            userPermissions.DisableAcceptedDomain = updateUser.DisableAcceptedDomainPerm;
                        }
                        else if (userPermissions == null && updateUser.IsCompanyAdmin)
                        {
                            this.logger.Debug("User " + updateUser.UserPrincipalName + " does not have any existing company admin rights. We need to add them to the database.");

                            // No existing permissions were found and we need to add to database
                            userPermissions                       = new UserPermission();
                            userPermissions.UserID                = foundUser.ID;
                            userPermissions.EnableExchange        = updateUser.EnableExchangePerm;
                            userPermissions.DisableExchange       = updateUser.DisableExchangePerm;
                            userPermissions.AddDomain             = updateUser.AddDomainPerm;
                            userPermissions.DeleteDomain          = updateUser.DeleteDomainPerm;
                            userPermissions.EnableAcceptedDomain  = updateUser.EnableAcceptedDomainPerm;
                            userPermissions.DisableAcceptedDomain = updateUser.DisableAcceptedDomainPerm;
                            database.UserPermissions.Add(userPermissions);

                            // Add to Admins@ security group
                            ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                            ldapGroup.AddMember("Admins@" + updateUser.CompanyCode, updateUser.UserPrincipalName, "upn");
                        }
                    }
                    else
                    {
                        this.logger.Debug("User making changes to " + updateUser.UserPrincipalName + " is not a super admin or reseller admin. We cannot update company admin or reseller admin permissions unless the user making changes is a super or reseller admin.");
                    }

                    // Update database
                    database.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                this.logger.Debug("Error updating user " + updateUser.UserPrincipalName, ex);
                ThrowEvent(AlertID.FAILED, ex.Message);
            }
            finally
            {
                if (ldapUser != null)
                {
                    ldapUser.Dispose();
                }

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

                if (database != null)
                {
                    database.Dispose();
                }
            }
        }
예제 #6
0
        internal static List <AdFolderData> GetUserElcFolders(MailboxSession session, ADUser aduser, List <ELCFolder> allAdFolders, bool getFoldersOnly, bool getOrgFoldersOnly)
        {
            if (allAdFolders == null || allAdFolders.Count == 0 || aduser == null)
            {
                return(null);
            }
            string                arg             = session.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString();
            ADSessionSettings     sessionSettings = ADSessionSettings.FromOrganizationIdWithoutRbacScopesServiceOnly(session.MailboxOwner.MailboxInfo.OrganizationId);
            IConfigurationSession tenantOrTopologyConfigurationSession = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(ConsistencyMode.FullyConsistent, sessionSettings, 258, "GetUserElcFolders", "f:\\15.00.1497\\sources\\dev\\infoworker\\src\\common\\ELC\\AdFolderReader.cs");
            ADObjectId            managedFolderMailboxPolicy           = aduser.ManagedFolderMailboxPolicy;

            if (managedFolderMailboxPolicy == null)
            {
                AdReader.Tracer.TraceDebug <string>(0L, "Mailbox '{0}' does not have an ELC Mailbox policy.", arg);
                return(null);
            }
            ManagedFolderMailboxPolicy managedFolderMailboxPolicy2 = tenantOrTopologyConfigurationSession.Read <ManagedFolderMailboxPolicy>(managedFolderMailboxPolicy);

            if (managedFolderMailboxPolicy2 == null)
            {
                AdReader.Tracer.TraceDebug <string, ADObjectId>(0L, "Mailbox '{0}' no matching ELC Mailbox policy for Template '{1}'.", arg, managedFolderMailboxPolicy);
                return(null);
            }
            MultiValuedProperty <ADObjectId> managedFolderLinks = managedFolderMailboxPolicy2.ManagedFolderLinks;
            List <AdFolderData> list = new List <AdFolderData>();

            using (MultiValuedProperty <ADObjectId> .Enumerator enumerator = managedFolderLinks.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    ADObjectId elcFolderId = enumerator.Current;
                    ELCFolder  elcfolder   = allAdFolders.Find((ELCFolder adFolder) => elcFolderId.ObjectGuid == adFolder.Id.ObjectGuid);
                    if (elcfolder == null)
                    {
                        throw new ELCNoMatchingOrgFoldersException(elcFolderId.DistinguishedName);
                    }
                    if (!getOrgFoldersOnly || elcfolder.FolderType == ElcFolderType.ManagedCustomFolder)
                    {
                        AdFolderData adFolderData = new AdFolderData();
                        adFolderData.LinkedToTemplate = true;
                        adFolderData.Synced           = false;
                        adFolderData.Folder           = elcfolder;
                        if (!getFoldersOnly)
                        {
                            adFolderData.FolderSettings = AdFolderReader.FetchFolderContentSettings(elcfolder);
                        }
                        list.Add(adFolderData);
                    }
                }
            }
            return(list);
        }
예제 #7
0
    protected void btnCreate_Click(object sender, EventArgs e)
    {
        CustomError passwordError = Utilities.CheckPassword(pwfPassword.Password, txtMANR.Text);

        if (!passwordError.HasErrors)
        {
            ADUser user = new ADUser(Utilities.RemoveExcessWhitespaces(txtMANR.Text.ToUpper()), Utilities.RemoveExcessWhitespaces(txtFirstname.Text), Utilities.RemoveExcessWhitespaces(txtLastname.Text), pwfPassword.Password, ddlOU.SelectedValue);

            DateTime?expires = null;
            if (!String.IsNullOrWhiteSpace(txtExpires.Text))
            {
                DateTime dt;
                if (DateTime.TryParseExact(txtExpires.Text, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
                {
                    expires = dt;
                }
            }

            user.DateExpires = expires;

            bool mustChangePassword = User.IsInRole("Admin") ? chkbxForceChangePassword.Checked : !pwfPassword.IsPasswordGenerated;

            CustomError userError = user.Save(mustChangePassword, false);

            if (!userError.HasErrors)
            {
                txtMANR.Text        = String.Empty;
                txtFirstname.Text   = String.Empty;
                txtLastname.Text    = String.Empty;
                txtExpires.Text     = String.Empty;
                ddlOU.SelectedIndex = 0;
                pwfPassword.GeneratePassword();
                SetMessage(String.Format("<a href=\"/EditADUser/{0}\">{0}</a> oprettet med password: {1}", user.AccountName, user.Password));
                hplPrint.NavigateUrl = String.Format("~/Print/{0}/{1}", user.AccountName, user.Password);
                hplPrint.Visible     = true;
                mailPassword         = user.Password;
                mailUsername         = user.AccountName;
                btnSendEmail.Text    = "Email koden til: 00" + user.AccountName + "@mil.dk ?";
                btnSendEmail.Visible = true;
            }
            else
            {
                switch (userError.ErrorList[0])
                {
                case CustomError.ErrorType.UserExists:
                    SetMessage("Brugeren eksisterer i forvejen", true);
                    break;

                case CustomError.ErrorType.OUDoesNotExist:
                    SetMessage("Der skete en fejl med Enhed. Venligst kontakt IT og oplys hvilken enhed du benyttede.", true);
                    break;

                case CustomError.ErrorType.UnknownError:
                    SetMessage("Der skete en ukendt fejl. Prøv igen og hvis fejlen fortsætter, kontakt da os.", true);
                    break;

                default:
                    break;
                }
            }
        }
        else
        {
            switch (passwordError.ErrorList[0])
            {
            case CustomError.ErrorType.PasswordLessThan8:
                SetMessage("Password skal være på minimum 8 tegn", true);
                break;

            case CustomError.ErrorType.PasswordIncludesAccount:
                SetMessage("Password må ikke indeholde dele af navnet", true);
                break;

            case CustomError.ErrorType.PasswordNotComplex:
                SetMessage("Passwordet opfylder ikke komplexitetskravene");
                break;

            default:
                break;
            }
        }
    }
예제 #8
0
        protected override void InternalValidate()
        {
            if (this.Identity != null && this.SharePointUrl != null)
            {
                base.WriteError(new InvalidOperationException(Strings.TestTeamMailboxConstraintError("Identity", "SharePointUrl")), ErrorCategory.InvalidOperation, null);
            }
            else if (this.Identity == null && this.SharePointUrl == null)
            {
                base.WriteError(new InvalidOperationException(Strings.TestTeamMailboxConstraintError("Identity", "SharePointUrl")), ErrorCategory.InvalidOperation, null);
            }
            if (this.UseAppTokenOnly && this.RequestorIdentity != null)
            {
                base.WriteError(new InvalidOperationException(Strings.TestTeamMailboxConstraintError("UseAppTokenOnly", "RequestorIdentity")), ErrorCategory.InvalidOperation, null);
            }
            ADObjectId adobjectId = null;

            base.TryGetExecutingUserId(out adobjectId);
            if (this.RequestorIdentity == null)
            {
                if (adobjectId == null)
                {
                    base.WriteError(new InvalidOperationException(Strings.CouldNotGetExecutingUser), ErrorCategory.InvalidOperation, null);
                }
                try
                {
                    this.requestor = (ADUser)base.GetDataObject(new RecipientIdParameter(adobjectId));
                    goto IL_145;
                }
                catch (ManagementObjectNotFoundException)
                {
                    if (this.UseAppTokenOnly && base.Organization != null)
                    {
                        this.requestor = null;
                        goto IL_145;
                    }
                    throw;
                }
            }
            this.requestor = (ADUser)base.GetDataObject(this.RequestorIdentity);
            if (adobjectId != this.requestor.Id)
            {
                this.additionalConstrainedIdentity = this.requestor.Id;
            }
IL_145:
            if (this.Identity != null)
            {
                base.InternalValidate();
                if (base.TMPrincipals.Count > 1)
                {
                    base.WriteError(new InvalidOperationException(Strings.MoreThanOneTeamMailboxes), ErrorCategory.InvalidOperation, null);
                }
                using (Dictionary <ADUser, ExchangePrincipal> .KeyCollection.Enumerator enumerator = base.TMPrincipals.Keys.GetEnumerator())
                {
                    if (enumerator.MoveNext())
                    {
                        ADUser aduser = enumerator.Current;
                        this.tmADObject = aduser;
                        if (this.tmADObject.SharePointUrl == null)
                        {
                            base.WriteError(new InvalidOperationException(Strings.TeamMailboxSharePointUrlMissing), ErrorCategory.InvalidOperation, null);
                        }
                    }
                }
            }
        }
예제 #9
0
 public ADUserInstance(ObjectInstance prototype, ADUser user, string ldap)
     : this(prototype, user)
 {
     m_ldap = ldap;
 }
예제 #10
0
 public OWAExtensionDataProvider(string domain, IRecipientSession adRecipientSession, ADSessionSettings adSessionSettings, bool isUserScope, ADUser mailboxOwner, string action, bool isDebug) : base(adSessionSettings, mailboxOwner, action)
 {
     this.domain             = domain;
     this.adRecipientSession = adRecipientSession;
     this.isUserScope        = isUserScope;
     this.isDebug            = isDebug;
 }
예제 #11
0
        internal InternalClientContext(ClientSecurityContext clientSecurityContext, IBudget budget, ExTimeZone timeZone, CultureInfo clientCulture, string messageId, ADUser adUser) : base(budget, timeZone, clientCulture, messageId)
        {
            if (clientSecurityContext == null)
            {
                throw new ArgumentNullException("clientSecurityContext");
            }
            this.clientSecurityContext     = clientSecurityContext;
            this.ownsClientSecurityContext = false;
            if (adUser != null)
            {
                this.adUser            = adUser;
                this.organizationId    = adUser.OrganizationId;
                this.adUserInitialized = true;
            }
            else
            {
                this.adUser            = null;
                this.adUserInitialized = false;
            }
            if (this.clientSecurityContext.UserSid != null)
            {
                this.identityForFilteredTracing = this.clientSecurityContext.UserSid.ToString();
            }
            SecurityAccessToken securityAccessToken = new SecurityAccessToken();

            this.clientSecurityContext.SetSecurityAccessToken(securityAccessToken);
            this.serializedSecurityContext = new SerializedSecurityContext(securityAccessToken);
        }
 public ExternalAuthenticationRequest(RequestLogger requestLogger, ExternalAuthentication externalAuthentication, ADUser user, SmtpAddress emailAddress, TokenTarget target, Offer offer)
 {
     this.requestLogger        = requestLogger;
     this.user                 = user;
     this.emailAddress         = emailAddress;
     this.target               = target;
     this.offer                = offer;
     this.securityTokenService = externalAuthentication.GetSecurityTokenService(user.OrganizationId);
 }
예제 #13
0
        protected override void WriteConfigXml(XmlWriter xmlFragment)
        {
            if (base.RequestedRecipient == null)
            {
                this.WriteErrorResponse(xmlFragment, "2", Strings.MobileSyncAddressNotFound.ToString(), string.Empty, base.RequestData, null, null);
                return;
            }
            if (base.RequestedRecipient.RecipientType != RecipientType.UserMailbox)
            {
                this.WriteErrorResponse(xmlFragment, "9", Strings.MobileSyncBadAddress.ToString(), base.RequestedRecipient.RecipientType.ToString(), base.RequestData, base.RequestedRecipient.DisplayName, base.RequestedRecipient.PrimarySmtpAddress.ToString());
                return;
            }
            ADUser            adUser            = base.RequestedRecipient as ADUser;
            ExchangePrincipal exchangePrincipal = Common.GetExchangePrincipal(adUser);

            if (exchangePrincipal == null)
            {
                this.WriteErrorResponse(xmlFragment, "1", Strings.ActiveDirectoryFailure.ToString(), base.RequestedRecipient.RecipientType.ToString(), base.RequestData, base.RequestedRecipient.DisplayName, base.RequestedRecipient.PrimarySmtpAddress.ToString());
                return;
            }
            string mobileName   = null;
            string certUrl      = null;
            string certTemplate = null;
            bool   certEnabled  = false;
            VariantConfigurationSnapshot configuration = exchangePrincipal.GetConfiguration();

            if (Common.SkipServiceTopologyInDatacenter(configuration))
            {
                Uri datacenterFrontEndEasUrl = FrontEndLocator.GetDatacenterFrontEndEasUrl();
                if (datacenterFrontEndEasUrl != null)
                {
                    mobileName = datacenterFrontEndEasUrl.ToString();
                }
            }
            else
            {
                ServiceTopology currentServiceTopology = ServiceTopology.GetCurrentServiceTopology("f:\\15.00.1497\\sources\\dev\\autodisc\\src\\Providers\\MobileSync\\Web\\MobileSyncProvider.cs", "WriteConfigXml", 376);
                Site            site = currentServiceTopology.GetSite(exchangePrincipal.MailboxInfo.Location.ServerFqdn, "f:\\15.00.1497\\sources\\dev\\autodisc\\src\\Providers\\MobileSync\\Web\\MobileSyncProvider.cs", "WriteConfigXml", 377);
                SiteCostComparer <MobileSyncService> comparer = new SiteCostComparer <MobileSyncService>(currentServiceTopology, site);
                MobileSyncService cheapest        = null;
                MobileSyncService cheapestToProxy = null;
                currentServiceTopology.ForEach <MobileSyncService>(delegate(MobileSyncService service)
                {
                    if (service.ClientAccessType == ClientAccessType.External)
                    {
                        if (service.ServerVersionNumber == exchangePrincipal.MailboxInfo.Location.ServerVersion && (cheapest == null || comparer.Compare(cheapest, service) > 0))
                        {
                            cheapest = service;
                            return;
                        }
                        if (cheapestToProxy == null || comparer.Compare(cheapestToProxy, service) > 0)
                        {
                            if (service.ServerVersionNumber > exchangePrincipal.MailboxInfo.Location.ServerVersion)
                            {
                                cheapestToProxy = service;
                                return;
                            }
                            ServerVersion serverVersion  = new ServerVersion(exchangePrincipal.MailboxInfo.Location.ServerVersion);
                            ServerVersion serverVersion2 = new ServerVersion(service.ServerVersionNumber);
                            if (serverVersion2.Major >= serverVersion.Major && serverVersion2.Minor >= serverVersion.Minor)
                            {
                                cheapestToProxy = service;
                            }
                        }
                    }
                }, "f:\\15.00.1497\\sources\\dev\\autodisc\\src\\Providers\\MobileSync\\Web\\MobileSyncProvider.cs", "WriteConfigXml", 388);
                if (cheapest == null && cheapestToProxy == null)
                {
                    this.WriteErrorResponse(xmlFragment, "1", Strings.ExternalUrlNotFound.ToString(), base.RequestedRecipient.RecipientType.ToString(), base.RequestData, base.RequestedRecipient.DisplayName, base.RequestedRecipient.PrimarySmtpAddress.ToString());
                    return;
                }
                if (cheapest == null || (cheapestToProxy != null && comparer.Compare(cheapest, cheapestToProxy) > 0))
                {
                    cheapest = cheapestToProxy;
                }
                mobileName   = cheapest.Url.ToString();
                certUrl      = cheapest.CertificateAuthorityUrl;
                certTemplate = cheapest.CertEnrollTemplateName;
                certEnabled  = cheapest.IsCertEnrollEnabled;
            }
            Common.StartEnvelope(xmlFragment);
            xmlFragment.WriteStartElement("Response", this.ResponseNs);
            xmlFragment.WriteElementString("Culture", this.ResponseNs, MobileSyncProvider.defaultCulture);
            this.WriteUserFragment(xmlFragment, base.RequestedRecipient.DisplayName, base.RequestedRecipient.PrimarySmtpAddress.ToString());
            xmlFragment.WriteStartElement("Action", this.ResponseNs);
            xmlFragment.WriteStartElement("Settings", this.ResponseNs);
            this.WriteServerFragment(xmlFragment, mobileName, certUrl, certTemplate, certEnabled);
            xmlFragment.WriteEndElement();
            this.WriteMailboxesFragment(xmlFragment, exchangePrincipal);
            xmlFragment.WriteEndElement();
            xmlFragment.WriteEndElement();
            Common.EndEnvelope(xmlFragment);
            Common.EventLog.LogEvent(AutodiscoverEventLogConstants.Tuple_InfoProvConfigurationResponse, Common.PeriodicKey, new object[]
            {
                (base.RequestData.LegacyDN == null) ? base.RequestData.EMailAddress : base.RequestData.LegacyDN
            });
            RequestDetailsLoggerBase <RequestDetailsLogger> .Current.AppendGenericInfo("MobileSyncConfigSuccess", base.RequestData.LegacyDN ?? base.RequestData.EMailAddress);
        }
 public CreateSiteCollectionTask(ADUser accessingUser, IRecipientSession adSession, Guid activityId) : base(accessingUser, adSession, activityId)
 {
 }
예제 #15
0
        protected override IConfigDataProvider CreateSession()
        {
            ADUser discoveryMailbox = MailboxDataProvider.GetDiscoveryMailbox(base.TenantGlobalCatalogSession);

            return(new UnifiedPolicySyncNotificationDataProvider(base.SessionSettings, discoveryMailbox, "Get-CompliancePolicySyncNotification"));
        }
예제 #16
0
        internal override MailAppsResult GetExchangeDiagnosticsInfoData(DiagnosableParameters argument)
        {
            MailAppsResult mailAppsResult = new MailAppsResult();
            string         text           = argument.Argument;

            if (!string.IsNullOrEmpty(text))
            {
                string value = null;
                string text2 = ",val=";
                int    num   = text.IndexOf(text2);
                if (num != -1)
                {
                    value = text.Substring(num + text2.Length);
                    text  = argument.Argument.Substring(0, num);
                }
                MailAppsArgument mailAppsArgument = new MailAppsArgument(text);
                if (mailAppsArgument.HasArgument("org") && mailAppsArgument.HasArgument("cmd"))
                {
                    bool              flag      = false;
                    string            argument2 = mailAppsArgument.GetArgument <string>("org");
                    ExchangePrincipal exchangePrincipal;
                    if (mailAppsArgument.HasArgument("usr"))
                    {
                        string            argument3  = mailAppsArgument.GetArgument <string>("usr");
                        ADSessionSettings adSettings = ADSessionSettings.RootOrgOrSingleTenantFromAcceptedDomainAutoDetect(argument2);
                        exchangePrincipal = ExchangePrincipal.FromProxyAddress(adSettings, argument3 + "@" + argument2, RemotingOptions.AllowCrossSite);
                    }
                    else
                    {
                        ADUser orgMailbox = OrgExtensionTable.GetOrgMailbox(argument2);
                        exchangePrincipal = ExchangePrincipal.FromADUser(orgMailbox, null);
                        flag = true;
                    }
                    using (MailboxSession mailboxSession = MailboxSession.OpenAsSystemService(exchangePrincipal, CultureInfo.CurrentCulture, "Client=WebServices"))
                    {
                        using (UserConfiguration folderConfiguration = UserConfigurationHelper.GetFolderConfiguration(mailboxSession, mailboxSession.GetDefaultFolderId(DefaultFolderType.Inbox), "ExtensionMasterTable", UserConfigurationTypes.XML, true, false))
                        {
                            using (Stream xmlStream = folderConfiguration.GetXmlStream())
                            {
                                if (string.Equals(mailAppsArgument.GetArgument <string>("cmd"), "set", StringComparison.OrdinalIgnoreCase) && num != -1)
                                {
                                    xmlStream.SetLength(0L);
                                    bool flag2 = string.IsNullOrEmpty(value);
                                    if (!flag2)
                                    {
                                        using (StreamWriter streamWriter = new StreamWriter(xmlStream, Encoding.UTF8))
                                        {
                                            streamWriter.Write(value);
                                        }
                                    }
                                    folderConfiguration.Save();
                                    if (flag)
                                    {
                                        OrgEmptyMasterTableCache.Singleton.Update(exchangePrincipal.MailboxInfo.OrganizationId, flag2);
                                    }
                                    mailAppsResult.Message = "Raw value saved.";
                                }
                                else
                                {
                                    using (StreamReader streamReader = new StreamReader(xmlStream, true))
                                    {
                                        mailAppsResult.RawMasterTable = streamReader.ReadToEnd();
                                        if (mailAppsArgument.HasArgument("len"))
                                        {
                                            int argument4 = mailAppsArgument.GetArgument <int>("len");
                                            if (argument4 > 0 && argument4 < mailAppsResult.RawMasterTable.Length)
                                            {
                                                mailAppsResult.RawMasterTable = mailAppsResult.RawMasterTable.Substring(0, argument4);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(mailAppsResult);
        }
예제 #17
0
 public IMessageComposer Build(ADUser recipient)
 {
     ArgumentValidator.ThrowIfNull("recipient", recipient);
     this.Initialize();
     return(new WelcomeToGroupMessageComposer(this, recipient, this.groupMailbox));
 }
예제 #18
0
        protected void ResolveDatabaseAndServer()
        {
            DatabaseIdParameter databaseIdParameter   = this.Database;
            ServerIdParameter   serverIdParameter     = this.Server ?? new ServerIdParameter();
            ActiveManager       activeManagerInstance = ActiveManager.GetActiveManagerInstance();

            if (this.Identity != null)
            {
                bool flag = false;
                if (this.isRunningLogonStatisticsTask)
                {
                    TIdentity tidentity            = this.Identity;
                    IEnumerable <Database> objects = tidentity.GetObjects <Database>(null, base.GlobalConfigSession);
                    foreach (Database item in objects)
                    {
                        this.databases.Add(item);
                    }
                    if (this.databases.Count > 0)
                    {
                        if (this.databases[0].Server == null)
                        {
                            string    name       = typeof(Database).Name;
                            TIdentity tidentity2 = this.Identity;
                            base.WriteError(new MdbAdminTaskException(Strings.ErrorInvalidObjectMissingCriticalProperty(name, tidentity2.ToString(), DatabaseSchema.Server.Name)), ErrorCategory.InvalidArgument, this.Identity);
                        }
                        DatabaseLocationInfo serverForDatabase = activeManagerInstance.GetServerForDatabase(this.databases[0].Guid);
                        serverIdParameter = ServerIdParameter.Parse(serverForDatabase.ServerFqdn);
                        if (string.IsNullOrEmpty(this.databases[0].ExchangeLegacyDN))
                        {
                            string    name2      = typeof(Database).Name;
                            TIdentity tidentity3 = this.Identity;
                            base.WriteError(new MdbAdminTaskException(Strings.ErrorInvalidObjectMissingCriticalProperty(name2, tidentity3.ToString(), DatabaseSchema.ExchangeLegacyDN.Name)), ErrorCategory.InvalidArgument, this.Identity);
                        }
                        this.identity = new MailboxId(this.databases[0].ExchangeLegacyDN);
                        flag          = true;
                    }
                }
                if (!flag)
                {
                    IIdentityParameter  id            = this.Identity;
                    IConfigDataProvider session       = this.readOnlyRecipientSession;
                    ObjectId            rootID        = null;
                    TIdentity           tidentity4    = this.Identity;
                    LocalizedString?    notFoundError = new LocalizedString?(Strings.ErrorMailboxNotFound(tidentity4.ToString()));
                    TIdentity           tidentity5    = this.Identity;
                    ADRecipient         adrecipient   = (ADRecipient)base.GetDataObject <ADRecipient>(id, session, rootID, notFoundError, new LocalizedString?(Strings.ErrorMailboxNotUnique(tidentity5.ToString())));
                    Guid       guid = Guid.Empty;
                    string     mailboxExchangeLegacyDn = null;
                    ADObjectId adobjectId = null;
                    if (string.IsNullOrEmpty(adrecipient.LegacyExchangeDN))
                    {
                        string    name3      = typeof(ADRecipient).Name;
                        TIdentity tidentity6 = this.Identity;
                        base.WriteError(new MdbAdminTaskException(Strings.ErrorInvalidObjectMissingCriticalProperty(name3, tidentity6.ToString(), ADRecipientSchema.LegacyExchangeDN.Name)), ErrorCategory.InvalidArgument, this.Identity);
                    }
                    ADUser                   aduser                   = adrecipient as ADUser;
                    ADSystemMailbox          adsystemMailbox          = adrecipient as ADSystemMailbox;
                    ADSystemAttendantMailbox adsystemAttendantMailbox = adrecipient as ADSystemAttendantMailbox;
                    ADPublicDatabase         adpublicDatabase         = adrecipient as ADPublicDatabase;
                    if (aduser != null)
                    {
                        if (this.isRunningMailboxStatisticsTask && aduser.RecipientTypeDetails == RecipientTypeDetails.AuditLogMailbox && !this.GetAuditLogMailboxStatistics())
                        {
                            TIdentity tidentity7 = this.Identity;
                            base.WriteError(new MdbAdminTaskException(Strings.RecipientNotFoundException(tidentity7.ToString())), ErrorCategory.InvalidArgument, null);
                        }
                        bool archiveMailboxStatistics = this.GetArchiveMailboxStatistics();
                        if (aduser.RecipientType == RecipientType.MailUser && !archiveMailboxStatistics)
                        {
                            base.WriteError(new MdbAdminTaskException(Strings.RecipientTypeNotValid(aduser.ToString())), (ErrorCategory)1003, this.Identity);
                        }
                        RecipientIdParameter recipientIdParameter = this.Identity as RecipientIdParameter;
                        if (this.isRunningMailboxStatisticsTask && recipientIdParameter != null && recipientIdParameter.RawMailboxGuidInvolvedInSearch != Guid.Empty && aduser.MailboxLocations != null)
                        {
                            IMailboxLocationInfo mailboxLocation = aduser.MailboxLocations.GetMailboxLocation(recipientIdParameter.RawMailboxGuidInvolvedInSearch);
                            if (mailboxLocation != null)
                            {
                                guid       = mailboxLocation.MailboxGuid;
                                adobjectId = mailboxLocation.DatabaseLocation;
                            }
                        }
                        if (guid == Guid.Empty || adobjectId == null)
                        {
                            if (archiveMailboxStatistics)
                            {
                                if (aduser.ArchiveGuid != Guid.Empty)
                                {
                                    if (aduser.ArchiveDomain != null)
                                    {
                                        base.WriteError(new MdbAdminTaskException(Strings.ErrorRemoteArchiveNoStats(aduser.ToString())), (ErrorCategory)1003, this.Identity);
                                    }
                                    else
                                    {
                                        guid       = aduser.ArchiveGuid;
                                        adobjectId = (aduser.ArchiveDatabase ?? aduser.Database);
                                    }
                                }
                                else
                                {
                                    base.WriteError(new MdbAdminTaskException(Strings.ErrorArchiveNotEnabled(aduser.ToString())), ErrorCategory.InvalidArgument, this.Identity);
                                }
                            }
                            else
                            {
                                guid       = aduser.ExchangeGuid;
                                adobjectId = aduser.Database;
                            }
                        }
                        mailboxExchangeLegacyDn = aduser.LegacyExchangeDN;
                    }
                    else if (adsystemMailbox != null)
                    {
                        guid = adsystemMailbox.ExchangeGuid;
                        mailboxExchangeLegacyDn = adsystemMailbox.LegacyExchangeDN;
                        adobjectId = adsystemMailbox.Database;
                    }
                    else if (adsystemAttendantMailbox != null)
                    {
                        guid = adsystemAttendantMailbox.Guid;
                        mailboxExchangeLegacyDn = adsystemAttendantMailbox.LegacyExchangeDN;
                        adobjectId = adsystemAttendantMailbox.Database;
                    }
                    else if (adpublicDatabase != null)
                    {
                        mailboxExchangeLegacyDn = adpublicDatabase.LegacyExchangeDN;
                        adobjectId = (ADObjectId)adpublicDatabase.Identity;
                    }
                    if (adobjectId == null)
                    {
                        string    name4      = adrecipient.GetType().Name;
                        TIdentity tidentity8 = this.Identity;
                        base.WriteError(new MdbAdminTaskException(Strings.ErrorInvalidObjectMissingCriticalProperty(name4, tidentity8.ToString(), IADMailStorageSchema.Database.Name)), ErrorCategory.InvalidArgument, adrecipient);
                    }
                    databaseIdParameter = new DatabaseIdParameter(adobjectId);
                    if (this.isRunningLogonStatisticsTask)
                    {
                        this.identity = new MailboxId(mailboxExchangeLegacyDn);
                    }
                    else
                    {
                        this.identity = new MailboxId(MapiTaskHelper.ConvertDatabaseADObjectIdToDatabaseId(adobjectId), guid);
                    }
                }
            }
            if (databaseIdParameter != null)
            {
                databaseIdParameter.AllowLegacy = true;
                LocalizedString empty  = LocalizedString.Empty;
                LocalizedString empty2 = LocalizedString.Empty;
                Database        database;
                if (this.isRunningLogonStatisticsTask)
                {
                    database = (Database)base.GetDataObject <Database>(databaseIdParameter, base.GlobalConfigSession, null, new LocalizedString?(Strings.ErrorDatabaseNotFound(databaseIdParameter.ToString())), new LocalizedString?(Strings.ErrorDatabaseNotUnique(databaseIdParameter.ToString())));
                }
                else
                {
                    database = (MailboxDatabase)base.GetDataObject <MailboxDatabase>(databaseIdParameter, base.GlobalConfigSession, null, new LocalizedString?(Strings.ErrorMailboxDatabaseNotFound(databaseIdParameter.ToString())), new LocalizedString?(Strings.ErrorMailboxDatabaseNotUnique(databaseIdParameter.ToString())));
                }
                if (database.Server == null)
                {
                    base.WriteError(new MdbAdminTaskException(Strings.ErrorInvalidObjectMissingCriticalProperty(this.isRunningLogonStatisticsTask ? typeof(Database).Name : typeof(MailboxDatabase).Name, databaseIdParameter.ToString(), DatabaseSchema.Server.Name)), ErrorCategory.InvalidArgument, database);
                }
                this.databases = new List <Database>(new Database[]
                {
                    database
                });
                if (this.CopyOnServer != null)
                {
                    serverIdParameter = this.CopyOnServer;
                }
                else
                {
                    DatabaseLocationInfo serverForDatabase = activeManagerInstance.GetServerForDatabase(database.Guid);
                    serverIdParameter = ServerIdParameter.Parse(serverForDatabase.ServerFqdn);
                }
            }
            if (this.Server != null)
            {
                serverIdParameter = this.Server;
                this.server       = MapiTaskHelper.GetMailboxServer(this.Server, base.GlobalConfigSession, new Task.ErrorLoggerDelegate(base.WriteError));
            }
            else
            {
                this.server = (Server)base.GetDataObject <Server>(serverIdParameter, base.GlobalConfigSession, null, new LocalizedString?((this.Identity == null && this.Database == null) ? Strings.ErrorLocalMachineIsNotExchangeServer : Strings.ErrorServerNotFound(serverIdParameter.ToString())), new LocalizedString?(Strings.ErrorServerNotUnique(serverIdParameter.ToString())));
                if (!this.server.IsExchange2007OrLater || !this.server.IsMailboxServer)
                {
                    if (this.Identity != null)
                    {
                        TIdentity tidentity9 = this.Identity;
                        base.WriteError(new MdbAdminTaskException(Strings.ErrorMailboxInNonMailboxServer(tidentity9.ToString())), ErrorCategory.InvalidArgument, this.server);
                    }
                    if (this.Database != null)
                    {
                        base.WriteError(new MdbAdminTaskException(Strings.ErrorDatabaseInNonMailboxServer(this.Database.ToString())), ErrorCategory.InvalidArgument, this.server);
                    }
                    base.WriteError(new MdbAdminTaskException(Strings.ErrorLocalServerIsNotMailboxServer), ErrorCategory.InvalidArgument, this.server);
                }
            }
            if (string.IsNullOrEmpty(this.server.ExchangeLegacyDN))
            {
                base.WriteError(new MdbAdminTaskException(Strings.ErrorInvalidObjectMissingCriticalProperty(typeof(Server).Name, serverIdParameter.ToString(), ServerSchema.ExchangeLegacyDN.Name)), ErrorCategory.InvalidArgument, this.Identity);
            }
            if (this.databases.Count == 0)
            {
                if (this.isRunningLogonStatisticsTask)
                {
                    this.FilterActiveDatabases(activeManagerInstance, this.server.GetDatabases());
                    return;
                }
                this.FilterActiveDatabases(activeManagerInstance, this.server.GetMailboxDatabases());
            }
        }
예제 #19
0
        private static UMMailboxPolicy GetTargetPolicy(IConfigurationSession tenantLocalConfigSession, ADUser sourceUser)
        {
            UMMailboxPolicy ummailboxPolicy = null;

            UMMailboxPolicy[] array = tenantLocalConfigSession.Find <UMMailboxPolicy>(null, QueryScope.SubTree, null, null, 0);
            foreach (UMMailboxPolicy ummailboxPolicy2 in array)
            {
                if (ummailboxPolicy2.SourceForestPolicyNames.Contains(sourceUser.UMMailboxPolicy.Name))
                {
                    ummailboxPolicy = ummailboxPolicy2;
                    break;
                }
            }
            if (ummailboxPolicy == null)
            {
                throw new NoMatchingUMMailboxPolicyInTargetForestException();
            }
            return(ummailboxPolicy);
        }
예제 #20
0
 // Token: 0x06000197 RID: 407 RVA: 0x000064F4 File Offset: 0x000046F4
 internal bool TryAdd(ADUser user, bool wakeCache)
 {
     AnchorUtil.ThrowOnNullArgument(user, "user");
     return(this.TryUpdate(this.Context.CreateCacheEntry(user), wakeCache));
 }
예제 #21
0
 protected void btnSendEmail_Click(object sender, EventArgs e)
 {
     ADUser.Mail(mailUsername, mailPassword);
     SetMessage(string.Format("Mail sendt til 00{0}@mil.dk", mailUsername));
 }
예제 #22
0
        internal static WacResult ExecuteWacRequest(string wacTemplateUrl, string owaTemplateUrl, ADUser user, StringBuilder diagnosticsDetails)
        {
            string          text            = string.Empty;
            string          text2           = string.Empty;
            string          text3           = string.Empty;
            WacRequestState wacRequestState = new WacRequestState();
            WacResult       wacResult       = new WacResult();

            try
            {
                string text4 = user.PrimarySmtpAddress.ToString();
                if (string.IsNullOrEmpty(text4))
                {
                    diagnosticsDetails.AppendLine(string.Format("Primary SMTP Address not found for user {0}", user.Alias));
                    wacResult.Error = wacRequestState.Error;
                    return(wacResult);
                }
                text = WacWorker.GenerateWopiSrcUrl(owaTemplateUrl, text4);
                LocalTokenIssuer localTokenIssuer = new LocalTokenIssuer(user.OrganizationId);
                TokenResult      wacCallbackToken = localTokenIssuer.GetWacCallbackToken(new Uri(text, UriKind.Absolute), text4, Guid.NewGuid().ToString());
                text3 = wacCallbackToken.TokenString;
                text2 = WacWorker.GenerateWacIFrameUrl(text, wacTemplateUrl, text4, text3);
                text  = string.Format("{0}&access_token={1}", text, text3);
                diagnosticsDetails.AppendLine("Probe Details:");
                diagnosticsDetails.AppendLine("WacIFrameUrl:");
                diagnosticsDetails.AppendLine(text2);
                diagnosticsDetails.AppendLine("ExchangeCheckFileUrl:");
                diagnosticsDetails.AppendLine(text);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(text2);
                wacRequestState.Request            = httpWebRequest;
                wacRequestState.WacIFrameUrl       = text2;
                wacRequestState.WopiUrl            = text;
                wacRequestState.Error              = false;
                wacRequestState.DiagnosticsDetails = diagnosticsDetails;
                WacWorker.allDone.Reset();
                WacWorker.latencyMeasurementStart = DateTime.UtcNow;
                IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(new AsyncCallback(WacWorker.ProcessWacResponse), wacRequestState);
                ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, new WaitOrTimerCallback(WacWorker.TimeoutCallback), httpWebRequest, 120000, true);
                WacWorker.allDone.WaitOne();
                if (wacRequestState.Response != null)
                {
                    wacRequestState.Response.Close();
                }
            }
            catch (WebException ex)
            {
                diagnosticsDetails.AppendLine("Stack Trace:");
                diagnosticsDetails.AppendLine(string.Format("Exception: {0}.", ex.ToString()));
                for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
                {
                    diagnosticsDetails.AppendLine(string.Format("Inner Exception: {0}.", innerException.ToString()));
                }
                diagnosticsDetails.AppendLine("Diagnostic Tip: There is an unhandled exception occured while running Wac Probe. Please look into the exception details.");
                wacRequestState.Error = true;
            }
            wacResult.Error = wacRequestState.Error;
            return(wacResult);
        }
예제 #23
0
 public User(ADUser dataObject) : base(dataObject)
 {
 }
예제 #24
0
        protected override void InternalProcessRecord()
        {
            ADUser      dataObject  = this.DataObject;
            TeamMailbox teamMailbox = TeamMailbox.FromDataObject(dataObject);

            this.teamMailboxHelper = new TeamMailboxHelper(teamMailbox, base.ExchangeRunspaceConfig.ExecutingUser, base.ExchangeRunspaceConfig.ExecutingUserOrganizationId, (IRecipientSession)base.DataSession, new TeamMailboxGetDataObject <ADUser>(base.GetDataObject <ADUser>));
            TeamMailboxMembershipHelper teamMailboxMembershipHelper = new TeamMailboxMembershipHelper(teamMailbox, (IRecipientSession)base.DataSession);
            Exception ex     = null;
            ADUser    aduser = TeamMailboxADUserResolver.Resolve((IRecipientSession)base.DataSession, this.executingUserId, out ex);

            if (aduser == null)
            {
                base.WriteError(new RecipientTaskException(Strings.ErrorExecutingUserIsNull), ExchangeErrorCategory.Client, null);
            }
            if (base.Fields.IsModified("DisplayName"))
            {
                teamMailbox.DisplayName = this.DisplayName;
            }
            teamMailbox.SetPolicy(this.provisioningPolicy);
            base.WriteVerbose(Strings.SiteMailboxPolicySet(this.provisioningPolicy.ToString()));
            teamMailbox.SetMyRole(this.executingUserId);
            Uri sharePointUrl = this.SharePointUrl;
            SharePointMemberShip sharePointMemberShip = SharePointMemberShip.Others;
            Uri  webCollectionUrl = null;
            Guid empty            = Guid.Empty;

            if (base.Fields.IsModified("SharePointUrl") && !base.Fields.IsModified("Force"))
            {
                try
                {
                    TeamMailboxHelper.CheckSharePointSite(SmtpAddress.Empty, ref sharePointUrl, base.ExchangeRunspaceConfig.ExecutingUser, base.ExchangeRunspaceConfig.ExecutingUserOrganizationId, aduser, out sharePointMemberShip, out webCollectionUrl, out empty);
                }
                catch (RecipientTaskException exception)
                {
                    base.WriteError(exception, ExchangeErrorCategory.Client, null);
                }
            }
            teamMailbox.SharePointUrl = sharePointUrl;
            teamMailbox.SetSharePointSiteInfo(webCollectionUrl, empty);
            teamMailbox.SharePointLinkedBy = this.executingUserId;
            List <ADObjectId>  list          = new List <ADObjectId>();
            List <ADObjectId>  list2         = new List <ADObjectId>();
            IList <ADObjectId> list3         = null;
            IList <ADObjectId> usersToRemove = null;

            if (TeamMailboxMembershipHelper.IsUserQualifiedType(aduser))
            {
                if (sharePointMemberShip == SharePointMemberShip.Owner)
                {
                    list.Add(this.executingUserId);
                    teamMailboxMembershipHelper.UpdateTeamMailboxUserList(teamMailbox.Owners, list, out list3, out usersToRemove);
                    teamMailboxMembershipHelper.UpdateTeamMailboxUserList(teamMailbox.OwnersAndMembers, list, out list3, out usersToRemove);
                }
                else if (sharePointMemberShip == SharePointMemberShip.Member)
                {
                    list2.Add(this.executingUserId);
                    teamMailboxMembershipHelper.UpdateTeamMailboxUserList(teamMailbox.OwnersAndMembers, list2, out list3, out usersToRemove);
                }
            }
            Exception ex2 = null;

            try
            {
                teamMailboxMembershipHelper.SetTeamMailboxUserPermissions(list3, usersToRemove, new SecurityIdentifier[]
                {
                    WellKnownSids.SiteMailboxGrantedAccessMembers
                }, false);
                if (list3 != null)
                {
                    base.WriteVerbose(Strings.SiteMailboxCreatorSet(list3[0].ToString()));
                }
            }
            catch (OverflowException ex3)
            {
                ex2 = ex3;
            }
            catch (COMException ex4)
            {
                ex2 = ex4;
            }
            catch (UnauthorizedAccessException ex5)
            {
                ex2 = ex5;
            }
            catch (TransientException ex6)
            {
                ex2 = ex6;
            }
            catch (DataSourceOperationException ex7)
            {
                ex2 = ex7;
            }
            if (ex2 != null)
            {
                base.WriteError(new RecipientTaskException(Strings.ErrorSetTeamMailboxUserPermissions(teamMailbox.DisplayName, ex2.Message)), ExchangeErrorCategory.Client, null);
            }
            base.InternalProcessRecord();
            if (base.Fields.IsModified("SharePointUrl") && !base.Fields.IsModified("Force"))
            {
                try
                {
                    this.teamMailboxHelper.LinkSharePointSite(sharePointUrl, true, false);
                    base.WriteVerbose(Strings.SiteMailboxLinkedToSharePointSite(sharePointUrl.AbsoluteUri));
                }
                catch (RecipientTaskException exception2)
                {
                    base.DataSession.Delete(this.DataObject);
                    base.WriteError(exception2, ExchangeErrorCategory.Client, null);
                }
            }
            IList <Exception> list4;

            teamMailboxMembershipHelper.SetShowInMyClient(list3, usersToRemove, out list4);
            foreach (Exception ex8 in list4)
            {
                this.WriteWarning(Strings.ErrorTeamMailboxResolveUser(ex8.Message));
            }
            EnqueueResult enqueueResult = EnqueueResult.Success;

            if (this.databaseLocationInfo != null)
            {
                int num = 0;
                for (;;)
                {
                    base.WriteVerbose(new LocalizedString(string.Format("Trying to send membership sync request to server {0} for MailboxGuid {1} using domain controller {2}", this.databaseLocationInfo.ServerFqdn, dataObject.ExchangeGuid, this.lastUsedDc)));
                    enqueueResult = RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.databaseLocationInfo.ServerFqdn, dataObject.ExchangeGuid, QueueType.TeamMailboxMembershipSync, base.CurrentOrganizationId, "NewTMCMD_" + base.ExecutingUserIdentityName, this.lastUsedDc, SyncOption.Default);
                    base.WriteVerbose(new LocalizedString(string.Format("The membership sync result is {0}", enqueueResult.Result)));
                    if (enqueueResult.Result == EnqueueResultType.Successful)
                    {
                        goto IL_409;
                    }
                    if (num > 12)
                    {
                        break;
                    }
                    Thread.Sleep(5000);
                    num++;
                }
                this.WriteWarning(Strings.ErrorTeamMailboxEnqueueMembershipSyncEvent(enqueueResult.ResultDetail));
                goto IL_414;
IL_409:
                base.WriteVerbose(Strings.SiteMailboxMembershipSyncEventEnqueued);
IL_414:
                enqueueResult = RpcClientWrapper.EnqueueTeamMailboxSyncRequest(this.databaseLocationInfo.ServerFqdn, dataObject.ExchangeGuid, QueueType.TeamMailboxDocumentSync, base.CurrentOrganizationId, "NewTMCMD_" + base.ExecutingUserIdentityName, this.lastUsedDc, SyncOption.Default);
                base.WriteVerbose(new LocalizedString(string.Format("Document sync request to server {0} for MailboxGuid {1} using domain controller {2}. The result is: {3}", new object[]
                {
                    this.databaseLocationInfo.ServerFqdn,
                    dataObject.ExchangeGuid,
                    this.lastUsedDc,
                    enqueueResult.ResultDetail
                })));
                return;
            }
            this.WriteWarning(Strings.ErrorTeamMailboxEnqueueMembershipSyncEvent("No database location information available"));
        }
예제 #25
0
        public void CreateUser(UsersObject newUser)
        {
            CPDatabase database  = null;
            ADGroup    ldapGroup = null;
            ADUser     ldapUser  = null;

            CloudPanelTransaction newUserTransaction = new CloudPanelTransaction();

            try
            {
                // Insert into database
                database = new CPDatabase();

                // Make sure the user doesn't already exist
                var foundUser = (from u in database.Users
                                 where u.UserPrincipalName == newUser.UserPrincipalName
                                 select u).FirstOrDefault();

                if (foundUser != null)
                {
                    ThrowEvent(AlertID.FAILED, "User already exists " + newUser.UserPrincipalName);
                }
                else
                {
                    // Get the company's OU where we need to save the user
                    var companyDistinguishedName = (from c in database.Companies
                                                    where !c.IsReseller
                                                    where c.CompanyCode == newUser.CompanyCode
                                                    select c.DistinguishedName).First();

                    // Check if they are using a custom user's OU
                    if (!string.IsNullOrEmpty(StaticSettings.UsersOU))
                    {
                        companyDistinguishedName = string.Format("OU={0},{1}", StaticSettings.UsersOU, companyDistinguishedName);
                    }

                    ldapUser = new ADUser(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                    UsersObject createdUser = ldapUser.NewUser(newUser, companyDistinguishedName, StaticSettings.AllowCustomNameAttribute);
                    newUserTransaction.NewUser(createdUser.UserPrincipalName);

                    // Add the users to the groups
                    ldapGroup = new ADGroup(StaticSettings.Username, StaticSettings.DecryptedPassword, StaticSettings.PrimaryDC);
                    ldapGroup.AddMember("AllUsers@" + newUser.CompanyCode, createdUser.UserPrincipalName, "upn");

                    if (newUser.IsCompanyAdmin)
                    {
                        ldapGroup.AddMember("Admins@" + newUser.CompanyCode, createdUser.UserPrincipalName, "upn");
                    }

                    // Insert into database
                    User sqlUser = new User();
                    sqlUser.UserGuid          = createdUser.UserGuid;
                    sqlUser.CompanyCode       = createdUser.CompanyCode;
                    sqlUser.sAMAccountName    = createdUser.sAMAccountName;
                    sqlUser.UserPrincipalName = createdUser.UserPrincipalName;
                    sqlUser.DistinguishedName = createdUser.DistinguishedName;
                    sqlUser.DisplayName       = createdUser.DisplayName;
                    sqlUser.Firstname         = createdUser.Firstname;
                    sqlUser.Middlename        = createdUser.Middlename;
                    sqlUser.Lastname          = createdUser.Lastname;
                    sqlUser.Email             = string.Empty;
                    sqlUser.Department        = createdUser.Department;
                    sqlUser.IsResellerAdmin   = createdUser.IsResellerAdmin;
                    sqlUser.IsCompanyAdmin    = createdUser.IsCompanyAdmin;
                    sqlUser.MailboxPlan       = 0;
                    sqlUser.TSPlan            = 0;
                    sqlUser.LyncPlan          = 0;
                    sqlUser.Created           = DateTime.Now;
                    sqlUser.AdditionalMB      = 0;
                    sqlUser.ActiveSyncPlan    = 0;
                    database.Users.Add(sqlUser);

                    // Insert permissions into database
                    if (createdUser.IsCompanyAdmin)
                    {
                        UserPermission newPermissions = new UserPermission();
                        newPermissions.UserID                = sqlUser.ID;
                        newPermissions.EnableExchange        = createdUser.EnableExchangePerm;
                        newPermissions.DisableExchange       = createdUser.DisableExchangePerm;
                        newPermissions.AddDomain             = createdUser.AddDomainPerm;
                        newPermissions.DeleteDomain          = createdUser.DeleteDomainPerm;
                        newPermissions.EnableAcceptedDomain  = createdUser.EnableAcceptedDomainPerm;
                        newPermissions.DisableAcceptedDomain = createdUser.DisableAcceptedDomainPerm;
                        database.UserPermissions.Add(newPermissions);
                    }

                    database.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ThrowEvent(AlertID.FAILED, ex.Message);

                // Rollback on error
                newUserTransaction.RollBack();
            }
            finally
            {
                if (ldapUser != null)
                {
                    ldapUser.Dispose();
                }

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

                if (database != null)
                {
                    database.Dispose();
                }
            }
        }
예제 #26
0
        protected void uploadbtn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["teacher"]))
            {
                HAP.MyFiles.Homework.Homework Homework = new HAP.MyFiles.Homework.Homeworks().Homework.Single(hw => hw.Teacher == Request.QueryString["teacher"] && hw.Name == Request.QueryString["name"] && hw.Start == Request.QueryString["start"].Replace('.', ':') && hw.End == Request.QueryString["end"].Replace('.', ':'));
                ADUser.Authenticate(Homework.Teacher, TokenGenerator.ConvertToPlain(Homework.Token));
            }
            ADUser.Impersonate();
            message.Text = "";
            string       path = Server.UrlDecode(Request.QueryString["path"].Remove(0, 1).Replace('^', '&').Replace("|", "%"));
            string       p    = Request.QueryString["path"].Substring(0, 1);
            DriveMapping unc  = null;

            unc = config.MyFiles.Mappings.FilteredMappings[p.ToCharArray()[0]];
            if (unc == null || !isWriteAuth(unc))
            {
                Response.Redirect(Request.ApplicationPath + "/unauthorised.aspx", true);
            }
            else
            {
                path = Converter.FormatMapping(unc.UNC, ADUser) + path.Replace('/', '\\');
            }
            if (FileUpload1.HasFile && isAuth(Path.GetExtension(FileUpload1.FileName)))
            {
                FileUpload1.SaveAs(Path.Combine(path, (string.IsNullOrEmpty(Request.QueryString["teacher"]) ? "" : User.Identity.Name + " - ") + FileUpload1.FileName)); message.Text += FileUpload1.FileName + " has been uploaded<br />";
            }
            else if (FileUpload1.HasFile)
            {
                message.Text += "Error: " + FileUpload1.FileName + " is a restricted file type<br/>";
            }
            if (FileUpload2.HasFile && isAuth(Path.GetExtension(FileUpload2.FileName)))
            {
                FileUpload2.SaveAs(Path.Combine(path, (string.IsNullOrEmpty(Request.QueryString["teacher"]) ? "" : User.Identity.Name + " - ") + FileUpload2.FileName)); message.Text += FileUpload2.FileName + " has been uploaded<br />";
            }
            else if (FileUpload2.HasFile)
            {
                message.Text += "Error: " + FileUpload2.FileName + " is a restricted file type<br/>";
            }
            if (FileUpload3.HasFile && isAuth(Path.GetExtension(FileUpload3.FileName)))
            {
                FileUpload3.SaveAs(Path.Combine(path, (string.IsNullOrEmpty(Request.QueryString["teacher"]) ? "" : User.Identity.Name + " - ") + FileUpload3.FileName)); message.Text += FileUpload3.FileName + " has been uploaded<br />";
            }
            else if (FileUpload3.HasFile)
            {
                message.Text += "Error: " + FileUpload3.FileName + " is a restricted file type<br/>";
            }
            if (FileUpload4.HasFile && isAuth(Path.GetExtension(FileUpload4.FileName)))
            {
                FileUpload4.SaveAs(Path.Combine(path, (string.IsNullOrEmpty(Request.QueryString["teacher"]) ? "" : User.Identity.Name + " - ") + FileUpload4.FileName)); message.Text += FileUpload4.FileName + " has been uploaded<br />";
            }
            else if (FileUpload4.HasFile)
            {
                message.Text += "Error: " + FileUpload4.FileName + " is a restricted file type<br/>";
            }
            if (FileUpload5.HasFile && isAuth(Path.GetExtension(FileUpload5.FileName)))
            {
                FileUpload5.SaveAs(Path.Combine(path, (string.IsNullOrEmpty(Request.QueryString["teacher"]) ? "" : User.Identity.Name + " - ") + FileUpload5.FileName)); message.Text += FileUpload5.FileName + " has been uploaded<br />";
            }
            else if (FileUpload5.HasFile)
            {
                message.Text += "Error: " + FileUpload5.FileName + " is a restricted file type<br/>";
            }
            if (!string.IsNullOrEmpty(message.Text))
            {
                message.Text = "<div style=\"padding: 4px; color: red;\">" + message.Text + "</div>";
            }
            closeb.Visible = (((Button)sender).ID == "uploadbtnClose");
            ADUser.EndImpersonate();
        }
 // Token: 0x06001678 RID: 5752 RVA: 0x0007EC98 File Offset: 0x0007CE98
 protected override void HandleEventInternal(MapiEvent mapiEvent, MailboxSession itemStore, StoreObject item, List <KeyValuePair <string, object> > customDataToLog)
 {
     if (this.InternalIsEventInteresting(mapiEvent) && itemStore != null && item != null)
     {
         MessageItem messageItem = item as MessageItem;
         if (messageItem == null)
         {
             RecipientDLExpansionEventBasedAssistant.Tracer.TraceWarning((long)this.GetHashCode(), "The item being processed is not a message item.");
             return;
         }
         RecipientDLExpansionEventBasedAssistant.Tracer.TraceDebug <Guid, StoreObjectId, string>((long)this.GetHashCode(), "Processing mailbox guid: {0} and message id: {1} with subject: '{2}'", itemStore.MailboxGuid, messageItem.StoreObjectId, messageItem.Subject);
         StorageGlobals.EventLogger.LogEvent(StorageEventLogConstants.Tuple_RecipientDLExpansionIsProcessing, null, new object[]
         {
             messageItem.StoreObjectId,
             messageItem.Subject,
             itemStore.MailboxGuid
         });
         bool flag  = false;
         bool flag2 = true;
         try
         {
             ADUser adUser = DirectoryHelper.ReadADRecipient(itemStore.MailboxOwner.MailboxInfo.MailboxGuid, itemStore.MailboxOwner.MailboxInfo.IsArchive, itemStore.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid)) as ADUser;
             bool   flag3  = this.IsFlightingFeatureEnabled(adUser) || RecipientDLExpansionEventBasedAssistantHelper.IsRecipientDLExpansionTestHookEnabled();
             RecipientDLExpansionEventBasedAssistantHelper.GetComplianceMaxExpansionDGRecipientsAndNestedDGs(itemStore.OrganizationId, out this.maxDGExpansionRecipients, out this.maxExpansionNestedDGs);
             if (flag3 && this.maxDGExpansionRecipients != 0U)
             {
                 flag2 = false;
                 this.PerformDLExpansionOnItemRecipients(itemStore, messageItem, ref flag2);
             }
             else
             {
                 RecipientDLExpansionEventBasedAssistant.Tracer.TraceDebug <StoreObjectId, Guid, OrganizationId>((long)this.GetHashCode(), "Per tenant configuration or flighting framework, DL expansion is disabled, skip processing message id: {0}, mailbox guid: {1}, tenant: {2}", messageItem.StoreObjectId, itemStore.MailboxGuid, itemStore.OrganizationId);
                 StorageGlobals.EventLogger.LogEvent(StorageEventLogConstants.Tuple_RecipientDLExpansionSkipped, null, new object[]
                 {
                     messageItem.StoreObjectId,
                     itemStore.MailboxGuid,
                     itemStore.OrganizationId
                 });
             }
         }
         catch (Exception ex)
         {
             RecipientDLExpansionEventBasedAssistant.Tracer.TraceError((long)this.GetHashCode(), "Exception when updating the item with id: {0}, mailbox guid: {1}, tenant: {2}.\n\nThe exception is : {3}", new object[]
             {
                 messageItem.StoreObjectId,
                 itemStore.MailboxGuid,
                 itemStore.OrganizationId,
                 ex
             });
             StorageGlobals.EventLogger.LogEvent(StorageEventLogConstants.Tuple_RecipientDLExpansionFailed, null, new object[]
             {
                 messageItem.StoreObjectId,
                 itemStore.MailboxGuid,
                 itemStore.OrganizationId,
                 ex
             });
             this.PublishMonitoringResults(itemStore, ex);
             flag = true;
             if (!(ex is StorageTransientException) && !(ex is StoragePermanentException))
             {
                 throw;
             }
         }
         if (!flag && !flag2)
         {
             this.PublishMonitoringResults(itemStore, null);
         }
     }
 }
예제 #28
0
 public CASMailboxPlan(ADUser dataObject) : base(dataObject)
 {
 }
예제 #29
0
        public override bool IsValidReplicationTarget()
        {
            ADUser aduser = base.FindAdUser();

            return(aduser.RecipientTypeDetails == RecipientTypeDetails.UserMailbox);
        }
예제 #30
0
        public static void EnableTargetUserForUM(IRecipientSession tenantLocalRecipientSession, IConfigurationSession tenantLocalConfigSession, bool isDatacenter, ADUser sourceUser, ADUser targetUser)
        {
            UMMailboxPolicy policy;
            UMDialPlan      dialPlan;
            MultiValuedProperty <string> extensions;
            string sipResourceIdentifier;

            MigrationHelper.GetUMSettingsFromSourceUser(tenantLocalRecipientSession, tenantLocalConfigSession, isDatacenter, sourceUser, targetUser, out policy, out dialPlan, out extensions, out sipResourceIdentifier);
            targetUser.UMEnabledFlags |= UMEnabledFlags.UMEnabled;
            Utils.UMPopulate(targetUser, sipResourceIdentifier, extensions, policy, dialPlan);
        }
예제 #31
0
        private void grdDomainUsers_Click(object sender, EventArgs e)
        {
            if (ObjectDomainChangeEvent == null) return;

            if (grdDomainUsers.CurrentRow == null) return;
            if (grdDomainUsers.CurrentRow.DataBoundItem == null) return;

            _CurrentUserName = (ADUser)grdDomainUsers.CurrentRow.DataBoundItem;
            OnObjectDomainChange();
        }
예제 #32
0
        public static void ValidateTargetUserCanBeEnabledForUM(IRecipientSession tenantLocalRecipientSession, IConfigurationSession tenantLocalConfigSession, bool isDatacenter, ADUser sourceUser, ADUser targetUser)
        {
            if (!sourceUser.UMEnabled)
            {
                return;
            }
            UMMailboxPolicy ummailboxPolicy;
            UMDialPlan      umdialPlan;
            MultiValuedProperty <string> multiValuedProperty;
            string text;

            MigrationHelper.GetUMSettingsFromSourceUser(tenantLocalRecipientSession, tenantLocalConfigSession, isDatacenter, sourceUser, targetUser, out ummailboxPolicy, out umdialPlan, out multiValuedProperty, out text);
        }
예제 #33
0
 private void domainUsers1_ObjectDomainChangeEvent(ADUser user)
 {
     
 }
예제 #34
0
        private static void GetUMSettingsFromSourceUser(IRecipientSession tenantLocalRecipientSession, IConfigurationSession tenantLocalConfigSession, bool isDatacenter, ADUser sourceUser, ADUser targetUser, out UMMailboxPolicy targetPolicy, out UMDialPlan targetDialPlan, out MultiValuedProperty <string> targetUserExtensions, out string targetUserSipResourceIdentifier)
        {
            if (!Utils.UnifiedMessagingAvailable(targetUser))
            {
                throw new UMNotAvailableForUserInTargetForestException();
            }
            targetPolicy         = MigrationHelper.GetTargetPolicy(tenantLocalConfigSession, sourceUser);
            targetDialPlan       = tenantLocalConfigSession.Read <UMDialPlan>(targetPolicy.UMDialPlan);
            targetUserExtensions = MigrationHelper.GetTargetUserExtensions(sourceUser, targetDialPlan, out targetUserSipResourceIdentifier);
            LocalizedException           ex;
            TelephoneNumberProcessStatus telephoneNumberProcessStatus;

            Utils.ValidateExtensionsAndSipResourceIdentifier(tenantLocalRecipientSession, tenantLocalConfigSession, isDatacenter, targetUser, targetDialPlan, targetUserExtensions.ToArray(), null, targetUserSipResourceIdentifier, out ex, out telephoneNumberProcessStatus);
            if (ex != null)
            {
                throw ex;
            }
        }
예제 #35
0
파일: Form1.cs 프로젝트: zoso10/ErrorLogger
        private void usernameTextBoxTextChanged(object sender, EventArgs e)
        {
            // Each time a letter is typed it checks AD for the user and updates the Status message and button availability
            ADManager ad = new ADManager(LordDomains.LORD);

            // I only use a try if someone in case someone enters crazy characters *^#$^&
            try
            {
                adUser = usernameTextBox.Text != string.Empty ? ad.GetUserByAccountName(usernameTextBox.Text) : null;
            }
            catch (Exception exc) { Console.WriteLine(exc.Message); }

            bool userExists = adUser != null;
            addUserButton.Enabled = userExists;
            statusMessage.Text = userExists ? adUser.AccountName.Replace('_', ' ') + " is a valid user" : usernameTextBox.Text == string.Empty ? string.Empty : "That username does not exist in AD";
        }
예제 #36
0
        public ADUserInstance Construct()
        {
            var user = new ADUser();

            return(new ADUserInstance(InstancePrototype, user));
        }