Пример #1
0
        public static void RemoveUserProperty(MailItem mailitem)
        {
            UserProperties mailUserProperties = null;

            try
            {
                var pointer = 0;
                mailUserProperties = mailitem.UserProperties;
                for (var i = 1; i == mailUserProperties.Count; i++)
                {
                    if (mailUserProperties[i].Name == "KayakoTicketId")
                    {
                        pointer = i;
                    }
                }
                mailUserProperties.Remove(pointer);
                mailitem.Save();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (mailUserProperties != null)
                {
                    Marshal.ReleaseComObject(mailUserProperties);
                }
            }
        }
Пример #2
0
        private void UpdateAccountDataForUser(ServerAccount serverAccount, UserProperties userProperties, System.Action <XmlDocument> finishedUpdatingAccountDataCallback)
        {
            serverAccount.UserProperties = userProperties;
            XmlDocument accountDataXml = AccountsXmlUtil.CreateAccountDataXml(serverAccount);

            AccountsServiceAPI.UpdateAccountData(serverAccount.AccountId, accountDataXml, finishedUpdatingAccountDataCallback);
        }
Пример #3
0
        public void SetSolutionItemEnabled(string solutionItemPath, bool enabled)
        {
            solutionItemPath = GetRelativeChildPath(Path.GetFullPath(solutionItemPath));
            var list = UserProperties.GetValue <List <string> > ("DisabledProjects");

            if (!enabled)
            {
                if (list == null)
                {
                    list = new List <string> ();
                }
                if (!list.Contains(solutionItemPath))
                {
                    list.Add(solutionItemPath);
                }
                UserProperties.SetValue("DisabledProjects", list);
            }
            else if (list != null)
            {
                list.Remove(solutionItemPath);
                if (list.Count == 0)
                {
                    UserProperties.RemoveValue("DisabledProjects");
                }
                else
                {
                    UserProperties.SetValue("DisabledProjects", list);
                }
            }
        }
        private static void add(ref AppointmentItem ai, MetadataId key, OlUserPropertyType keyType, object keyValue)
        {
            String addkeyName = metadataIdKeyName(key);

            UserProperties ups = null;

            try {
                if (!Exists(ai, key))
                {
                    int newSet;
                    int?keySet = getKeySet(ai, out newSet);
                    keySet = keySet ?? newSet + 1;
                    if (keySet.HasValue && keySet.Value != 0)
                    {
                        addkeyName += "-" + keySet.Value.ToString("D2");
                    }

                    try {
                        ups = ai.UserProperties;
                        ups.Add(addkeyName, keyType);
                    } catch (System.Exception ex) {
                        OGCSexception.Analyse(ex);
                        ups.Add(addkeyName, keyType, false);
                    } finally {
                        ups = (UserProperties)Calendar.ReleaseObject(ups);
                    }
                }
                ups = ai.UserProperties;
                ups[addkeyName].Value = keyValue;
                log.Fine("Set userproperty " + addkeyName + "=" + keyValue.ToString());
            } finally {
                ups = (UserProperties)Calendar.ReleaseObject(ups);
            }
        }
        private void MapHeaders(CloudEvent cloudEvent)
        {
            var ignoreKeys = new List <string>(3)
            {
                CloudEventAttributes.DataAttributeName(cloudEvent.SpecVersion),
                CloudEventAttributes.IdAttributeName(cloudEvent.SpecVersion),
                CloudEventAttributes.DataContentTypeAttributeName(cloudEvent.SpecVersion),
            };

            foreach (var attribute in cloudEvent.GetAttributes())
            {
                if (!ignoreKeys.Contains(attribute.Key))
                {
                    var key = Constants.PropertyKeyPrefix + attribute.Key;
                    switch (attribute.Value)
                    {
                    case Uri uri:
                        UserProperties.Add(key, uri.ToString());
                        break;

                    default:
                        UserProperties.Add(key, attribute.Value);
                        break;
                    }
                }
            }
        }
Пример #6
0
        public async Task <ActionResult <ApiResponse <UserProperties> > > VerifyMfaDisable()
        {
            try
            {
                var userName = User?.Identity?.Name;
                var userId   = User?.Claims.Where(x => x.Type == CustomClaims.USER_ID).FirstOrDefault()?.Value;

                if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(userId))
                {
                    return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to validate your request.")));
                }

                var currentPropertiesKey = await firebaseDbService.GetUserPropertiesKey(userId);

                if (string.IsNullOrWhiteSpace(currentPropertiesKey))
                {
                    return(BadRequest(RequestResponse.BadRequest("Mfa record not found. Please enable Mfa.")));
                }

                var cacheResult = new UserProperties(userId, string.Empty, false);
                await firebaseDbService.UpdateUserProperties(currentPropertiesKey, cacheResult);

                return(Ok(new ApiResponse <UserProperties>(cacheResult)));
            }
            catch (Exception)
            {
                return(BadRequest(RequestResponse.BadRequest("Something went wrong trying to enable Mfa.")));
            }
        }
