Пример #1
0
        /// <summary>
        /// Serializes the given object to a JSON string and puts it in the body of the response.
        /// Also adds an "application/json" Content-Type header.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="dataToSerialize">The data to serialize.</param>
        /// <param name="jsonSerializerSettings">The JSON serializer settings.</param>
        /// <exception cref="DoloresSerializationException">Thrown when the serialization fails.</exception>
        public static void Json(this Response response, object dataToSerialize, JsonSerializerSettings jsonSerializerSettings)
        {
            Enforce.ArgumentNotNull(jsonSerializerSettings, nameof(jsonSerializerSettings));

            string json;

            try
            {
                json = JsonConvert.SerializeObject(dataToSerialize, jsonSerializerSettings);
            }
            catch (Exception exception)
            {
                throw new DoloresSerializationException("An error occurred while serializing to a JSON string", exception);
            }

            var jsonStream = json.ToStream();

            response.MessageBody = jsonStream;
            response.SetContentTypeHeader("application/json");
        }
Пример #2
0
        public Assembly LoadAssembly(string simpleName)
        {
            simpleName = AssertIsSimpleName(Enforce.ArgumentNotNullOrEmpty(simpleName, "simpleName"));

            if (!_runtimeCfg.AvailableAssemblies.MeetsCriteria(simpleName))
            {
                throw new AssemblyUnavailableException(simpleName);
            }

            Assembly assembly = null;

            if (LoadedAssemblies.TryGetValue(simpleName, out assembly))
            {
                return(assembly);
            }
            else
            {
                return(DoLoadAssembly(simpleName));
            }
        }
 public static IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> MemberOf <TLimit, TActivatorData, TSingleRegistrationStyle>(IRegistrationBuilder <TLimit, TActivatorData, TSingleRegistrationStyle> registration, string collectionName) where TSingleRegistrationStyle : SingleRegistrationStyle
 {
     if (registration == null)
     {
         throw new ArgumentNullException("registration");
     }
     Enforce.ArgumentNotNullOrEmpty(collectionName, "collectionName");
     registration.OnRegistered <TLimit, TActivatorData, TSingleRegistrationStyle>(delegate(ComponentRegisteredEventArgs e) {
         IDictionary <string, object> metadata = e.ComponentRegistration.Metadata;
         if (metadata.ContainsKey("Autofac.CollectionRegistrationExtensions.MemberOf"))
         {
             metadata["Autofac.CollectionRegistrationExtensions.MemberOf"] = ((IEnumerable <string>)metadata["Autofac.CollectionRegistrationExtensions.MemberOf"]).Union <string>(new string[] { collectionName });
         }
         else
         {
             metadata.Add("Autofac.CollectionRegistrationExtensions.MemberOf", new string[] { collectionName });
         }
     });
     return(registration);
 }
Пример #4
0
        public BacklogInfoModel CreateBackLog(int teamID, string title, string content, string standard, string assignUserMail, int selectProjectID, int state, int?level, string createUserMail)
        {
            var projectInfoModel = this._projectRepository.GetProjectDetail(selectProjectID);

            if (projectInfoModel == null)
            {
                Enforce.Throw(new LogicErrorException("项目不存在"));
            }
            var userInfoModel = this._userRepository.GetUser(assignUserMail, 1);

            if (userInfoModel == null)
            {
                Enforce.Throw(new LogicErrorException("负责人账号不存在"));
            }
            if (this._projectRepository.GetProjectMember(selectProjectID, userInfoModel.info.mail) == null)
            {
                Enforce.Throw(new LogicErrorException("负责人不在项目中"));
            }
            BacklogInfoModel backlogInfoModel = new BacklogInfoModel();

            backlogInfoModel.teamID         = teamID;
            backlogInfoModel.title          = title;
            backlogInfoModel.content        = content;
            backlogInfoModel.standard       = standard;
            backlogInfoModel.sprintID       = 0;
            backlogInfoModel.assignUserMail = userInfoModel.info.mail;
            backlogInfoModel.assignUserName = userInfoModel.info.userName;
            backlogInfoModel.projectID      = selectProjectID;
            backlogInfoModel.projectName    = projectInfoModel.info.projectName;
            backlogInfoModel.state          = state;
            backlogInfoModel.level          = level;
            backlogInfoModel.createUserMail = createUserMail;
            backlogInfoModel.createTime     = DateTime.Now;
            var backlog = Mapper.Map <BacklogInfoModel, T_BACKLOG>(backlogInfoModel);

            if (this._backlogBll.Add(backlog))
            {
                backlogInfoModel = Mapper.Map <T_BACKLOG, BacklogInfoModel>(backlog);
            }
            return(backlogInfoModel);
        }
