public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var          values     = new Identities();
            IdentityType?currentKey = null;

            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                case JsonToken.PropertyName:
                    IdentityType?key = GetEnum((string)reader.Value);

                    if (!key.HasValue)
                    {
                        throw new SerializationException($"Did not recognize {reader.Value} as a valid Identity Type.");
                    }

                    currentKey = key.Value;
                    break;

                case JsonToken.String:
                    if (currentKey.HasValue && reader.Value != null)
                    {
                        values.Add(currentKey.Value, (string)reader.Value);
                    }

                    break;

                case JsonToken.EndObject:
                    return(values);
                }
            }

            return(values);
        }
        private static void CreateProtocolAndAdvise(Lifetime lifetime, List <ProtocolInstance> list, string solutionName)
        {
            try
            {
                var dispatcher = MainThreadDispatcher.Instance;
                var riderProtocolController = new RiderProtocolController(dispatcher, lifetime);
                list.Add(new ProtocolInstance(riderProtocolController.Wire.Port, solutionName));

#if !NET35
                var serializers = new Serializers(lifetime, null, null);
#else
                var serializers = new Serializers();
#endif
                var identities = new Identities(IdKind.Server);

                MainThreadDispatcher.AssertThread();
                var protocol = new Protocol("UnityEditorPlugin" + solutionName, serializers, identities, MainThreadDispatcher.Instance, riderProtocolController.Wire, lifetime);
                riderProtocolController.Wire.Connected.WhenTrue(lifetime, connectionLifetime =>
                {
                    ourLogger.Log(LoggingLevel.VERBOSE, "Create UnityModel and advise for new sessions...");
                    var model = new EditorPluginModel(connectionLifetime, protocol);
                    AdviseUnityActions(model, connectionLifetime);
                    AdviseEditorState(model);
                    OnModelInitialization(new UnityModelAndLifetime(model, connectionLifetime));
                    AdviseRefresh(model);
                    InitEditorLogPath(model);

                    model.UnityProcessId.SetValue(Process.GetCurrentProcess().Id);
                    model.UnityApplicationData.SetValue(new UnityApplicationData(
                                                            EditorApplication.applicationPath,
                                                            EditorApplication.applicationContentsPath, UnityUtils.UnityApplicationVersion));
                    model.ScriptingRuntime.SetValue(UnityUtils.ScriptingRuntime);

                    if (UnityUtils.UnityVersion >= new Version(2018, 2))
                    {
                        model.ScriptCompilationDuringPlay.Set(EditorPrefsWrapper.ScriptChangesDuringPlayOptions);
                    }
                    else
                    {
                        model.ScriptCompilationDuringPlay.Set((int)PluginSettings.AssemblyReloadSettings);
                    }

                    AdviseShowPreferences(model, connectionLifetime, ourLogger);
                    AdviseGenerateUISchema(model);
                    AdviseExitUnity(model);
                    GetBuildLocation(model);
                    AdviseRunMethod(model);
                    GetInitTime(model);

                    ourLogger.Verbose("UnityModel initialized.");
                    var pair = new ModelWithLifetime(model, connectionLifetime);
                    connectionLifetime.OnTermination(() => { UnityModels.Remove(pair); });
                    UnityModels.Add(pair);
                });
            }
            catch (Exception ex)
            {
                ourLogger.Error("Init Rider Plugin " + ex);
            }
        }
Example #3
0
 private void CheckUsername(string username)
 {
     if (Identities.Any(x => String.Equals(x.Username, username, StringComparison.InvariantCultureIgnoreCase)))
     {
         throw new DuplicateUsernameException("The username '" + username + "' is already in use.");
     }
 }
Example #4
0
        private void AddIdentity(string name, string version, string hintPath)
        {
            if (name.IsNullOrEmpty())
            {
                throw new ArgumentNullException("name");
            }

            foreach (char c in name)
            {
                if (!char.IsLetterOrDigit(c) && c != '.' && c != '_')
                {
                    throw new Exception(PlugInConst.ManifestIdentity + " name contains invalid character: '" + c + "'");
                }
            }
            Version v = PlugInReference.ParseVersion(version, hintPath);

            if (PrimaryVersion == null)
            {
                PrimaryVersion = v;
            }
            if (PrimaryIdentity == null)
            {
                PrimaryIdentity = name;
            }

            Identities.Add(name, v);
        }