Пример #7
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="tokenSuffix">アカウント番号</param>
        /// <param name="user">表示対象のユーザー</param>
        public ShowList(int tokenSuffix, UserProperties user)
        {
            InitializeComponent();

            this.ShowListViewModel = new ShowListViewModel(tokenSuffix, user);
            this.DataContext       = this.ShowListViewModel;
        }
Пример #8
0
 private static void RestoreUserDetails(UserProperties userProps, EmailViewModel viewModel)
 {
     viewModel.Subject       = userProps.Subject;
     viewModel.BodyText      = userProps.Body;
     viewModel.UserEmail     = userProps.UserName;
     viewModel.EmailContacts = new ObservableCollection <string>(userProps.ContactList);
 }
        internal void Update(ContactItem outlookContactItem, Syncronizer sync)
        {
            this.EntryID                 = outlookContactItem.EntryID;
            this.FileAs                  = outlookContactItem.FileAs;
            this.FullName                = outlookContactItem.FullName;
            this.Email1Address           = ContactPropertiesUtils.GetOutlookEmailAddress1(outlookContactItem);
            this.MobileTelephoneNumber   = outlookContactItem.MobileTelephoneNumber;
            this.Categories              = outlookContactItem.Categories;
            this.LastModificationTime    = outlookContactItem.LastModificationTime;
            this.Company                 = outlookContactItem.CompanyName;
            this.TitleFirstLastAndSuffix = GetTitleFirstLastAndSuffix(outlookContactItem);

            UserProperties userProperties = outlookContactItem.UserProperties;
            UserProperty   prop           = userProperties[sync.OutlookPropertyNameId];

            this.UserProperties.GoogleContactId = prop != null?string.Copy((string)prop.Value) : null;

            if (prop != null)
            {
                Marshal.ReleaseComObject(prop);
            }

            prop = userProperties[sync.OutlookPropertyNameSynced];
            this.UserProperties.LastSync = prop != null ? (DateTime)prop.Value : (DateTime?)null;
            if (prop != null)
            {
                Marshal.ReleaseComObject(prop);
            }

            Marshal.ReleaseComObject(userProperties);
        }
Пример #10
0
        public async Task <bool> DisconnectAsync()
        {
            try
            {
                ConnexionRequest connexion = new ConnexionRequest()
                {
                    command = "disconnect"
                };
                var uri = new Uri(string.Format(Constants.BASE_URL + UserProperties.GetLocalIP() + Constants.API_DISCONNECT, string.Empty));

                var json    = JsonConvert.SerializeObject(connexion);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(uri, content);

                if (response.IsSuccessStatusCode)
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
            return(false);
        }
Пример #11
0
        public int CreateUser_DL(UserProperties User)
        {
            //int CompanyID, string FName, string LName, DateTime DOB, string UserName, string PWD, string uType, string Designation, double ApprovalLimit, string PresentAddress, string PermanentAddress, DateTime DateOfJoining, DateTime DateOfProbation, int DepartmentID, string NetWkId, int FleetID

            SqlParameter[] sqlprm = new SqlParameter[] {
                new SqlParameter("@CompanyID", User.CompanyId),
                new SqlParameter("@FName", User.First_Name),
                new SqlParameter("@LName", User.Last_Name),
                new SqlParameter("@DOB", User.DOB),
                new SqlParameter("@UserName", User.UserName),
                new SqlParameter("@PWD", User.Password),
                new SqlParameter("@uType", User.UserType),
                new SqlParameter("@Designation", User.Designation),
                new SqlParameter("@ApprovalLimit", User.ApprovalLimit),
                new SqlParameter("@PresentAddress", User.PresentAddress),
                new SqlParameter("@PermanentAddress", User.PermanentAddress),
                new SqlParameter("@DateOfJoining", User.DateOfJoining),
                new SqlParameter("@DateOfProbation", User.DateOfProbation),
                new SqlParameter("@DepartmentID", User.DepartmentID),
                new SqlParameter("@NetWkId", User.NetWkId),
                new SqlParameter("@FleetID", User.FleetID),
                new SqlParameter("@Created_By", User.Created_By),
                new SqlParameter("@Mobile", User.Mobile),
                new SqlParameter("@Email", User.Email),
                new SqlParameter("@ManagerID", User.ManagerID),
                new SqlParameter("return", SqlDbType.Int)
            };

            sqlprm[sqlprm.Length - 1].Direction = ParameterDirection.ReturnValue;
            SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, "SP_INF_CREATE_USER", sqlprm);
            return(Convert.ToInt32(sqlprm[sqlprm.Length - 1].Value));
        }