Пример #5
0
        /// <summary>
        /// Starts the dispatcher with the given actor.
        /// </summary>
        /// <remarks>If the method has already been called previously, this new call will siltenly fail.</remarks>
        /// <param name="actor">The actor to run on.</param>
        /// <exception cref="ArgumentException">The specified actor is null.</exception>
        internal static void Run(IActor actor)
        {
            Enforce.ArgumentNotNull(actor, "actor");

            // Double-check pattern (1)
            if (m_actor != null)
            {
                return;
            }
            lock (m_syncLock)
            {
                // Double-check pattern (2)
                if (m_actor != null)
                {
                    return;
                }

                m_actor          = actor;
                m_oneSecondTimer = actor.GetTimer(OnOneSecondTimerTick, 1000, true);
            }
        }
Пример #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Pool" /> class.
        /// </summary>
        /// <param name="poolConfig"></param>
        /// <param name="objectFactory"></param>
        public Pool(
            IPoolConfig poolConfig,
            IObjectFactory objectFactory)
        {
            Enforce.ArgumentNotNull(() => poolConfig);    // make sure we have a config instance supplied.
            Enforce.ArgumentNotNull(() => objectFactory); // make sure we have a objectFactory instance supplied.

            _objectFactory = objectFactory;

            // TODO: validate pool central wallet & rewards within the startup.

            Config = poolConfig;

            _logger = Log.ForContext <Pool>().ForContext("Component", Config.Coin.Name);

            GenerateInstanceId();

            InitDaemon();
            InitManagers();
            InitServers();
        }
        public bool Listen(string name, Func <IntradomainSocket, IntradomainSocket> acceptClient)
        {
            Enforce.NotNull(acceptClient, nameof(acceptClient));

            if (string.IsNullOrEmpty(name))
            {
                return(false);
            }


            lock (_locker)
            {
                if (_listeners.ContainsKey(name))
                {
                    return(false);
                }

                _listeners.Add(name, acceptClient);
                return(true);
            }
        }
Пример #8
0
        public bool TryGetExtensionPointConfiguration(string extensionPointId, out IExtensionPointConfiguration pointConfiguration)
        {
            Enforce.ArgumentNotNullOrEmpty(extensionPointId, "extensionPointId");

            IBundle bundle;

            if (_bundleByExtensionPointId.TryGetValue(extensionPointId, out bundle))
            {
                foreach (IExtensionPointConfiguration cfg in bundle.ContributedExtensionPoints)
                {
                    if (cfg.Id == extensionPointId)
                    {
                        pointConfiguration = cfg;
                        return(true);
                    }
                }
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Expected extension point configuration element with bundleId {0} to be contained in bundle with bundleId {1}.", extensionPointId, bundle.Id));
            }
            pointConfiguration = null;
            return(false);
        }
        public bool Connected(IntradomainSocket socket)
        {
            if (string.IsNullOrEmpty(socket.ConnectionId))
            {
                return(false);
            }

            Enforce.IsTrue(socket.Type != SocketType.Listener, nameof(socket));

            lock (_locker)
            {
                if (!_connections.ContainsKey(socket.ConnectionId))
                {
                    return(false);
                }

                return(socket.Type == SocketType.Client
                    ? _connections[socket.ConnectionId].ClientSocketState == IntradomainSocketState.Connected
                    : _connections[socket.ConnectionId].ServerSocketState == IntradomainSocketState.Connected);
            }
        }