Example #5
0
 private void InitDbIdentity()
 {
     if (_dbId == null)
     {
         lock (_lockObject)
         {
             if (_dbId == null)
             {
                 var identity = Identities.FirstOrDefault();
                 if (identity == null)
                 {
                     var guid = Guid.NewGuid().ToByteArray();
                     identity = new IdentityEntity()
                     {
                         Data = guid
                     };
                     Identities.Add(identity);
                     SaveChanges();
                 }
                 _dbId = identity.Data;
                 Console.WriteLine($"SQLite ID:{_dbId.ToHexString()}");
             }
         }
     }
 }
Example #6
0
        public async Task <IActionResult> ForgotPassword(string email)
        {
            if (ModelState.IsValid)
            {
                var user = await Identities.GetUserByUsernameAsync(email);

                if (user == null)
                {
                    return(RedirectToAction("ForgotPasswordConfirm"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                // Send an email with this link
                var result = await Identities.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.Action("ForgotPasswordCallback", "Account", new { userId = user.Id, code = result.Token }, HttpContext.Request.Scheme);
                await Communication.SendForgotPassword(user, callbackUrl);

                return(RedirectToAction("ForgotPasswordConfirm"));
            }
            else
            {
                var invalidProperty = ModelState.First(x => x.Value.ValidationState == ModelValidationState.Invalid);
                SetUserError("תקלה במידע שהתקבל", invalidProperty.Value.Errors.FirstOrDefault()?.ErrorMessage ?? "אנא נסו שוב");
                return(View());
            }
        }
Example #7
0
 public IActionResult GetListByUsrName(int pageIndex, int rowCount, string userName, string usrType)
 {
     /*判断是否合法*/
     if (ModelState.IsValid)
     {
         try
         {
             if (string.IsNullOrEmpty(usrType))
             {
                 usrType = "2,3";
             }
             IList <HelpCenter.Model.Usr> usrList =
                 HelpCenter.BLL.Usr.GetListByUsrName(pageIndex, rowCount, out int _totalCount, out int _pageCount, userName, usrType,
                                                     User.Identities.First(u => u.IsAuthenticated).FindFirst("UsrDeptId").Value);
             return(null == usrList
                 ? Ok(new { result = false, tips = ResponseMessageTips.MSG_USR_INFO_NO_FOUND })
                 : Ok(new
             {
                 result = true,
                 tips = ResponseMessageTips.MSG_PROCESS_SUCCESS,
                 data = new { totalCount = _totalCount, pageCount = _pageCount, info = usrList }
             }));
         }
         catch (Exception e)
         {
             return(Ok(new { result = false, tips = ResponseMessageTips.MSG_PROCESS_EXCEPTION + e.Message.ToString() }));
         }
     }
     return(Ok(new { result = false, tips = ResponseMessageTips.MSG_PROCESS_DATA_FORMAT_ERROR }));
 }
Example #8
0
        public async Task <IActionResult> Login(AccountLoginViewModel model)
        {
            var returnModel = new AccountViewModel()
            {
                Login = model
            };

            if (ModelState.IsValid)
            {
                var result = await Identities.LoginAsync(model.Email, model.Password, true);

                if (result.IsSuccess)
                {
                    var cookieConsent = HttpContext.Features.Get <ITrackingConsentFeature>();
                    cookieConsent.GrantConsent();
                    return(RedirectToAction("Index", "Personal", new { area = "Participant" }));
                }
                else
                {
                    SetUserError("כשלון בהתחברות ", result.Details);
                    return(View("LoginOrRegister", returnModel));
                }
            }
            else
            {
                var invalidProperty = ModelState.First(x => x.Value.ValidationState == ModelValidationState.Invalid);
                SetUserError("תקלה במידע שהתקבל", invalidProperty.Value.Errors.FirstOrDefault()?.ErrorMessage ?? "אנא נסו שוב");
                return(View("LoginOrRegister", returnModel));
            }

            // If we got this far, something failed, redisplay form
            return(View("LoginOrRegister", model));
        }
 public void Render(Message message, Identities source)
 {
     foreach (var nestedRenderer in _nestedRenderers)
     {
         nestedRenderer.Render(message, source);
     }
 }
Example #10
0
 public void Render(Message message, Identities source)
 {
     if (message.Level >= _level)
     {
         _nestedRenderer.Render(message, source);
     }
 }
        public ICommand ToCommand(Object serial, Stream stream, Encoding encoding)
        {
            if (stream == null)
            {
                return(default(ICommand));
            }

            CommandIdentifier identifier = null;

            if (Identities != null && Identities.ContainsKey(serial))
            {
                identifier = (CommandIdentifier)Identities [serial];
            }

            if (identifier == null)
            {
                return(default(ICommand));
            }

            Object command = null;

            // create a reader, using the specific encoding of the socket
            using (StreamReader reader = new StreamReader(stream, encoding)) {
                //XmlDocument xmldoc = new XmlDocument();
                //xmldoc.Load (reader);

                // create a serializer for the given object type.
                XmlSerializer serializer = new XmlSerializer(identifier.CommandType);
                //XmlWriterSettings settings = new XmlWriterSettings();
                //settings.Encoding = encoding;
                //settings.Indent = false;

                //XmlReader reader = XmlReader.Create(stream, settings);
                command = serializer.Deserialize(reader);
                //xmldoc.

/*
 *              using (XmlReader xmlr = XmlReader.Create(reader)) {
 *                  XmlDocument xml = new XmlDocument();
 *
 *              }
 */

//                    // serializer lock, making it thread safe.
//                    lock (SerializerLock) {
//                        c = Serializer.Deserialize(reader);
//                       reader.Close();
//                   }
            }

            if (!(command is ICommand))
            {
                // TODO throw exception
                return(default(ICommand));
            }


            return((ICommand)command);
        }
        private static void Init()
        {
            var projectDirectory = Directory.GetParent(Application.dataPath).FullName;

            var projectName = Path.GetFileName(projectDirectory);

            SlnFile = Path.GetFullPath($"{projectName}.sln");

            InitializeEditorInstanceJson();

            // for the case when files were changed and user just alt+tab to unity to make update, we want to fire
            CsprojAssetPostprocessor.OnGeneratedCSProjectFiles();

            Log.DefaultFactory = new RiderLoggerFactory();

            var lifetimeDefinition = Lifetimes.Define(EternalLifetime.Instance);
            var lifetime           = lifetimeDefinition.Lifetime;

            AppDomain.CurrentDomain.DomainUnload += (EventHandler)((_, __) =>
            {
                ourLogger.Verbose("lifetimeDefinition.Terminate");
                lifetimeDefinition.Terminate();
            });

            Debug.Log($"Rider plugin initialized. Logs are in: {LogPath}. Current Logging Level {PluginSettings.SelectedLoggingLevel}. Change it in Unity Preferences -> Rider.");

            try
            {
                var riderProtocolController = new RiderProtocolController(MainThreadDispatcher.Instance, lifetime);

                var serializers = new Serializers();
                var identities  = new Identities(IdKind.Server);

                MainThreadDispatcher.AssertThread();

                riderProtocolController.Wire.Connected.View(lifetime, (lt, connected) =>
                {
                    if (connected)
                    {
                        var protocol = new Protocol(serializers, identities, MainThreadDispatcher.Instance, riderProtocolController.Wire);
                        ourLogger.Log(LoggingLevel.VERBOSE, "Create UnityModel and advise for new sessions...");

                        ourModel.Value = CreateModel(protocol, lt);
                    }
                    else
                    {
                        ourModel.Value = null;
                    }
                });
            }
            catch (Exception ex)
            {
                ourLogger.Error("Init Rider Plugin " + ex);
            }

            ourAssetHandler = new OnOpenAssetHandler(ourModel, ourRiderPathLocator, ourPluginSettings, SlnFile);

            ourInitialized = true;
        }
Example #13
0
        /// <summary>
        /// Metoda wykonywana za każdym razem gdy użytkownik zmieni zaznaczenie wiersza w DataGridViewIdentitys
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewIdentities_SelectionChanged(object sender, EventArgs e)
        {
            // Pobranie zaznaczonych danych z tabeli
            Identities identities = (Identities)dataGridViewIdentities.CurrentRow.DataBoundItem;

            // Zmiana wyświetlanego zdjęcia
            pictureBoxPhoto.Image = ConvertByteArrayToImage(identities.Image);
        }
Example #14
0
 public void Render(Message message, Identities source)
 {
     _writerProvider.Value.WriteLine("<tr class='item {0}'>", message.Level);
     _writerProvider.Value.WriteLine("<td>{0}</td>", message.Level);
     _writerProvider.Value.WriteLine("<td>{0}</td>", string.Join(" -> ", source.Items.Select(id => id.Value).ToArray()));
     _writerProvider.Value.WriteLine("<td><pre>{0}</pre></td>", message.Text);
     _writerProvider.Value.WriteLine("</tr>");
 }
Example #15
0
 /// <inheritdoc/>
 public override string ToString()
 {
     return(string.Format(
                "Delete from '{0}' where ({1}){2}",
                SourceTablePath,
                string.Join(" and ",
                            Identities.Select(pair => pair.ToString()).ToArray()),
                PostCopy ? " (after data copying)" : string.Empty));
 }
Example #16
0
 /// <inheritdoc/>
 public override string ToString()
 {
     return(string.Format(
                "Update '{0}' set ({1}) where ({2})",
                SourceTablePath,
                string.Join(", ", UpdateParameter.Select(pair =>
                                                         string.Format("{0}={1}", pair.First, pair.Second ?? "Default"))
                            .ToArray()),
                string.Join(" and ", Identities.Select(pair => pair.ToString()).ToArray())));
 }
Example #17
0
        private void SaveIdentities(string root)
        {
            Identities identities = new Identities(_applicationIdentity, _assemblyIdentity, _domainIdentity);

            using (FileStream fs = File.OpenWrite(root + ".storage")) {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, identities);
                fs.Close();
            }
        }
Example #18
0
        private async Task RefreshAccounts()
        {
            Trace($"Refresh accounts");

            var accounts = Identities.SelectMany(i => i.Accounts.Where(a => a.IsLive));

            var tasks = accounts.Select(a => a.Refresh(this));

            await Task.WhenAll(tasks);
        }
        private static DteProtocolModel SetupModel(Lifetime lifetime, int port)
        {
            IScheduler scheduler   = new SimpleInpaceExecutingScheduler(Logger.GetLogger <ConnectionManager>());
            var        server      = new SocketWire.Client(lifetime, scheduler, port);
            var        serializers = new Serializers();
            var        identities  = new Identities(IdKind.Client);
            var        protocol    = new Protocol(Protocol, serializers, identities, scheduler, server, lifetime);

            return(new DteProtocolModel(lifetime, protocol));
        }
Example #20
0
 public virtual DynamicJsonValue ToJson()
 {
     return(new DynamicJsonValue(GetType())
     {
         [nameof(Documents)] = Documents.ToJson(),
         [nameof(RevisionDocuments)] = RevisionDocuments.ToJson(),
         [nameof(Tombstones)] = Tombstones.ToJson(),
         [nameof(Identities)] = Identities.ToJson(),
         [nameof(Indexes)] = Indexes.ToJson(),
     });
 }
 internal static void AddUserIdentities(Identities identities, IdentityApiRequest identityApiRequest)
 {
     if (identityApiRequest != null)
     {
         var userIdentities = identityApiRequest.UserIdentities;
         foreach (var identity in userIdentities)
         {
             identities[(IdentityType)identity.Key] = identity.Value;
         }
     }
 }
 /// <inheritdoc/>
 public override string ToString()
 {
     return(string.Format(
                "Copy from '{0}' to '{1}' where ({2})",
                string.Join(", ", CopiedColumns.Select(pair => pair.First)
                            .ToArray()),
                string.Join(", ", CopiedColumns.Select(pair => pair.Second)
                            .ToArray()),
                string.Join(" and ", Identities.Select(pair => pair.ToString())
                            .ToArray())));
 }
Example #23
0
        /// <summary>
        /// Change the Username of an Identity.
        /// </summary>
        public void ChangeUsername(Guid identityId, string username)
        {
            CheckUsername(username);
            var identity = Identities.FirstOrDefault(x => x.Id == identityId);

            if (identity == null)
            {
                throw new Exception("Identity does not belong to this System.");
            }
            identity.ChangeUsername(username);
        }
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (_publicProperties != null ? _publicProperties.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Id != null ? Id.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (DisplayName != null ? DisplayName.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (AvatarUrl != null ? AvatarUrl.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Identities != null ? Identities.GetHashCode() : 0);
         return(hashCode);
     }
 }
Example #25
0
        private int AddUpdateEntry(Update update, XDocument updateXmlDoc)
        {
            var newUpdateIndex = Identities.Count;

            Identities.Add(update.Identity);

            IdentityToIndex.Add(update.Identity, newUpdateIndex);
            IndexToIdentity.Add(newUpdateIndex, update.Identity);

            if (update is Detectoid)
            {
                UpdateTypeMap.Add(newUpdateIndex, (uint)UpdateType.Detectoid);
                Categories.TryAdd(update.Identity, update);
            }
            else if (update is Classification)
            {
                UpdateTypeMap.Add(newUpdateIndex, (uint)UpdateType.Classification);
                Categories.TryAdd(update.Identity, update);
            }
            else if (update is Product)
            {
                UpdateTypeMap.Add(newUpdateIndex, (uint)UpdateType.Product);
                Categories.TryAdd(update.Identity, update);
            }
            else if (update is SoftwareUpdate)
            {
                UpdateTypeMap.Add(newUpdateIndex, (uint)UpdateType.Software);
                Updates.TryAdd(update.Identity, update);
            }
            else if (update is DriverUpdate)
            {
                UpdateTypeMap.Add(newUpdateIndex, (uint)UpdateType.Driver);
                Updates.TryAdd(update.Identity, update);
            }

            ExtractAndIndexTitle(newUpdateIndex, updateXmlDoc);

            AddedUpdates.Add(newUpdateIndex, update);

            AddUpdateBundleInformation(newUpdateIndex, update.Identity, updateXmlDoc);
            AddPrerequisiteInformation(newUpdateIndex, update.Identity, updateXmlDoc);
            AddUpdateFileInformationToIndex(newUpdateIndex, update.Identity, updateXmlDoc);
            ExtractSupersedingInformation(newUpdateIndex, update.Identity, updateXmlDoc);

            if (update is DriverUpdate)
            {
                ExtractAndIndexDriverMetadata(newUpdateIndex, updateXmlDoc);
            }

            ExtractAndIndexKbArticle(newUpdateIndex, updateXmlDoc, update);

            return(newUpdateIndex);
        }
        private IdentityRequest BuildIdentityRequest(IdentityApiRequest identityApiRequest)
        {
            var identityRequest = new IdentityRequest();

            PopulateBaseIdentityRequest(identityRequest);
            var identities = new Identities();

            AddDeviceIdentities(identities);
            AddUserIdentities(identities, identityApiRequest);
            identityRequest.KnownIdentities = identities;
            return(identityRequest);
        }
Example #27
0
        public async Task <IActionResult> Logout()
        {
            var myCookies = Request.Cookies.Keys;

            foreach (var cookie in myCookies)
            {
                Response.Cookies.Delete(cookie);
            }
            await Identities.LogoutAsync(Actor.Me.Id);

            return(RedirectToAction("Login"));
        }
        private static void CreateProtocolAndAdvise(Lifetime lifetime, List <ProtocolInstance> list, string solutionFileName)
        {
            try
            {
                var dispatcher = MainThreadDispatcher.Instance;
                var riderProtocolController = new RiderProtocolController(dispatcher, lifetime);
                list.Add(new ProtocolInstance(riderProtocolController.Wire.Port, solutionFileName));

                var serializers = new Serializers();
                var identities  = new Identities(IdKind.Server);

                MainThreadDispatcher.AssertThread();

                riderProtocolController.Wire.Connected.WhenTrue(lifetime, connectionLifetime =>
                {
                    var protocol = new Protocol("UnityEditorPlugin", serializers, identities, MainThreadDispatcher.Instance, riderProtocolController.Wire);
                    ourLogger.Log(LoggingLevel.VERBOSE, "Create UnityModel and advise for new sessions...");
                    var model = new EditorPluginModel(connectionLifetime, protocol);
                    AdviseUnityActions(model, connectionLifetime);
                    AdviseEditorState(model);
                    OnModelInitialization(new UnityModelAndLifetime(model, connectionLifetime));
                    AdviseRefresh(model);
                    InitEditorLogPath(model);
                    AdviseScriptCompilationDuringPlay(model, connectionLifetime);

                    model.UnityProcessId.Set(Process.GetCurrentProcess().Id);
                    model.FullPluginPath.AdviseNotNull(connectionLifetime, AdditionalPluginsInstaller.UpdateSelf);
                    model.ApplicationPath.SetValue(EditorApplication.applicationPath);
                    model.ApplicationContentsPath.SetValue(EditorApplication.applicationContentsPath);
                    model.ApplicationVersion.SetValue(Application.unityVersion);
                    model.ScriptingRuntime.SetValue(UnityUtils.ScriptingRuntime);

                    if (UnityUtils.UnityVersion >= new Version(2018, 2) && EditorPrefsWrapper.ScriptChangesDuringPlayOptions == 0)
                    {
                        model.NotifyIsRecompileAndContinuePlaying.Fire("General");
                    }
                    else if (UnityUtils.UnityVersion < new Version(2018, 2) && PluginSettings.AssemblyReloadSettings == AssemblyReloadSettings.RecompileAndContinuePlaying)
                    {
                        model.NotifyIsRecompileAndContinuePlaying.Fire("Rider");
                    }

                    ourLogger.Verbose("UnityModel initialized.");
                    var pair = new ModelWithLifetime(model, connectionLifetime);
                    connectionLifetime.AddAction(() => { UnityModels.Remove(pair); });
                    UnityModels.Add(pair);
                    new UnityEventLogSender(ourLogEventCollector);
                });
            }
            catch (Exception ex)
            {
                ourLogger.Error("Init Rider Plugin " + ex);
            }
        }
Example #29
0
        public void PlusSingleIdentity()
        {
            var first = new Identities(new Identity("1"), new Identity("2"));
            var second = new Identity("3");

            var result = first + second;

            Assert.That(result.Items.Length, Is.EqualTo(3));
            Assert.That(result.Items[0].Value, Is.EqualTo("1"));
            Assert.That(result.Items[1].Value, Is.EqualTo("2"));
            Assert.That(result.Items[2].Value, Is.EqualTo("3"));
        }
Example #30
0
 public Wallet()
 {
     Identities.Clear();
     Identities.Add(new Identity {
         Label = "NewIdentity", IsDefault = true, Lock = false, Extra = null, Controls = new List <Control> {
             new Control("6Pxxxxxxxxx", "1")
         }, Ontid = "did:ont:AMxxxxxxxxxxxxxxxxxxxxxxx"
     });
     Accounts.Add(new Account {
         Address = "TA6xxxxxxxxxxxx", Key = "6Pxxxxxxxxxxx", Hash = "sha256", Label = "NewAccount", PublicKey = "1202xxxxxxxxxxxxxx", SignatureScheme = "SHA256withECDSA", PasswordHash = "passwordhash"
     });
     Scrypt = new Scrypt(16384, 8, 8);
 }
Example #31
0
        public async Task Seed()
        {
            if (await Identities.AnyAsync() || await PasswordAuthentications.AnyAsync())
            {
                return;
            }

            await Identities.AddRangeAsync(Seeder.Identites);

            await PasswordAuthentications.AddRangeAsync(Seeder.PasswordAuths);

            await SaveChangesAsync();
        }
Example #32
0
        public async void DeleteAccount(Account account)
        {
            Trace($"Delete {account}");

            var manager = Identities.FirstOrDefault(i => i.AccountID == account.ManagerID);

            if (manager != null)
            {
                await manager.DeleteAccount(account, Connection);
            }

            Uncache(account);
        }
Example #33
0
        public void GivenMappingsBetweenTheFollowingTags(Table table)
        {
            var mappings           = table.Rows.Select(row => (Source: row["Source"], From: row["From"], To: Guid.Parse(row["To"])));
            var identitiesBySource = mappings.GroupBy(row => row.Source);
            var identitiesSource   = identitiesBySource.ToDictionary(entry => entry.Key,
                                                                     entry => entry.ToDictionary(entryForSource => entryForSource.From,
                                                                                                 entryForSource => entryForSource.To)).ToDictionary(entry => entry.Key,
                                                                                                                                                    entry => new TimeSeriesByTag(entry.Value));

            var identities = new Identities(identitiesSource);

            _container.RegisterInstanceAs <Identities>(identities);
        }
Example #34
0
        public async Task <IActionResult> Register(AccountRegisterViewModel model)
        {
            var returnModel = new AccountViewModel()
            {
                Register = model
            };

            if (ModelState.IsValid)
            {
                var participant = new LongTermParticipant
                {
                    YearOfBirth          = model.YearOfBirth,
                    UserName             = model.Email,
                    FullName             = model.FullName,
                    Email                = model.Email,
                    IsAllowingPromotions = model.IsAllowingPromotions,
                    PhoneNumber          = model.PhoneNumber,
                };
                var addResult = await Identities.AddNewParticipant(participant, model.Password);

                if (addResult.IsSuccess)
                {
                    await Communication.SendWelcomeMessageAsync(participant);

                    var signInResult = await Identities.LoginAsync(model.Email, model.Password, true);

                    if (signInResult.IsSuccess)
                    {
                        var cookieConsent = HttpContext.Features.Get <ITrackingConsentFeature>();
                        cookieConsent.GrantConsent();
                        return(RedirectToAction("Index", "Personal", new { area = "Participant" }));
                    }
                    else
                    {
                        SetUserError("כשלון בהתחברות לאחר רישום", signInResult.Details);
                        return(View("LoginOrRegister", returnModel));
                    }
                }
                else
                {
                    SetUserError("תקלה ביצירת משתתף", addResult.Errors.FirstOrDefault());
                    return(View("LoginOrRegister", returnModel));
                }
            }
            else
            {
                var invalidProperty = ModelState.First(x => x.Value.ValidationState == ModelValidationState.Invalid);
                SetUserError("תקלה במידע שהתקבל", invalidProperty.Value.Errors.FirstOrDefault()?.ErrorMessage ?? "אנא נסו שוב");
                return(View("LoginOrRegister", returnModel));
            }
        }
Example #35
0
 private TaskContext(
     IResultsStorage results, 
     IExecutionStrategy executionStrategy, 
     Identity identity, 
     ILogRenderer logRenderer, 
     IDirectory workDirectory, 
     IEnvironment environment, 
     ITaskInterceptor interceptor, 
     Identities identitiesTail)
 {
     _identity = identity;
     _results = results;
     _executionStrategy = executionStrategy;
     _logRenderer = logRenderer;
     _workDirectory = workDirectory;
     _environment = environment;
     _interceptor = interceptor;
     _identitiesTail = identitiesTail;
     _log = new LogHelper(message => logRenderer.Render(message, GetFullIdentitiesPath()));
 }
Example #36
0
        public Layer[] Compose(RegisteredTasks map, Identities filter)
        {
            var allTasks = GetAllTasks(map, filter);
            var result = new List<Layer>();

            while (allTasks.Any())
            {
                var layerTasks = allTasks.Where(task => AllDependenciesResolved(map, task.Id, result));
                var layer = new Layer(layerTasks.Select(x => new ExecutableWithIdentity(x.Task, x.Id)).ToArray());

                if (layer.IsEmpty)
                {
                    throw new Exception(GetErrorMessage(allTasks, result));
                }

                result.Add(layer);
                allTasks = allTasks.Where(item => !layer.Contains(item.Task)).ToList();
            }

            return result.ToArray();
        }
Example #37
0
        private static List<ExecutableWithIdentity> GetAllTasks(RegisteredTasks map, Identities filter)
        {
            if (filter.IsEmpty)
            {
                return map.Transform((id, task) => new ExecutableWithIdentity(task.Task, id)).ToList();
            }

            List<ExecutableWithIdentity> result = new List<ExecutableWithIdentity>();
            Identities currentTasks = filter;

            while (true)
            {
                if (currentTasks.IsEmpty)
                {
                    return result;
                }

                int oldResultSize = result.Count;
                IEnumerable<ExecutableWithIdentity> iterationDependencies = map.Transform(currentTasks, (id, task) => new ExecutableWithIdentity(task.Task, id));
                foreach (ExecutableWithIdentity dependency in iterationDependencies)
                {
                    if (!result.Any(x => x.Id == dependency.Id))
                    {
                        result.Add(dependency);
                    }
                }

                int newResultSize = result.Count;

                if (newResultSize == oldResultSize)
                {
                    return result;
                }

                currentTasks = new Identities(currentTasks
                    .Items
                    .SelectMany(task => map[task].Dependencies.Items)
                    .ToArray());
            }
        }
        public void Render(Message message, Identities source)
        {
            lock (_lockObject)
            {
                var level = message.Level;

                if (_lastSource == null || !Equals(_lastSource, source))
                {
                    for (int index = 0; index < source.Items.Length; index++)
                    {
                        Identity identity = source.Items[index];

                        WriteColored("[", ConsoleColor.DarkMagenta);
                        WriteColored(identity.Value, ConsoleColor.DarkMagenta);
                        WriteColored("]", ConsoleColor.DarkMagenta);

                        if (index < source.Items.Length - 1)
                        {
                            WriteColored("->", ConsoleColor.DarkCyan);
                        }
                    }

                    Console.WriteLine();
                }

                var lines = message.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();
                var procesedLines = new List<string>();

                const int fullIndentSize = 8;

                var maxWidth = _consoleWidth - fullIndentSize - 1;
                foreach (var line in lines)
                {
                    var currentLine = line;
                    while (currentLine.Length > maxWidth)
                    {
                        procesedLines.Add(currentLine.Substring(0, maxWidth));
                        currentLine = currentLine.Substring(maxWidth);
                    }

                    procesedLines.Add(currentLine);
                }

                if (procesedLines.Count > 0)
                {
                    var levelString = " " + level.ToString().ToUpper();
                    WriteColored(levelString, ConsoleColor.DarkGray);
                    Console.Write(new string(' ', fullIndentSize - levelString.Length));

                    WriteColored(procesedLines[0], GetColorForLevel(level));
                    Console.WriteLine();

                    if (procesedLines.Count > 1)
                    {
                        for (int i = 1; i < procesedLines.Count; i++)
                        {
                            Console.Write(new string(' ', fullIndentSize));
                            WriteColored(procesedLines[i], GetColorForLevel(level));
                            Console.WriteLine();
                        }
                    }
                }
                else
                {
                    Console.WriteLine();
                }

                _lastSource = source;
            }
        }
 private IEnumerable<Layer> ComposeWithFilter(TaskMap map, Identities filter)
 {
     return new SimpleLayersComposer().Compose(new RegisteredTasks(map.Map, null, Identities.Empty), filter);
 }
 private IEnumerable<Layer> ComposeWithAllTasksAsFilter(TaskMap map)
 {
     var startupTaskIds = new Identities(map.Map.Keys.ToArray());
     return new SimpleLayersComposer().Compose(new RegisteredTasks(map.Map, null, Identities.Empty), startupTaskIds);
 }
Example #41
0
		private void SaveIdentities (string root)
		{
			Identities identities = new Identities (_applicationIdentity, _assemblyIdentity, _domainIdentity);
			BinaryFormatter formatter = new BinaryFormatter ();
			mutex.WaitOne ();
			try {
				using (FileStream fs = File.Create (root + ".storage")) {
					formatter.Serialize (fs, identities);
				}
			}
			finally {
				mutex.ReleaseMutex ();
			}
		}