Пример #12
0
        public override void HandleNotification(PureMVC.Interfaces.INotification notification)
        {
            base.HandleNotification(notification);
            switch (notification.Name)
            {
            case GameFacade.CONNECTED:
                TransitionToState(mLoginState);
                break;

            case GameFacade.LOGIN_REQUEST:
                // TODO: add a "Connecting" state
                break;

            case GameFacade.LOGIN_SUCCESS:
                if (this.CurrentState.GetType() != mConnectedState.GetType())
                {
                    UserProperties userProperties = (UserProperties)notification.Body;
                    GameFacade.Instance.RegisterProxy(new UserAccountProxy(userProperties));
                    TransitionToState(mConnectedState);
                }
                break;

            case GameFacade.DISCONNECTED:
                TransitionToState(mDisconnectedState);
                break;

            case GameFacade.LOGIN_FAILED:
                // TODO: don't disconnect, but go back to login retry
                TransitionToState(mDisconnectedState);
                break;
            }
        }
Пример #13
0
        public void Save()
        {
            var props = new UserProperties[1];

            props[0] = new UserProperties()
            {
                CompanyInteropID = CompanyInteropID,
                UserInteropID    = InteropID,
                UserName         = UserName,
                FirstName        = FirstName,
                LastName         = LastName,
                PhoneNumber      = PhoneNumber,
                Email            = Email,
                Active           = Active,
                TermsAccepted    = TermsAccepted
            };

            if (Password != null)
            {
                props[0].Password = Password;
            }

            var error = _user.Save(props, this.SharedSecret);

            if (error.Length > 0)
            {
                throw new Exception(error[0].InteropID + " failed: " + error[0].ErrorMessage);
            }
            this.Sync();
        }
Пример #14
0
        private void signUpbt_Clicked(object sender, EventArgs e)
        {
            UserProperties add = new UserProperties();

            add.Username = username.Text;
            if (password.Text == confirmPassword.Text)
            {
                add.Password = password.Text;
                Navigation.PushAsync(new MainPage());
            }
            else
            {
                DisplayAlert("Error", "Passwords don't match", "Ok");
            }
            add.Fullname = fullname.Text;
            add.Mood1    = mood1.SelectedItem.ToString();
            add.Mood2    = mood2.SelectedItem.ToString();
            add.Mood3    = mood3.SelectedItem.ToString();
            add.Mood4    = mood4.SelectedItem.ToString();
            add.Mood5    = mood5.SelectedItem.ToString();
            add.Mood6    = mood6.SelectedItem.ToString();
            add.Mood7    = mood7.SelectedItem.ToString();
            add.Mood8    = mood8.SelectedItem.ToString();

            addUser.SaveDataOnDatabase(add.Fullname, add.Username, add.Password, add.Mood1, add.Mood2, add.Mood3, add.Mood4, add.Mood5, add.Mood6, add.Mood7, add.Mood8);
        }
Пример #15
0
        /// <summary>
        /// Log the various User Properties.
        /// </summary>
        /// <param name="ai">The Appointment item.</param>
        /// <param name="thresholdLevel">Only log if logging configured at this level or higher.</param>
        public static void LogProperties(AppointmentItem ai, log4net.Core.Level thresholdLevel)
        {
            if (((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level.Value > thresholdLevel.Value)
            {
                return;
            }

            UserProperties ups = null;
            UserProperty   up  = null;

            try {
                log.Debug(OutlookOgcs.Calendar.GetEventSummary(ai));
                ups = ai.UserProperties;
                for (int p = 1; p <= ups.Count; p++)
                {
                    try {
                        up = ups[p];
                        log.Debug(up.Name + "=" + up.Value.ToString());
                    } finally {
                        up = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(up);
                    }
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed to log Appointment UserProperties", ex);
            } finally {
                ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups);
            }
        }
Пример #16
0
        public static Boolean Exists(AppointmentItem ai, MetadataId searchId, out String searchKey)
        {
            searchKey = metadataIdKeyName(searchId);

            int maxSet;
            int?keySet = getKeySet(ai, out maxSet);

            if (keySet.HasValue && keySet.Value != 0)
            {
                searchKey += "-" + keySet.Value.ToString("D2");
            }

            UserProperties ups  = null;
            UserProperty   prop = null;

            try {
                ups  = ai.UserProperties;
                prop = ups.Find(searchKey);
                if (searchId == MetadataId.gCalendarId)
                {
                    return(prop != null && prop.Value.ToString() == Settings.Instance.UseGoogleCalendar.Id);
                }
                else
                {
                    return(prop != null && Get(ai, MetadataId.gCalendarId) == Settings.Instance.UseGoogleCalendar.Id);
                }
            } catch {
                return(false);
            } finally {
                prop = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(prop);
                ups  = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups);
            }
        }
Пример #17
0
        public static String Get(AppointmentItem ai, MetadataId key)
        {
            String retVal = null;
            String searchKey;

            if (Exists(ai, key, out searchKey))
            {
                UserProperties ups  = null;
                UserProperty   prop = null;
                try {
                    ups  = ai.UserProperties;
                    prop = ups.Find(searchKey);
                    if (prop != null)
                    {
                        if (prop.Type != OlUserPropertyType.olText)
                        {
                            log.Warn("Non-string property " + searchKey + " being retrieved as String.");
                        }
                        retVal = prop.Value.ToString();
                    }
                } finally {
                    prop = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(prop);
                    ups  = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups);
                }
            }
            return(retVal);
        }