Пример #10
0
        public async Task <UserRepoModel> BindUser(string submitToken, string redisId, string mail, string agent)
        {
            UserRepoModel userRepoModel = null;

            if (await this.checkSubmitToken(EmailAuthCodeType.BindUser, mail, submitToken, agent))
            {
                var thirdParty = await _relationRepo.GetRelationAccountModel(redisId);

                if (null == thirdParty)
                {
                    Enforce.Throw(new FrontInputValidateErrorException("第三方Id不存在"));
                }
                var userInfoModel = this.getUserInfoModelByMail(mail, 1);
                if (userInfoModel == null)
                {
                    Enforce.Throw(new LogicErrorException("当前账号不存在"));
                }

                if (this.getThirdPartyInfoModel(thirdParty.thirdPartyID, thirdParty.from) != null)
                {
                    Enforce.Throw(new LogicErrorException("第三方账号已被其他账号绑定"));
                }

                if (this.getThirdPartyInfoModel(userInfoModel.userID, thirdParty.from) != null)
                {
                    Enforce.Throw(new LogicErrorException("当前账号已绑定过该类型的第三方账号"));
                }

                userInfoModel.lastLoginTime = DateTime.Now;
                bool ret = this._userBll.UpdateUserAndThirdParty(Mapper.Map <UserInfoModel, T_USER>(userInfoModel), thirdParty.thirdPartyID, thirdParty.from);
                if (ret)
                {
                    userRepoModel          = new UserRepoModel();
                    userRepoModel.info     = userInfoModel;
                    userRepoModel.roleList = this.getUserRoleListByUserID(userRepoModel.info.userID);
                }
            }

            return(userRepoModel);
        }
Пример #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DatasetApplicationCommands"/> class.
        /// </summary>
        /// <param name="dataDownload">The object that handles the communication with remote endpoints.</param>
        /// <param name="datasetLock">The function that handles downloading data from the remote endpoint.</param>
        /// <param name="closeAction">The action that closes the application.</param>
        /// <param name="loadAction">The action that is used to load the dataset from a given file path.</param>
        /// <param name="systemDiagnostics">The object that provides the diagnostics methods for the system.</param>
        /// <param name="scheduler">The scheduler that is used to run the tasks.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="dataDownload"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="datasetLock"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="closeAction"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="loadAction"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// Thrown is <paramref name="systemDiagnostics"/> is <see langword="null"/>
        /// </exception>
        public DatasetApplicationCommands(
            DownloadDataFromRemoteEndpoints dataDownload,
            ITrackDatasetLocks datasetLock,
            Action closeAction,
            Action <FileInfo> loadAction,
            SystemDiagnostics systemDiagnostics,
            TaskScheduler scheduler = null)
        {
            {
                Enforce.Argument(() => dataDownload);
                Enforce.Argument(() => closeAction);
                Enforce.Argument(() => loadAction);
                Enforce.Argument(() => systemDiagnostics);
            }

            m_DataDownload = dataDownload;
            m_DatasetLock  = datasetLock;
            m_CloseAction  = closeAction;
            m_LoadAction   = loadAction;
            m_Diagnostics  = systemDiagnostics;
            m_Scheduler    = scheduler ?? TaskScheduler.Default;
        }
Пример #12
0
        /// <summary>
        /// Loads the type.
        /// </summary>
        /// <param name="typeName">Name of the type.</param>
        /// <param name="defaultAssembly">The default assembly.</param>
        /// <returns></returns>
        protected virtual Type LoadType(string typeName, Assembly defaultAssembly)
        {
            Enforce.ArgumentNotNull(typeName, "typeName");
            if (typeName == string.Empty)
            {
                throw new ArgumentOutOfRangeException("typeName");
            }

            Type type = Type.GetType(typeName);

            if (type == null && defaultAssembly != null)
            {
                type = defaultAssembly.GetType(typeName, false); // Don't throw on error.
            }
            if (type == null)
            {
                throw new ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture,
                                                                     ConfigurationSettingsReaderResources.TypeNotFound, typeName));
            }

            return(type);
        }
Пример #13
0
        // ReSharper disable InconsistentNaming

        static void ClassUsagePatterns <T>(T param, IEnumerable <T> collection, Rule <T> rule) where T : class
        {
            Enforce.Argument(() => param);
            Enforce.Argument(() => param, rule);
            Enforce.Argument(() => collection, rule);
            Enforce.Arguments(() => param, () => param);
            Enforce.Arguments(() => param, () => param, () => param);
            Enforce.Arguments(() => param, () => param, () => param, () => param);
            Enforce.Arguments(() => param, () => param, () => param, () => param, () => param);


            Enforce.That(() => param);
            Enforce.That(() => param, rule);
            Enforce.That(() => collection, rule);

            Enforce.That(param, rule);
            Enforce.That(collection, rule);

            var local = param;

            Enforce.NotNull(() => local);
        }
Пример #14
0
        public SprintInfoModel CreateSprint(int teamID, int releaseID, DateTime startTime, DateTime endTime, string currentMail)
        {
            if (this.getReleaseInfoByTeamIDAndReleaseID(teamID, releaseID) == null)
            {
                Enforce.Throw(new LogicErrorException("不存在该Release"));
            }
            SprintInfoModel sprintInfoModel = new SprintInfoModel();

            sprintInfoModel.releaseID      = releaseID;
            sprintInfoModel.startTime      = startTime;
            sprintInfoModel.endTime        = endTime;
            sprintInfoModel.state          = 0;
            sprintInfoModel.createUserMail = currentMail;
            sprintInfoModel.createTime     = DateTime.Now;

            var    sprintInfoModelList = this.ListSprint(teamID, releaseID);
            var    maxSprintNo         = sprintInfoModelList.Count > 0?sprintInfoModelList.Max(s => s.no):0;
            string lockKey             = string.Format("Scrum_Team_{0}", teamID);

            lock (lockKey)
            {
                sprintInfoModelList = this.ListSprint(teamID, releaseID);
                maxSprintNo         = sprintInfoModelList.Count > 0 ? sprintInfoModelList.Max(s => s.no) : 0;
                sprintInfoModel.no  = maxSprintNo + 1;
                if (sprintInfoModelList.Count <= 0)
                {
                    sprintInfoModel.state = 1;
                }
                var sprint = AutoMapper.Mapper.Map <SprintInfoModel, T_RELEASE_SPRINT>(sprintInfoModel);
                if (this._relaseSprintBll.Add(sprint))
                {
                    sprintInfoModel = Mapper.Map <T_RELEASE_SPRINT, SprintInfoModel>(sprint);
                }
            }



            return(sprintInfoModel);
        }
Пример #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ScriptFrontEndProjectHub"/> class.
        /// </summary>
        /// <param name="projects">The object that handles all the project activities.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="projects"/> is <see langword="null" />.
        /// </exception>
        public ScriptFrontEndProjectHub(ScriptBackEndProjectHub projects)
        {
            {
                Enforce.Argument(() => projects);
            }

            m_Projects = projects;
            {
                m_Projects.OnNewProjectLoaded +=
                    (s, e) =>
                {
                    m_Current = null;
                    RaiseOnNewProjectLoaded();
                };
                m_Projects.OnProjectUnloaded +=
                    (s, e) =>
                {
                    m_Current = null;
                    RaiseOnProjectUnloaded();
                };
            }
        }
Пример #16
0
        private void TryEnqueue(string typeName)
        {
            string[] splittedTypeName = typeName.Split('.');
            string   modelName;

            if (splittedTypeName.Length == 1)
            {
                modelName = splittedTypeName[0];
            }
            else
            {
                modelName = splittedTypeName[1];
            }

            Enforce.IsNotNull <string>(modelName, typeName + " parsing failed.");

            if (_visited.ContainsKey(modelName) && _visited[modelName] == 0)
            {
                _visitingQueue.Enqueue(modelName);
                _visited[modelName] = 1;
            }
        }
Пример #17
0
        private void GenerateFiles(DocumentContext context, bool isRootContext)
        {
            if (!isRootContext && ContextUtils.IsCommon(context.CodeNamespace))
            {
                return;
            }

            LOG.Debug(string.Format("Generating code for {0}...", context.Namespace));

            Enforce.IsNotNull(_outputFolder, "The output folder was not set!");
            if (!_outputFolder.Exists)
            {
                _outputFolder.Create();
            }

            LOG.Debug(string.Format("Writing source files into {0} using {1} ...", _outputFolder,
                                    _generatorConfig.CodeFlavor));

            var codeGenerator = CreateCodeGenerator(context);

            codeGenerator.Visit(context.Document);
        }