Пример #18
0
        public void EditUserProperty(UserProperties property, string value, DirectoryEntry entry)
        {
            string prop = Enum.GetName(typeof(UserProperties), property);

            entry.Properties[prop].Value = value;
            entry.CommitChanges();
        }
Пример #19
0
        public async Task <LoginResponse> LoginAsync(LoginRequest connexion)
        {
            try
            {
                if (!string.IsNullOrEmpty(UserProperties.GetApiKey()) && !client.DefaultRequestHeaders.Contains("X-Api-Key"))
                {
                    client.DefaultRequestHeaders.Add("X-Api-Key", UserProperties.GetApiKey());
                }

                var uri = new Uri(string.Format(Constants.BASE_URL + UserProperties.GetLocalIP() + Constants.API_LOGIN, string.Empty));

                var json    = JsonConvert.SerializeObject(connexion);
                var payload = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(uri, payload);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeObject <LoginResponse>(content);
                    return(result);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
            return(null);
        }
Пример #20
0
        public EditUserPropertiesRequest(UserProperties settings, string account)
        {
            account.NotEmpty();

            this.Settings = settings;
            this.Account  = account;
        }
Пример #21
0
        public static void AddUserProperty(MailItem mailitem, string ticketid)
        {
            UserProperties mailUserProperties = null;
            UserProperty   mailUserProperty   = null;

            try
            {
                mailUserProperties = mailitem.UserProperties;
                mailUserProperty   = mailUserProperties.Add("KayakoTicketId", OlUserPropertyType.olText, true, 1);
                // Where 1 is OlFormatText (introduced in Outlook 2007)
                mailUserProperty.Value = ticketid;
                mailitem.Save();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (mailUserProperty != null)
                {
                    Marshal.ReleaseComObject(mailUserProperty);
                }
                if (mailUserProperties != null)
                {
                    Marshal.ReleaseComObject(mailUserProperties);
                }
            }
        }
Пример #22
0
 protected void OnDeserialized(StreamingContext context)
 {
     if (Energieverbrauch == null)
     {
         Energieverbrauch = new List <Verbrauch>();
     }
     else if (Energieverbrauch.Count > 0)
     {
         Energieverbrauch = Energieverbrauch
                            .Select(v => Verbrauch.FixSapCdsBug(v))
                            .Where(v => !(v.Startdatum == DateTime.MinValue || v.Enddatum == DateTime.MinValue))
                            .Where(v => !(v.UserProperties != null && v.UserProperties.ContainsKey("invalid") && (bool)v.UserProperties["invalid"] == true))
                            .ToList();
         if (UserProperties != null && UserProperties.TryGetValue(Verbrauch._SAP_PROFDECIMALS_KEY, out JToken profDecimalsRaw))
         {
             var profDecimals = profDecimalsRaw.Value <int>();
             if (profDecimals > 0)
             {
                 for (int i = 0; i < profDecimals; i++)
                 {
                     // or should I import math.pow() for this purpose?
                     foreach (Verbrauch v in Energieverbrauch.Where(v => v.UserProperties == null || !v.UserProperties.ContainsKey(Verbrauch._SAP_PROFDECIMALS_KEY)))
                     {
                         v.Wert /= 10.0M;
                     }
                 }
             }
             UserProperties.Remove(Verbrauch._SAP_PROFDECIMALS_KEY);
         }
     }
 }
Пример #23
0
        internal bool IsSolutionItemEnabled(string solutionItemPath)
        {
            solutionItemPath = GetRelativeChildPath(Path.GetFullPath(solutionItemPath));
            var list = UserProperties.GetValue <List <string> > ("DisabledProjects");

            return(list == null || !list.Contains(solutionItemPath));
        }
Пример #24
0
        private static void uniTest()
        {
            //using (var fs = new System.IO.StreamWriter(Path.Combine(HomeFolder, "cpr.txt"), false))
            //{
            //    fs.Write(cprContent);
            //    fs.Close();
            //}

            UserProperties userPropsFrom = new UserProperties()
            {
                { "L", new string[] { "Boston", "Tokio" } },
                { "facsimileTelephoneNumber", null }, // new string[]{"123"}
                { "mobile", new string[] { "7" } },
                { "memberOf", new string[] { "CN=Exchange Services,CN=Users,DC=egar,DC=egartech,DC=com", "CN=IIS_IUSRS,CN=Builtin,DC=kireev,DC=local" } },
                { "mail", new string[] { "123DfG123" } },
                { "userPrincipalName", new string[] { "123" } },
            };
            UserProperties userPropsTo = new UserProperties()
            {
                { "L", new string[] { "Boston" } },
                { "facsimileTelephoneNumber", new string[] { "456" } },
                { "userAccountControl", new string[] { Convert.ToString((uint)Utils.UserAccountControl.SMARTCARD_REQUIRED) } },
                { "mobile", new string[] { "4" } },
                { "memberOf", new string[] { "CN=Exchange Services,CN=Users,DC=egar,DC=egartech,DC=com", "CN=IIS_IUSRS,CN=Builtin,DC=kireev,DC=local" } },
            };

            string        transResult;
            ADHintElement adHint = ADHintsConfigurationSection.GetOUByAttributes(userPropsTo, userPropsFrom, out transResult);

            if (adHint != null)
            {
                var qualityCheck = adHint.QualityCheck(userPropsFrom);
                //var transResult = adHint.GetTransitionByUserAttributes(userPropsFrom, userPropsTo);
            }
        }
Пример #25
0
        /// <summary>
        /// Completely remove all OGCS custom properties
        /// </summary>
        /// <param name="ai">The AppointmentItem to strip attributes from</param>
        /// <returns>Whether any properties were removed</returns>
        public static Boolean Extirpate(ref AppointmentItem ai)
        {
            List <String> keyNames = new List <String>()
            {
                metadataIdKeyName(MetadataId.forceSave),
                metadataIdKeyName(MetadataId.gCalendarId),
                metadataIdKeyName(MetadataId.gEventID),
                metadataIdKeyName(MetadataId.locallyCopied),
                metadataIdKeyName(MetadataId.ogcsModified)
            };
            Boolean        removedProperty = false;
            UserProperties ups             = null;

            try {
                ups = ai.UserProperties;
                for (int p = ups.Count; p > 0; p--)
                {
                    UserProperty prop = null;
                    try {
                        prop = ups[p];
                        if (keyNames.Exists(k => prop.Name.StartsWith(k)))
                        {
                            log.Fine("Removed " + prop.Name);
                            prop.Delete();
                            removedProperty = true;
                        }
                    } finally {
                        prop = (UserProperty)Calendar.ReleaseObject(prop);
                    }
                }
            } finally {
                ups = (UserProperties)Calendar.ReleaseObject(ups);
            }
            return(removedProperty);
        }
Пример #26
0
        public EditUserPropertiesResponse(int trid, UserProperties settings, string account)
            : base(trid, PackageType.EditUserProperties)
        {
            account.NotEmpty();

            this.Settings = settings;
            this.Account  = account;
        }
Пример #27
0
 public async override void ViewAppeared()
 {
     base.ViewAppeared();
     if (!string.IsNullOrEmpty(UserProperties.GetLocalIP()) && !string.IsNullOrEmpty(UserProperties.GetApiKey()))
     {
         await _navigationService.Navigate <MainViewModel>();
     }
 }
Пример #28
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        /// <param name="tokenSuffix">アカウント番号</param>
        /// <param name="user">操作対象のユーザー</param>
        public ShowAddToListViewModel(int tokenSuffix, UserProperties user)
        {
            this.ShowAddToList = new ShowAddToList(tokenSuffix, user);
            this.User          = this.ShowAddToList.User;
            this.Lists         = this.ShowAddToList.Lists;

            this.ApplyCommand = new RelayCommand(this.Apply);
        }
Пример #29
0
        /// <summary>
        /// it is expected the Account Xml node be formated as such:
        ///  <Account accountId="" fbAccountid="" piAccountId="" nickname="">
        ///		<AccountData>
        ///			<UserProperties>
        ///				<UserProperty Name="" Value=""/>
        ///				<UserProperty Name="" Value=""/>
        ///				<UserProperty Name="" Value=""/>
        ///				...
        ///			</UserProperties>
        ///		</AccountData>
        ///  </Account>
        /// </summary>
        /// <param name="xmlNode"></param>
        public static ServerAccount GetAccountFromXml(XmlNode xmlNode)
        {
            string accountIdString   = string.Empty;
            string fbAccountIdString = string.Empty;
            string piAccountIdString = string.Empty;
            string piSecureKeyString = string.Empty;
            string nickNameString    = string.Empty;
            string firstNameString   = string.Empty;
            string lastNameString    = string.Empty;

            if (!(XmlUtil.TryGetAttributeFromXml(ConstStrings.kAccountId, xmlNode, out accountIdString) &&              //uint
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kFbAccountId, xmlNode, out fbAccountIdString) &&          //long
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kPiAccountId, xmlNode, out piAccountIdString) &&          //
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kPiSecureKey, xmlNode, out piSecureKeyString) &&          //
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kNickName, xmlNode, out nickNameString) &&
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kFirstName, xmlNode, out firstNameString) &&
                  XmlUtil.TryGetAttributeFromXml(ConstStrings.kLastName, xmlNode, out lastNameString)))                //
            {
                StateServerAssert.Assert(new Exception("An account parameter is missing when creating a new account."));
                return(null);
            }

            AccountId accountId   = null;
            long      fbAccountId = 0;

            try
            {
                uint accountIdUInt = Convert.ToUInt32(accountIdString);
                accountId   = new AccountId(accountIdUInt);
                fbAccountId = Convert.ToInt64(fbAccountIdString);
            }
            catch (System.Exception ex)
            {
                StateServerAssert.Assert(new Exception("Error converting string to accountId type: " + ex.Data, ex));
                return(null);
            }

            XmlNode        accountDataNode = xmlNode.SelectSingleNode(ConstStrings.kAccountData);
            UserProperties userProperties  = new UserProperties();

            if (accountDataNode != null)
            {
                XmlNode userPropertiesXmlNode = accountDataNode.SelectSingleNode(ConstStrings.kUserProperties);
                //if we can't find a UserProperties node, we can just set some default values
                if (userPropertiesXmlNode != null)
                {
                    if (!UserProperties.UserPropertiesFromXml(userPropertiesXmlNode, out userProperties))
                    {
                        StateServerAssert.Assert(new Exception("Error parsing user properties from xml: " + xmlNode.OuterXml));
                        return(null);
                    }
                }
            }

            SetDefaultUserProperties(ref userProperties);

            return(new ServerAccount(accountId, fbAccountId, piAccountIdString, piSecureKeyString, nickNameString, firstNameString, lastNameString, userProperties));
        }