Пример #18
0
        public Stream CreateAuthCode(string identity, int width, int height)
        {
            if (string.IsNullOrEmpty(identity))
            {
                Enforce.Throw(new FrontInputValidateErrorException("验证码identity不能为空"));
            }

            if (width < 0)
            {
                width = 100;
            }

            if (height < 0)
            {
                height = 40;
            }

            var authCode = AuthCode.CreateAuthCode(width, height, ImageFormat.Png);

            _database.StringSetAsync(identity, authCode.Code.ToLower(), TimeSpan.FromMinutes(5));
            return(authCode.Img);
        }
Пример #19
0
        public async Task <IHttpActionResult> SendAuthMail([FromBody] ReqSendAuthMail req)
        {
            var    response = new ResSendAuthMail();
            string agent    = Request.Headers.UserAgent.ToString();

            //验证码验证成功或者重发token验证成功
            var reSendToken = await this._userRepo.SendAuthMail(req.reSendEmailToken, req.identity, req.code, req.mail, req.codeType, agent);

            if (string.IsNullOrEmpty(reSendToken))
            {
                Enforce.Throw(new LogicErrorException("邮件发送失败"));
            }

            //发送邮件成功
            SendAuthMailResult sendAuthMailResult = new SendAuthMailResult();

            sendAuthMailResult.mail            = req.mail;
            sendAuthMailResult.reSendMailToken = reSendToken;
            response.setResponse(ResStatusCode.OK, sendAuthMailResult, 1, "邮件发送成功");

            return(Ok(response));
        }
Пример #20
0
        public void Close()
        {
            Enforce.NotDisposed(this, _isDisposed);
            try
            {
                _newChannelRequestAcceptor.ClientAccepted -= ClientAccepted;

                if (_stopAcceptorOnClose && _newChannelRequestAcceptor.Active)
                {
                    _newChannelRequestAcceptor.Stop();
                }

                foreach (var channel in _subscriptionManager.GetOpenChannels())
                {
                    channel.Close();
                }
            }
            finally
            {
                Active = false;
            }
        }
Пример #21
0
        /// <summary>
        /// Saves or updates the given entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void SaveOnSubmit(TEntity entity)
        {
            lock (this._lockObject)
            {
                Enforce.NotNull(() => entity);

                // Check whether the entity already exists. If so, remove it (and simulate an
                // update this way).
                var defaultQueryPropertyValue = _defaultQueryPropertyInfo.GetValue(entity, null);

                var element = (this.GetElementsByKeyValuePair(this._defaultQueryProperty, defaultQueryPropertyValue)).SingleOrDefault();

                if (element != null)
                {
                    element.Remove();
                }

                // Add the entity.
                this._rootElement.Add(this.DataMapper.ToXElement(entity));
                this._isDirty = true;
            }
        }
Пример #22
0
        public string GenerateContent(string template, string name, object model)
        {
            var result = string.Empty;

            if (string.IsNullOrEmpty(name))
            {
                Enforce.Throw(new Exception("模板名称不能为空"));
            }
            if (_razorEngineService.IsTemplateCached(name, null))
            {
                result = _razorEngineService.Run(name, null, model);
            }
            else
            {
                if (string.IsNullOrEmpty(template))
                {
                    Enforce.Throw(new Exception("模板不能为空"));
                }
                result = _razorEngineService.RunCompile(template, name, null, model);
            }
            return(result);
        }
Пример #23
0
        private void Render(CSharpContext context, string templateName)
        {
            var template = templateLoader.Load(templateName);

            Enforce.IsNotNull(template, string.Format("No template for '{0}' found!", templateName));
            template.Add("context", context);

            var tweakMap    = new Dictionary <string, bool>();
            var tweakValues = Enum.GetValues(typeof(GeneratorTweak));

            foreach (var tweak in tweakValues)
            {
                tweakMap.Add(tweak.ToString(), config.ContainsTweak((GeneratorTweak)tweak));
            }
            template.Add("tweaks", tweakMap);

            var globalValues   = new Dictionary <string, string>();
            var codeGenVersion = Assembly.GetExecutingAssembly().GetName().Version;

            globalValues.Add("CodeGenVersion", codeGenVersion.ToString());
            template.Add("global", globalValues);

            var           packages = context.CSharpNamespace.Split('.');
            DirectoryInfo folder   = outputFolder;

            foreach (string pkg in packages)
            {
                folder = folder.CreateSubdirectory(pkg);
            }

            var filename = Path.Combine(folder.FullName, context.CSharpName + ".cs");

            using (StreamWriter writer = new StreamWriter(filename, false, Encoding.UTF8))
            {
                template.Write(new AutoIndentWriter(writer));
                writer.Flush();
            }
        }
Пример #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DatasetModel"/> class.
        /// </summary>
        /// <param name="context">The context that is used to execute actions on the UI thread.</param>
        /// <param name="progressTracker">The object that handles the progress notifications for the applications.</param>
        /// <param name="project">The project that holds all the data.</param>
        /// <param name="dataset">The dataset.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="context"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="progressTracker"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="project"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="dataset"/> is <see langword="null" />.
        /// </exception>
        public DatasetModel(IContextAware context, ITrackSteppingProgress progressTracker, ILinkToProjects project, DatasetFacade dataset)
            : base(context)
        {
            {
                Enforce.Argument(() => progressTracker);
                Enforce.Argument(() => project);
                Enforce.Argument(() => dataset);
            }

            m_ProgressTracker                    = progressTracker;
            m_Project                            = project;
            m_Dataset                            = dataset;
            m_Dataset.OnNameChanged             += (s, e) => Notify(() => Name);
            m_Dataset.OnSummaryChanged          += (s, e) => Notify(() => Summary);
            m_Dataset.OnProgressOfCurrentAction += HandleDatasetProgress;
            m_Dataset.OnActivated               += HandleDatasetOnActivated;
            m_Dataset.OnDeactivated             += (s, e) =>
            {
                Notify(() => IsActivated);
                Notify(() => RunsOn);
                RaiseOnDeactivated();
            };
        }
Пример #25
0
        /// <summary>
        /// Gets a mimetype for the extension contained in the fileName
        /// If on extension available, or the extension is not in the dictionary,
        /// octet-stream is returned (forces download).
        /// </summary>
        /// <param name="fileName">The filename</param>
        /// <returns>The mimetype for the extension of the filename</returns>
        public static ContentType GetMimeTypeMapping(string fileName)
        {
            fileName = Enforce.NotNullOrEmpty(fileName, () => fileName);

            // Get the extension.
            string extension = GetFileExtension(fileName);

            // Check whether an extension was found. If not, return the default mimetype.
            if (extension.IsNullOrEmpty())
            {
                return(_extensionToMimeType[_defaultKey]);
            }

            // Check whether the extension is contained within the dictionary. If not, return the
            // default mimetype.
            if (!_extensionToMimeType.ContainsKey(extension))
            {
                return(_extensionToMimeType[_defaultKey]);
            }

            // Else return the appropriate mimetype.
            return(_extensionToMimeType[extension]);
        }
Пример #26
0
        public void AuthenticatePin()
        {
            Enforce.NotNull(_token);

            int pin;

            if (!int.TryParse(Pin, out pin))
            {
                throw new InvalidOperationException("The PIN must be a number.");
            }

            var authorizer = new OAuthAuthorizer(AppBootstrapper.ConsumerKey, AppBootstrapper.ConsumerSecret);

            authorizer.GetAccessToken("https://twitter.com/oauth/access_token", _token, Pin)
            .DispatcherSubscribe(
                response =>
            {
                AppSettings.UserOAuthToken       = response.Token.Key;
                AppSettings.UserOAuthTokenSecret = response.Token.Secret;
                _eventAggregator.Publish(new AuthenticatedMessage());
            },
                OnError);
        }