Пример #30
0
        public override async Task Initialize()
        {
            await base.Initialize();

            this.ConnectionStatus = "Déconnecté";
            this.ConnectionIcon   = "ic_warning_red_dark_36dp";
            this.ConnectionIP     = UserProperties.GetLocalIP();
            ManageWebsocketConnection();
        }
Пример #31
0
        public void Dispose()
        {
            if (_wsUserProperties != null)
            {
                foreach (var key in _wsUserProperties.Keys)
                {
                    _wsUserProperties[key].Dispose();
                }
                _wsUserProperties.Clear();
            }

            if (_userProperties != null)
            {
                Marshal.ReleaseComObject(_userProperties);
                _userProperties = null;
            }
        }
Пример #32
0
 public WsUserProperties(UserProperties userProperties)
 {
     _userProperties = userProperties;
 }
Пример #33
0
        /// <summary>
        /// Set selected properties of a user.
        /// </summary>
        /// <param name="userHandle">Handle to an open SAM user.</param>
        /// <param name="sourceUser">
        /// A <see cref="LocalUser"/> object containing the data to set into the user.
        /// </param>
        /// <param name="setFlags">
        /// A combination of <see cref="UserProperties"/> values indicating the properties to be set.
        /// </param>
        /// <param name="password">A <see cref="System.Security.SecureString"/>
        /// object containing the new password.
        /// </param>
        /// <param name="passwordExpired">One of the
        /// <see cref="PasswordExpiredState"/> enumeration values indicating
        /// whether the password-expired state is to be explicitly set or
        /// left as is. If the <paramref name="password"/> parameter is null,
        /// this parameter is ignored.
        /// </param>
        /// <param name="setPasswordNeverExpires">
        /// Nullable value the specifies whether the PasswordNeverExpires bit should be flipped
        /// </param>
        private void SetUserData(IntPtr userHandle,
                                 LocalUser sourceUser,
                                 UserProperties setFlags,
                                 System.Security.SecureString password,
                                 PasswordExpiredState passwordExpired,
                                 bool? setPasswordNeverExpires)
        {
            IntPtr buffer = IntPtr.Zero;

            try
            {
                UInt32 which = 0;
                UInt32 status = 0;
                UInt32 uac = GetUserAccountControl(userHandle);
                USER_ALL_INFORMATION info = new USER_ALL_INFORMATION();

                if (setFlags.HasFlag(UserProperties.AccountExpires))
                {
                    which |= SamApi.USER_ALL_ACCOUNTEXPIRES;
                    info.AccountExpires.QuadPart = sourceUser.AccountExpires.HasValue
                                                 ? sourceUser.AccountExpires.Value.ToFileTime()
                                                 : 0L;
                }
                if (setFlags.HasFlag(UserProperties.Description))
                {
                    which |= SamApi.USER_ALL_ADMINCOMMENT;
                    info.AdminComment = new UNICODE_STRING(sourceUser.Description);
                }
                if (setFlags.HasFlag(UserProperties.Enabled))
                {
                    which |= SamApi.USER_ALL_USERACCOUNTCONTROL;
                    if (sourceUser.Enabled)
                        uac &= ~SamApi.USER_ACCOUNT_DISABLED;
                    else
                        uac |= SamApi.USER_ACCOUNT_DISABLED;
                }
                if (setFlags.HasFlag(UserProperties.FullName))
                {
                    which |= SamApi.USER_ALL_FULLNAME;
                    info.FullName = new UNICODE_STRING(sourceUser.FullName);
                }

                if (setFlags.HasFlag(UserProperties.PasswordNeverExpires))
                {
                    // Only modify the bit if a change was requested
                    if (setPasswordNeverExpires.HasValue)
                    {
                        which |= SamApi.USER_ALL_USERACCOUNTCONTROL;
                        if (setPasswordNeverExpires.Value)
                            uac |= SamApi.USER_DONT_EXPIRE_PASSWORD;
                        else
                            uac &= ~SamApi.USER_DONT_EXPIRE_PASSWORD;
                    }
                }

                if (setFlags.HasFlag(UserProperties.PasswordRequired))
                {
                    which |= SamApi.USER_ALL_USERACCOUNTCONTROL;
                    if (sourceUser.PasswordRequired)
                        uac &= ~SamApi.USER_PASSWORD_NOT_REQUIRED;
                    else
                        uac |= SamApi.USER_PASSWORD_NOT_REQUIRED;
                }

                if (which != 0)
                {
                    info.WhichFields = which;
                    if ((which & SamApi.USER_ALL_USERACCOUNTCONTROL) != 0)
                        info.UserAccountControl = uac;

                    buffer = Marshal.AllocHGlobal(ClrFacade.SizeOf<USER_ALL_INFORMATION>());
                    ClrFacade.StructureToPtr<USER_ALL_INFORMATION>(info, buffer, false);

                    status = SamApi.SamSetInformationUser(userHandle,
                                                          USER_INFORMATION_CLASS.UserAllInformation,
                                                          buffer);
                    ThrowOnFailure(status);
                    status = SamApi.SamFreeMemory(buffer);
                    buffer = IntPtr.Zero;
                }

                if (setFlags.HasFlag(UserProperties.UserMayChangePassword))
                    SetUserMayChangePassword(userHandle, sourceUser.SID, sourceUser.UserMayChangePassword);

                if (password != null)
                    SetUserPassword(userHandle, password, passwordExpired);
            }
            finally
            {
                if (buffer != IntPtr.Zero)
                {
                    ClrFacade.DestroyStructure<USER_ALL_INFORMATION>(buffer);
                    Marshal.FreeHGlobal(buffer);
                }
            }
        }
        /// <summary>
        /// Gets the user info object for the currently logged in user.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <returns>
        /// The <see cref="T:UserInfo"/>, or <c>null</c>.
        /// </returns>
        /// <exception cref="ArgumentNullException">If <paramref name="username"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="username"/> is empty.</exception>
        public UserInfo GetUser(string username)
        {
            try {
                var user = StorageProvider.GetUser(username);

                if(user != null)
                    return user;

                if(m_Config.CaseInsensitive) {
                    UserInfo[] all = StorageProvider.GetUsers();

                    int userIndex = Array.BinarySearch(all, new UserInfo(username, null, null, true, DateTime.MinValue, null), new UsernameComparer());

                    if(userIndex >= 0)
                        return all[userIndex];
                }

                // Active Directory Attributes
                //
                // http://msdn.microsoft.com/en-us/library/ms683980(VS.85).aspx
                //
                // Object-Sid       -> objectSid      (required, single-value)
                // Object-Class     -> objectClass    (required, multi-value)
                // Object-Category  -> objectCategory (required, single-value)
                // SAM-Account-Name -> sAMAccountName (required, single-value)
                // E-mail-Addresses -> mail           (optional, single-value)
                // Display-Name     -> displayName    (optional, single-value)
                // Is-Member-Of-DL  -> memberOf       (optional, multi-value)

                using(Domain domain = m_Config.GetDomain()) {
                    SearchResult result;

                    try {
                        using(DirectoryEntry searchRoot = domain.GetDirectoryEntry()) {
                            using(var searcher = new DirectorySearcher(searchRoot)) {
                                searcher.Filter = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", username);

                                searcher.PropertiesToLoad.Add("objectSid");
                                searcher.PropertiesToLoad.Add("mail");
                                searcher.PropertiesToLoad.Add("displayName");
                                searcher.PropertiesToLoad.Add("memberOf");
                                searcher.PropertiesToLoad.Add("primaryGroupID");

                                result = searcher.FindOne();
                            }
                        }

                        if(result == null)
                            return null;
                    }

                    catch(Exception ex) {
                        LogEntry(LogEntryType.Error, "Unable to complete search for user \"{0}\": {1}", username, ex);
                        return null;
                    }

                    UserProperties userProperties;

                    try {
                        userProperties = new UserProperties {
                            ObjectSid = result.Properties["objectSid"].Cast<byte[]>().Single(),
                            Mail = result.Properties["mail"].Cast<string>().SingleOrDefault(),
                            DisplayName = result.Properties["displayName"].Cast<string>().SingleOrDefault(),
                            MemberOf = result.Properties["memberOf"].Cast<string>().ToList(),
                            PrimaryGroupID = result.Properties["primaryGroupID"].Cast<int>().Single(),
                        };
                    }

                    catch(Exception ex) {
                        LogEntry(LogEntryType.Error, "Unable to access properties for user \"{0}\": {1}", username, ex);
                        return null;
                    }

                    if(userProperties.Mail == null) {
                        if(m_Config.AutomaticMail != null && !string.IsNullOrEmpty(userProperties.DisplayName)) {
                            userProperties.Mail = userProperties.DisplayName.Replace(" ", ".") + "@" + m_Config.AutomaticMail;
                        }
                        else {
                            LogEntry(LogEntryType.Error, "Cannot login user \"{0}\" because they have no email address.", username);
                            return null;
                        }
                    }

                    CreatePrimaryGroupSID(userProperties.ObjectSid, userProperties.PrimaryGroupID);

                    string primaryGroupPath = String.Format("<SID={0}>", BuildOctetString(userProperties.ObjectSid));

                    userProperties.MemberOf.Add(primaryGroupPath);

                    var domainGroups = new List<string>();

                    foreach(string memberOfPath in userProperties.MemberOf) {
                        try {
                            using(var memberOfEntry = domain.GetDirectoryEntry()) {
                                string basePath = memberOfEntry.Path.Remove(memberOfEntry.Path.LastIndexOf("/"));

                                memberOfEntry.Path = String.Format("{0}/{1}", basePath, memberOfPath);

                                var samAccountName = memberOfEntry.Properties["sAMAccountName"].Cast<string>().Single();

                                domainGroups.Add(samAccountName);
                            }
                        }

                        catch(Exception ex) {
                            LogEntry(LogEntryType.Error, "Skipping group \"{0}\" due to lookup error: {1}", memberOfPath, ex);
                            continue;
                        }
                    }

                    var wikiGroups = m_Config.GetWikiGroups(domainGroups);

                    if(wikiGroups.Count == 0) {
                        LogEntry(LogEntryType.Error, "Refusing to create user \"{0}\" without any groups, please check the GroupMap configuration.", username);
                        return null;
                    }

                    user = StorageProvider.AddUser(username, userProperties.DisplayName, GeneratePassword(), userProperties.Mail, true, DateTime.Now);

                    if(user == null) {
                        LogEntry(LogEntryType.Error, "Failed to create user \"{0}\" using provider \"{1}\", but no error was given by the provider.", username, StorageProvider.GetType());
                        return null;
                    }

                    LogEntry(LogEntryType.General, "Created user \"{0}\" using provider \"{1}\", but no group membership has been set yet.", username, StorageProvider.GetType());

                    user = StorageProvider.SetUserMembership(user, wikiGroups.ToArray());

                    if(user == null) {
                        LogEntry(LogEntryType.Error, "Failed to set user membership for user \"{0}\" using provider \"{1}\", but no error was given by the provider.", username, StorageProvider.GetType());
                        return null;
                    }

                    LogEntry(LogEntryType.General, "Set user membership for user \"{0}\" using provider \"{1}\", user is ready for use.", username, StorageProvider.GetType());

                    return user;
                }
            }

            catch(Exception ex) {
                LogEntry(LogEntryType.Error, "Error looking up user: {0}", ex);
                return null;
            }
        }