Пример #27
0
        internal TcpChannel(TcpClient client,
                            IMessageSerializer serializer,
                            ChannelSettings channelSettings,
                            TcpConnectionSettings connetcionSettings,
                            ISecurityWrapper serverSecurityWrapper)
        {
            Enforce.NotNull(client, nameof(client));
            Enforce.NotNull(serializer, nameof(serializer));

            var ipEndPoint = (IPEndPoint)client.Client.RemoteEndPoint;

            _endpointData   = new TcpEndpointData(ipEndPoint.Address, ipEndPoint.Port);
            Serializer      = serializer;
            _client         = client;
            _client.NoDelay = true;

            connetcionSettings.SetupClient(_client);
            MaxMessageLength = channelSettings.MaxMessageLength;

            SecurityWrapper = serverSecurityWrapper;

            ResponseHandshake();
        }
Пример #28
0
        /// <summary>
        /// 校验提交Token
        /// </summary>
        /// <param name="codeType"></param>
        /// <param name="mail"></param>
        /// <param name="token"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        private async Task <bool> checkSubmitToken(EmailAuthCodeType codeType, string mail, string token, string agent)
        {
            bool result = true;

            if (string.IsNullOrEmpty(token))
            {
                Enforce.Throw(new FrontInputValidateErrorException("提交Token不能为空"));
            }
            string redisKey    = this.generateSubmitTokenKey(mail, codeType);
            var    submitToken = await _database.StringGetAsync(redisKey);

            if (submitToken.Equals(token))
            {
                var tokenContentModel = _tokenSecurity.decrypt <TokenContentModel>(submitToken);
                result = tokenContentModel != null && tokenContentModel.agent.Equals(agent);
            }
            else
            {
                result = false;
            }

            return(result);
        }
Пример #29
0
        public bool UpdateWorkflow(WorkflowDC workflow)
        {
            Enforce.ArgumentNotNull(workflow, "workflow");
            Enforce.ArgumentNotNull(workflow.Id, "workflow.Id");
            Enforce.ArgumentNotNull(workflow.StartState, "workflow.StartState");
            Enforce.ArgumentNotNull(workflow.DisplayName, "workflow.DisplayName");
            Enforce.ArgumentGreaterThanZero(workflow.States.Count, "workflow.States");

            var validator            = new WorkflowValidation();
            ValidationResult results = validator.Validate(workflow);

            IRepositoryHelper repoHelper = new RepositoryHelper(_connectionString);

            try
            {
                var unitOfWork      = new JsonUnitOfWork(_connectionString);
                var wfRepo          = new WorkflowRepository(unitOfWork);
                var workflowUpdated = wfRepo.Update(workflow.GetWorkflow());

                var stateRepo = new StateRepository(unitOfWork);
                stateRepo.SetWorkflowStates(workflow.Id, workflow.States.ToRepoList());

                var actRepo = new StateActivityRepository(unitOfWork);
                actRepo.SetWorkflowStates(workflow.Id, workflow.Activities.ToRepoList());

                var tranRepo = new StateTransitionRepository(unitOfWork);
                tranRepo.SetWorkflowStates(workflow.Id, workflow.Transitions.ToRepoList());

                repoHelper.GetUnitOfWork().SaveChanges();
            }
            catch (Exception ex)
            {
                var message = ex.Message;
                throw;
            }
            return(true);
        }
Пример #30
0
        protected virtual THtmlTag SetCssClass(string cssClass, bool isOverwrite = false)
        {
            Enforce.ArgumentNotEmpty(() => cssClass);

            var resultClass = string.Empty;

            if (isOverwrite)
            {
                resultClass = cssClass;
            }
            else
            {
                var sourceCssClass =
                    HtmlTagBuilder.Attributes.GetValue(HtmlTextWriterAttribute.Class, string.Empty).ToString();
                int startInd;
                if (!((startInd = sourceCssClass.IndexOf(cssClass)) >= 0 &&
                      (
                          //end of string
                          (startInd + cssClass.Length >= sourceCssClass.Length)
                          ||
                          // or inside string
                          (char.IsWhiteSpace(sourceCssClass, startInd + cssClass.Length))
                      )
                      ))
                {
                    resultClass = sourceCssClass + (string.IsNullOrWhiteSpace(sourceCssClass) ? "" : " ") + cssClass;
                }
            }

            if (!string.IsNullOrEmpty(resultClass))
            {
                SetAttribute(HtmlTextWriterAttribute.Class, resultClass);
            }

            return((THtmlTag)this);
        }