public override async Task StreamingCall(IAsyncStreamReader<SimpleRequest> requestStream, IServerStreamWriter<SimpleResponse> responseStream, ServerCallContext context)
 {
     await requestStream.ForEachAsync(async request =>
     {
         var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) };
         await responseStream.WriteAsync(response);
     });
 }
        public override async Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context)
        {
            await EnsureEchoMetadataAsync(context);
            EnsureEchoStatus(request.ResponseStatus, context);

            var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) };
            return response;
        }
Ejemplo n.º 3
0
        public void CallOptionsOverloadCanBeMocked()
        {
            var expected = new SimpleResponse();

            var mockClient = new Moq.Mock<TestService.TestServiceClient>();
            mockClient.Setup(m => m.UnaryCall(Moq.It.IsAny<SimpleRequest>(), Moq.It.IsAny<CallOptions>())).Returns(expected);

            Assert.AreSame(expected, mockClient.Object.UnaryCall(new SimpleRequest(), new CallOptions()));
        }
Ejemplo n.º 4
0
        public void ExpandedParamOverloadCanBeMocked()
        {
            var expected = new SimpleResponse();

            var mockClient = new Moq.Mock<TestService.TestServiceClient>();
            // mocking is relatively clumsy because one needs to specify value for all the optional params.
            mockClient.Setup(m => m.UnaryCall(Moq.It.IsAny<SimpleRequest>(), null, null, CancellationToken.None)).Returns(expected);

            Assert.AreSame(expected, mockClient.Object.UnaryCall(new SimpleRequest()));
        }
Ejemplo n.º 5
0
        public async Task WithExceptionCustomizer_NoException(bool sync)
        {
            var  response = new SimpleResponse();
            var  call     = FakeApiCall.Create <SimpleRequest, SimpleResponse>((req, options) => response);
            bool called   = false;

            call = call.WithExceptionCustomizer(original => { called = true; return(null); });
            var request        = new SimpleRequest();
            var actualResponse = sync ? call.Sync(request, null) : await call.Async(request, null);

            Assert.Same(response, actualResponse);
            Assert.False(called);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Provider for api to save customer data
        /// </summary>
        /// <param name="customerModel"></param>
        /// <returns></returns>
        public async Task <SimpleResponse> Customer_Save(CustomerModel customerModel)
        {
            SimpleResponse simpleResponse = new SimpleResponse();

            //Transform_CustomerSaveObject(req);
            simpleResponse = ValidateCustomerSave(simpleResponse, customerModel);
            if (simpleResponse.HasError)
            {
                return(simpleResponse);
            }

            return(await _customerHandler.Customer_Save(customerModel));
        }
Ejemplo n.º 7
0
        public async Task <SimpleResponse> GetCourseDetail(int courseId)
        {
            try
            {
                var course = await _ivySchoolRepository.GetCourseById(courseId);

                return(ObjectResponse <CourseDetail> .Success(ConvertToCourseDetail(course)));
            }
            catch (DBOperationException ex)
            {
                return(SimpleResponse.Error(ex.Message));
            }
        }
Ejemplo n.º 8
0
        public async Task <SimpleResponse <Member> > Handle(SignUpMemberCommand request, CancellationToken cancellationToken)
        {
            var member = _memberFactory.Create(request.Email, request.Name,
                                               request.MonthlyExpense, request.MonthlySalary);

            member = await _memberService.SignUpMember(member);

            await _userUnitOfWork.SaveChangesAsync(cancellationToken);

            member = await _memberService.GetMemberById(member.Id);

            return(SimpleResponse <Member> .Create(member));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// CP专区
        /// </summary>
        /// <returns></returns>
        public ActionResult CP()
        {
            int timeOut = 30;

            IEnumerable <RecommendView> recommendList = DataContext.TryCache <IEnumerable <RecommendView> >("CartoonIndex_ThreeD_More", () =>
            {
                return(GetRecList(RecSection.CartoonIndex.ThreeDRec, 10));
            }, timeOut);

            var model = new SimpleResponse <IEnumerable <RecommendView> >(!recommendList.IsNullOrEmpty(), recommendList);

            return(View(model));
        }
Ejemplo n.º 10
0
    public override async Task <SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context)
    {
        await EnsureEchoMetadataAsync(context, request.ResponseCompressed?.Value ?? false);

        EnsureEchoStatus(request.ResponseStatus, context);
        EnsureCompression(request.ExpectCompressed, context);

        var response = new SimpleResponse {
            Payload = CreateZerosPayload(request.ResponseSize)
        };

        return(response);
    }
        public override SimpleResponse Validate(StaffDeleteCommand command)
        {
            SimpleResponse response = new SimpleResponse();

            if (command.Id == null || command.Id < 1)
            {
                response.ResponseCode    = -100;
                response.ResponseMessage = "Invalid id value";
            }
            // Validation process will be added  in future.

            return(response);
        }
Ejemplo n.º 12
0
        public IActionResult DeleteUserInfo(int id, [FromBody] AppUser model)
        {
            SimpleResponse sr = new SimpleResponse();
            var userDb = _usernService.getUserById(id);
            if (userDb == null) return NotFound();

            int errorCode = 0;
            string result = "";
            _usernService.DeleteUser(userDb, ref errorCode, ref result);
            sr.ErrorCode = errorCode;
            sr.Result = result;
            return Ok(sr);
        }
        public async Task ReturnEchoedPayloadWithZeroValueForPOST()
        {
            SimpleResponse response = await Settings.Host
                                      .AppendPathSegment("securityProperty")
                                      .PostJsonAsync(new
            {
                Value,
                Message
            })
                                      .ReceiveJson <SimpleResponse>();

            ValidateEchoedResponse(response);
        }
Ejemplo n.º 14
0
        public async Task ReturnEchoedPayloadForPATCH()
        {
            SimpleResponse response = await Settings.Host
                                      .AppendPathSegment("verbs")
                                      .PatchJsonAsync(new
            {
                Value,
                Message
            })
                                      .ReceiveJson <SimpleResponse>();

            ValidateEchoedResponse(response);
        }
Ejemplo n.º 15
0
        public async Task <SimpleResponse <Member> > Handle(GetMemberByEmailQuery request,
                                                            CancellationToken cancellationToken)
        {
            var member = await _memberService.GetMemberByEmail(request.Email);

            if (member == null)
            {
                throw new BusinessException("Cannot find member for email {email}",
                                            BusinessErrors.ResourceNotFound("member", "Email is not found"),
                                            request.Email);
            }
            return(SimpleResponse <Member> .Create(member));
        }
Ejemplo n.º 16
0
        public async Task ReturnOkResultForCommandWithResultWhenNoValidator()
        {
            HttpResponse httpResponse = await ExecuteHttpAsync(new HttpCommandWithResultAndNoValidation
            {
                Value = 5
            });

            Assert.Equal(200, httpResponse.StatusCode);
            SimpleResponse result = httpResponse.GetJson <SimpleResponse>();

            Assert.Equal(1, result.Value);
            Assert.Equal("success", result.Message);
        }
Ejemplo n.º 17
0
        public IHttpActionResult BindingFinder(AccountBindModel accountBindModel)
        {
            var         response = new SimpleResponse();
            AccountUser account  = null;

            try
            {
                if (string.IsNullOrWhiteSpace(accountBindModel.Username))
                {
                    throw new Exception("账号不能为空!");
                }
                if (string.IsNullOrWhiteSpace(accountBindModel.Password))
                {
                    throw new Exception("密码不能为空!");
                }

                //删除请求中的空字符串
                accountBindModel.Username = accountBindModel.Username.Replace(" ", "");
                accountBindModel.Password = accountBindModel.Password.Replace(" ", "");


                var result = _accountUserRegistrationService.ValidateAccountUser(accountBindModel.Username, accountBindModel.Password);
                if (result != AccountUserLoginResults.Successful)
                {
                    throw new Exception("账号和密码不匹配!");
                }

                account = _accountService.GetAccountUserByUsername(accountBindModel.Username);
                account.WechatNickName = accountBindModel.Nickname;
                account.AvatarUrl      = accountBindModel.AvatarUrl;

                var request   = HttpContext.Current.Request;
                var authToken = request.Headers["Authorization"].Replace("Bear ", "");
                var openId    = _wechatLoginEventService.GetOpenIdWithToken(authToken);

                account.WechatOpenId = openId;
                _accountService.UpdateAccountUser(account);
                response.Message = "绑定成功!";
                response.Code    = "200";
            }
            catch (Exception ex)
            {
                //var finderInfo = string.Format("{0}{1}{2}{3}", accountBindModel.Name, accountBindModel.SchoolNumber);
                //_logger.Error(string.Format("{0},绑定失败,错误原因:{1}", finderInfo, ex.GetOriginalException().Message), account);

                response.Message = ex.Message;
                response.Code    = "400";
            }

            return(Ok(response));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Handler to save customer data
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task <SimpleResponse> Customer_Save(CustomerModel req)
        {
            SimpleResponse    result = new SimpleResponse();
            DynamicParameters param  = new DynamicParameters();

            AutoGenerateInputParams(param, req);

            //Check for duplicacy for name
            int duplicateCount = 0;

            int CustomerId = 0;

            using (SqlConnection con = await CreateConnectionAsync())
            {
                duplicateCount = await con.ExecuteScalarAsync <int>($"Select count(*) from dbo.Customers where FirstName = '{ req.FirstName }' " +
                                                                    $"and LastName = '{ req.LastName }' and CustomerId <> { req.CustomerId }");

                if (duplicateCount > 0)
                {
                    result.SetError(ErrorCodes.CUSTOMER_NAME_Duplicate);
                    result.Result = false;
                    return(result);
                }
                using (var trans = con.BeginTransaction())
                {
                    //Insert data into Customer table and get id in return
                    CustomerId = await con.ExecuteScalarAsync <int>("[dbo].[Customer_Save]", param, transaction : trans, commandType : CommandType.StoredProcedure);

                    //Now make a loop on address list and save in DB
                    foreach (CustomerAddress customerAddress in req.CustomerAddressList)
                    {
                        customerAddress.CustomerId = CustomerId;
                        DynamicParameters addressparam = new DynamicParameters();
                        AutoGenerateInputParams(addressparam, customerAddress);
                        await con.ExecuteAsync("[dbo].[CustomerAddress_Save]", addressparam, transaction : trans, commandType : CommandType.StoredProcedure);
                    }
                    //Now make a loop on billing info list and save in DB
                    foreach (CustomerBillingInfo customerBillingInfo in req.CustomerBillingInfoList)
                    {
                        customerBillingInfo.CustomerId = CustomerId;
                        DynamicParameters billInfoparam = new DynamicParameters();
                        AutoGenerateInputParams(billInfoparam, customerBillingInfo);
                        await con.ExecuteAsync("[dbo].[BillingInfo_Save]", billInfoparam, transaction : trans, commandType : CommandType.StoredProcedure);
                    }
                    trans.Commit();
                }
                result.Result = true;
            }

            return(result);
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Editar(Guid id, CampanhaModel model)
        {
            try
            {
                ViewBag.Prioridade = CarregarPrioridades(model.Prioridade);

                if (!ModelState.IsValid)
                {
                    return(View("Editar", model));
                }

                if (model.Prioridade.Value < 0 || model.Prioridade.Value > 3)
                {
                    ModelState.AddModelError("Prioridade", "A prioridade de estar dentro da lista de escolha");
                }

                if (model.ImgCampanha != null && model.ImgCampanha.Length > 524288)
                {
                    ModelState.AddModelError("ImgCampanha", "Tamanho máximo de arquivo excedido (500KBytes)");
                }

                if (ModelState.ErrorCount > 0)
                {
                    return(View("Editar", model));
                }

                SimpleResponseObj resposta = await EditarRegistro(model);

                if (resposta.Sucesso)
                {
                    if (model.ImgCampanha != null)
                    {
                        SimpleResponse respImg = await CarregarArquivo(model.Id.Value, model.ImgCampanha);

                        if (!respImg.Sucesso)
                        {
                            ViewBag.Prioridade = CarregarPrioridades(model.Prioridade);
                            model.Criticas     = "Falha ao carregar arquivo";
                            return(View("Editar", model));
                        }
                    }

                    return(RedirectToAction("Index"));
                }

                ModelState.AddModelError(string.Empty, $"Ops, algo deu errado, {resposta.Mensagem.ToString()}");
                return(View("Editar", model));
            }
            catch (SessaoExpiradaException) { return(RedirectToAction("Logout", "Account")); }
        }
Ejemplo n.º 20
0
        private void onChannelCreated(object sender, ChannelCreatedEventArgs e)
        {
            ListResponse <uint> test2 = queryRunner.GetClientDatabaseIdsByUniqueId("sR/12P6fJAJngNXQqK+JMA9CFuw=");

            uint test = queryRunner.GetClientDatabaseIdsByUniqueId(e.InvokerUniqueId).Values[0];
            ListResponse <ServerGroupLight> servergroups = queryRunner.GetServerGroupsByClientId(test);

            bool          allowed            = false;
            List <string> admin_servergroups = new List <string>();

            admin_servergroups.AddRange(sql.getProperty(serverinfo.id, "admins_servergroup_ids").Split(','));

            foreach (ServerGroupLight servergroup in servergroups)
            {
                foreach (string admin_servergroup in admin_servergroups)
                {
                    if (servergroup.Id == (uint)Convert.ToInt32(admin_servergroup))
                    {
                        allowed = true;
                    }
                }
            }

            if (allowed)
            {
                //User was allowed to do this, however now we want to re-scan the room list.
                ScanRooms();
            }
            else
            {
                ListResponse <ChannelListEntry> channels = queryRunner.GetChannelList(true, false, false, false, false);
                //SimpleResponse response = queryRunner.DeleteChannel((uint)Convert.ToInt32(values["cid"]));

                foreach (ChannelListEntry channel in channels)
                {
                    if (channel.Topic == "temporary_area")
                    {
                        SimpleResponse response = queryRunner.MoveChannel((uint)Convert.ToInt32(e.ChannelId), channel.ChannelId);

                        ChannelModification mod = new ChannelModification();
                        mod.IsTemporary     = true;
                        mod.IsPermanent     = false;
                        mod.IsSemiPermanent = false;

                        queryRunner.EditChannel((uint)Convert.ToInt32(e.ChannelId), mod);
                        break;
                    }
                }
            }
        }
Ejemplo n.º 21
0
        public async Task <IActionResult> OnPostNLAsync()
        {
            Newsletter NL = new Newsletter();

            NL.NewsletterID   = int.Parse(Request.Form["NLID"]);
            NL.IntroParagraph = Request.Form["tinyMCETextArea"];
            NL.MainImageURL   = Request.Form["imgURLtextbox"];

            SimpleResponse SR = await DS.PutAsyncSR(NL, "News/UpdateNewsLetter");

            await GetNewsletters();

            return(Page());
        }
Ejemplo n.º 22
0
        public void GivenCommonMapper_WhenMapSimpleResponseToApiSimpleResponse_ShouldMapSuccessfully()
        {
            // assign
            var account        = AccountDataBuilder.CreateAccount(1, null);
            var simpleResponse = SimpleResponse <Account> .Create(account);

            // act
            var apiSimpleResponse = _mapper.Map <ApiSimpleResponse <AccountModel> >(simpleResponse);

            //assert
            apiSimpleResponse.ShouldSatisfyAllConditions(
                () => apiSimpleResponse.ShouldNotBeNull(),
                () => apiSimpleResponse.Data.ShouldNotBeNull());
        }
Ejemplo n.º 23
0
        public ActionResult SetFirstPassword()
        {
            string email     = Request.Form["email"] ?? string.Empty;
            string password  = Request.Form["password"] ?? string.Empty;
            string orderbvin = Request.Form["orderbvin"] ?? string.Empty;

            SimpleResponse resp = new SimpleResponse();

            resp.Success = true;

            MerchantTribe.Commerce.Orders.Order order = MTApp.OrderServices.Orders.FindForCurrentStore(orderbvin);
            if (order == null)
            {
                resp.Success   = false;
                resp.Messages += "Order id was invalid for password reset. ";
            }
            else
            {
                if (order.CustomProperties.Where(y => (y.DeveloperId == "bvsoftware") &&
                                                 (y.Key == "allowpasswordreset") &&
                                                 (y.Value == "1")).Count() < 1)
                {
                    resp.Success   = false;
                    resp.Messages += "This order does not allow password reset anymore. Please use the 'Forgot Password' link when signing in. ";
                }
            }

            if (password.Trim().Length < WebAppSettings.PasswordMinimumLength)
            {
                resp.Success   = false;
                resp.Messages += "Password must be at least " + WebAppSettings.PasswordMinimumLength + " characters long. ";
            }

            if (resp.Success)
            {
                MTApp.MembershipServices.ResetPasswordForCustomer(email, password);

                // Turn off reset key so that this can only happen once.
                var prop = order.CustomProperties.Where(y => (y.DeveloperId == "bvsoftware") &&
                                                        (y.Key == "allowpasswordreset") &&
                                                        (y.Value == "1")).FirstOrDefault();
                if (prop != null)
                {
                    prop.Value = "0";
                }
                MTApp.OrderServices.Orders.Update(order);
            }

            return(new PreJsonResult(MerchantTribe.Web.Json.ObjectToJson(resp)));
        }
        public SimpleResponse GetMatches(int id)
        {
            MatchModel model;

            try
            {
                model = _service.FindById(id);
            }
            catch (Exception e)
            {
                return(SimpleResponse.Error(e.StackTrace));
            }
            return(SimpleResponse.Success(model));
        }
        // GET: api/Matches/5
        //[ResponseType(typeof(Match))]
        //public async Task<IHttpActionResult> GetMatch(int id)
        //{
        //    Match match = await db.Matches.FindAsync(id);
        //    if (match == null)
        //    {
        //        return NotFound();
        //    }

        //    //return Ok(match);
        //    return Json(new
        //    {
        //        DateTime = match.DateTime,
        //        Teams = new { TeamId = match.Teams.First().Id, Name = match.Teams.First().Name },
        //        League = match.League
        //    });
        //}

        //// PUT: api/Matches/5
        //[ResponseType(typeof(void))]
        //public async Task<IHttpActionResult> PutMatch(int id, Match match)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return BadRequest(ModelState);
        //    }

        //    if (id != match.Id)
        //    {
        //        return BadRequest();
        //    }

        //    db.Entry(match).State = EntityState.Modified;

        //    try
        //    {
        //        await db.SaveChangesAsync();
        //    }
        //    catch (DbUpdateConcurrencyException)
        //    {
        //        if (!MatchExists(id))
        //        {
        //            return NotFound();
        //        }
        //        else
        //        {
        //            throw;
        //        }
        //    }

        //    return StatusCode(HttpStatusCode.NoContent);
        //}

        // POST: api/Matches
        //[ResponseType(typeof(Match))]
        //public async Task<IHttpActionResult> PostMatch(Match match)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return BadRequest(ModelState);
        //    }

        //    db.Matches.Add(match);
        //    await db.SaveChangesAsync();

        //    return CreatedAtRoute("DefaultApi", new { id = match.Id }, match);
        //}

        public SimpleResponse PostMatch(MatchModel model)
        {
            Match newMatch;

            try
            {
                newMatch = _service.Create(model);
            }
            catch (Exception e)
            {
                return(SimpleResponse.Error(e.Message + "\t" + e.StackTrace));
            }
            return(SimpleResponse.Success(new { Id = newMatch.Id, DateTime = newMatch.DateTime, LeagueId = newMatch.LeagueId }));
        }
Ejemplo n.º 26
0
        public void UserInitialize(CoreList AddonInjections)
        {
            if (Nickname == null)
            {
                if (this.Subscriber.BotNickName == null)
                {
                    Nickname = Subscriber.AdminUsername;
                }
                else
                {
                    Nickname = Subscriber.BotNickName;
                }
            }

            this.connectionChange = new AutoResetEvent(false);
            AsyncTcpDispatcher    = new AsyncTcpDispatcher(Subscriber.ServerIp, (ushort)Subscriber.ServerPort);
            QueryRunner           = new QueryRunner(AsyncTcpDispatcher);

            //atd.ServerClosedConnection += atd_ServerClosedConnection;
            AsyncTcpDispatcher.ReadyForSendingCommands += atd_ReadyForSendingCommands;
            AsyncTcpDispatcher.SocketError             += atd_SocketError;

            Connect();

            SimpleResponse loginResult = Login();

            if (loginResult.IsBanned)
            {
                logger.Info("Login failure due to ban: {0}", loginResult.ResponseText);
            }
            else if (loginResult.IsErroneous)
            {
                logger.Info("Login failure due to error: {0}", loginResult.ResponseText);
            }
            else
            {
                SendSetNameCmd();

                SelectServer(Subscriber);

                SendSetNameCmd();

                UpdateServerUniqueId();

                whoAmI = QueryRunner.SendWhoAmI();

                RegisterEvents();
            }
        }
        public override SimpleResponse <CustomerResult> Handle(CustomerReadByIdQuery query)
        {
            var response = new SimpleResponse <CustomerResult>();

            try
            {
                if (query.Id == null)
                {
                    return(response);
                }

                if ((query.Id ?? 0) < 1)
                {
                    return(response);
                }

                using (var connection = GetDbConnection())
                {
                    try
                    {
                        connection.OpenIfNot();
                        var CustomerEntList = connection.Select <CustomerEntity>(p => p.CustomerId == query.Id)?.ToList() ?? new List <CustomerEntity>();
                        response.Data = new CustomerResult
                        {
                            Customer = (CustomerEntList.Select(p => new CustomerViewModel
                            {
                                CustomerId = p.CustomerId,
                                FirstName = p.FirstName,
                                LastName = p.LastName,
                                LastUpdate = p.LastUpdate
                            }).ToList() ?? new List <CustomerViewModel>()).FirstOrDefault()
                        };
                        response.ResponseCode = response.Data != null ? 1 : 0;
                        response.RCode        = response.ResponseCode.ToString();
                    }
                    finally
                    {
                        connection.CloseIfNot();
                    }
                }
            }
            catch (Exception ex)
            {
                response.ResponseCode = -500;
                DayLogger.Error(ex);
            }

            return(response);
        }
Ejemplo n.º 28
0
        public ContentResult CheckNutrient()
        {
            var webhookRequest = _googleJsonHelper.GetWebhook(Request);

            WebhookResponse response = new WebhookResponse();

            if (webhookRequest.QueryResult.Parameters.Fields.ContainsKey("Nutrient"))
            {
                var nutrient = webhookRequest.QueryResult.Parameters.Fields.GetValueOrDefault("Nutrient").StringValue;

                // TODO Check if the nutrient is ok
                var nutrientCheckResult = _mongoDBConnector.CheckNutrient(nutrient);

                SimpleResponses simpleResponses = new SimpleResponses();
                SimpleResponse  simpleResponse;

                if (nutrientCheckResult.IsEvilForYou)
                {
                    simpleResponse = new SimpleResponse()
                    {
                        DisplayText =
                            $"Sorry, the {nutrient} seems to be evil for you, because {nutrientCheckResult.Message}. I suggest you this alternative: {nutrientCheckResult.AlternativeNutrient}",
                        TextToSpeech =
                            $"Sorry, the {nutrient} seems to be evil for you, because {nutrientCheckResult.Message}. I suggest you this alternative: {nutrientCheckResult.AlternativeNutrient}"
                    };
                }
                else
                {
                    simpleResponse = new SimpleResponse()
                    {
                        DisplayText  = $"OK {nutrient} seems ok! Would you like to eat it at home, or outside?",
                        TextToSpeech = $"OK {nutrient} seems ok! Would you like to eat it at home, or outside?"
                    };
                }

                simpleResponses.SimpleResponses_.Add(simpleResponse);

                response.FulfillmentMessages.Add(new Message()
                {
                    Platform        = Platform.ActionsOnGoogle,
                    SimpleResponses = simpleResponses
                });
            }


            string responseJson = response.ToString();

            return(Content(responseJson, "application/json"));
        }
Ejemplo n.º 29
0
        protected void RunQueries(Action <QueryRunner> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            string host = ConfigurationManager.AppSettings["host"];

            if (host == null)
            {
                throw new ConfigurationErrorsException("host could not be found in web.config");
            }

            string portString = ConfigurationManager.AppSettings["port"];

            if (portString == null)
            {
                throw new ConfigurationErrorsException("port could not be found in web.config");
            }

            ushort port;

            if (!ushort.TryParse(portString, NumberStyles.Integer, CultureInfo.InvariantCulture, out port))
            {
                throw new ConfigurationErrorsException("port in web.config has invalid an invalid format.");
            }

            string login    = ConfigurationManager.AppSettings["login"];
            string password = ConfigurationManager.AppSettings["password"];


            using (QueryRunner queryRunner = new QueryRunner(new SyncTcpDispatcher(host, port)))  // host and port
            {
                // connection to the TS3-Server is established with the first query command

                if (!login.IsNullOrTrimmedEmpty() && !password.IsNullOrTrimmedEmpty())
                {
                    SimpleResponse loginResponse = queryRunner.Login(login, password); // login using the provided username and password and show a dump-output of the response in a textbox

                    if (loginResponse.IsErroneous)
                    {
                        throw new NotSupportedException("Login failed for the given username and password!");
                    }
                }

                action(queryRunner);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Executa a chamada a API para efetivar o match
        /// </summary>
        /// <param name="necessidadeId">Id do item de necessidade</param>
        /// <param name="doacaoId">Id do item de doação</param>
        protected async Task <SimpleResponse> ExecutaMatch(Guid necessidadeId, Guid doacaoId)
        {
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ObterToken());
            HttpResponseMessage resultApi = await _client.PostAsJsonAsync("/api/v1/Item/match", new { DoacaoId = doacaoId, NecessidadeId = necessidadeId });

            if (resultApi.StatusCode.Equals(HttpStatusCode.Unauthorized))
            {
                throw new SessaoExpiradaException();
            }
            string conteudo = await resultApi.Content.ReadAsStringAsync();

            SimpleResponse response = JsonConvert.DeserializeObject <SimpleResponse>(conteudo);

            return(response);
        }
        public static async Task <SimpleResponse <T> > SendMessage <T>(SimpleRestClient simpleClient, SimpleMessage simpleMessage)
        {
            SimpleResponse <T> toReturn = new SimpleResponse <T>();

            Web.HttpClient httpClient = new Web.HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage requestMessage = await BuildHttpRequestMessage(simpleClient, simpleMessage);

            HttpResponseMessage response = await httpClient.SendRequestAsync(requestMessage);

            toReturn.DataRaw       = response.Content;
            toReturn.DataConverted = JsonConvert.DeserializeObject <T>(response.Content.ToString());

            return(toReturn);
        }
Ejemplo n.º 32
0
        public static void muteUnmuteRTP(bool state)
        {
            // Get the host address, username and port for the ServerQuery Login
            Dictionary <string, string> config = getTSInfo();

            if (config == null)
            {
                return;
            }

            string sqPW = getSQPassword();
            ushort port;
            uint   talkPwr = (uint)(state ? 50 : 0);

            Regex regex = new Regex(@"^[0-9]+$");

            if (regex.IsMatch(config["port"]))
            {
                port = Convert.ToUInt16(config["port"]);
            }
            else
            {
                string msg = "ERROR: Invalid port. Port number may contain numbers 1-9 only.";
                string cap = "Error";
                errorMSG(msg, cap);
                return;
            }

            // Establish a connection with the TS3 server
            using (QueryRunner QR = new QueryRunner(new SyncTcpDispatcher(config["addr"], port)))
            {
                if (loginAndUse(QR, config, sqPW) != null)
                {
                    SimpleResponse muteResponse = QR.EditChannel(CID_RTP,
                                                                 new ChannelModification()
                    {
                        NeededTalkPower = talkPwr
                    });

                    if (muteResponse.IsErroneous)
                    {
                        string muteMsg = $"ERROR: {muteResponse.ErrorMessage}\n\n Error ID: {muteResponse.ErrorId}";
                        string muteCap = "Mute Channel Failed";
                        errorMSG(muteMsg, muteCap);
                    }
                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 搜索结果页
        /// </summary>
        /// <returns></returns>
        public ActionResult SearchList(string keyword, int pageIndex = 1, int pageSize = 10)
        {
            string where = GetSearchWhere(null, 0, 0, 0, keyword, Constants.Novel.ShowLocation.searchlist);
            string orderby = " order by n.Hits desc, n.FavCount desc, n.id desc";
            int    rowCount;
            var    bookList = _bookService.GetPagerList(where, orderby, out rowCount, pageIndex, pageSize,
                                                        new { keyword = UrlParameterHelper.GetDecodingParams("keyword") },
                                                        "[dbo].[Novel] as n inner join [dbo].[NovelClass] nc on nc.Id = n.ClassId",
                                                        "n.Id, n.Title, n.LargeCover, n.ThumbCover, n.SmallCover, n.UpdateStatus, nc.ClassName,n.Author,n.ShortDescription,n.ShortWordSize,n.ContentType, n.IsHideAuthor");

            ViewBag.TotalCount = rowCount;
            ViewBag.Keyword    = keyword;
            var model = new SimpleResponse <IEnumerable <NovelView> >(!bookList.IsNullOrEmpty(), bookList);

            return(View(model));
        }
Ejemplo n.º 34
0
 public async Task <SimpleResponse> CreateCourseAsync(CourseDetail course)
 {
     if (string.IsNullOrEmpty(course.Name))
     {
         return(SimpleResponse.Error("Name cannot be empty"));
     }
     try
     {
         await _ivySchoolRepository.CreateCourse(ConvertToCourseDb(course));
     }
     catch (DBOperationException ex)
     {
         return(SimpleResponse.Error(ex.Message));
     }
     return(SimpleResponse.Success());
 }
Ejemplo n.º 35
0
 public SimpleResponse<bool> CheckIfUniqueForCompany(IDRequest request)
 {
     var response = new SimpleResponse<bool>();
     try
     {
         var fieldName =	request["FieldName"];
         var value = request["Value"];
         var db = ImardaDatabase.CreateDatabase(Util.GetConnName<Company>());
         string query = string.Format("SELECT COUNT(*) FROM Company WHERE {0} = '{1}' AND ID <> '{2}'", fieldName, value, request.ID);
         using (IDataReader dr = db.ExecuteDataReader(CommandType.Text, query))
         {
             if (dr.Read() && Convert.ToInt32(dr[0]) > 0)
                 response = new SimpleResponse<bool>(false);
             else
                 response = new SimpleResponse<bool>(true);
             return response;
         }
     }
     catch (Exception ex)
     {
         return ErrorHandler.Handle<SimpleResponse<bool>>(ex);
     }
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Change the security entity company
 /// </summary>
 /// <param name="request">.ID = new company ID, ["username"] = SecurityEntity.LoginUserName</param>
 /// <returns>CRMID</returns>
 public SimpleResponse<Guid> TransferUser(IDRequest request)
 {
     try
     {
         SimpleResponse<Guid> appResponse = null;
         var service = ImardaProxyManager.Instance.IImardaSecurityProxy;
         ChannelInvoker.Invoke(delegate(out IClientChannel channel)
         {
             channel = service as IClientChannel;
             var resp = service.GetSecurityEntityByLoginUserName(request);
             ErrorHandler.CheckItem(resp);
             var securityEntity = resp.Item;
             securityEntity.CompanyID = request.ID;
             var resp2 = service.SaveSecurityEntity(new SaveRequest<SecurityEntity>(securityEntity));
             ErrorHandler.Check(resp2);
             appResponse = new SimpleResponse<Guid>(securityEntity.CRMId);
         });
         return appResponse;
     }
     catch (Exception ex)
     {
         return ErrorHandler.Handle<SimpleResponse<Guid>>(ex);
     }
 }
 private void ParseResponse(SimpleResponse response)
 {
     Success = (response.Status == "ok");
 }
        private void ParseResponse(SimpleResponse response)
        {
            Success = (response.Status == "ok");

            if (!string.IsNullOrWhiteSpace(response.Data))
                ResponseData = response.Data;
        }
        private void ParseResponse(SimpleResponse response)
        {
            Success = (response.Status == "ok");

            int monitorId;
            if (int.TryParse(response.Data, out monitorId))
                MonitorId = monitorId;
        }
        public ActionResult SetFirstPassword()
        {
            string email = Request.Form["email"] ?? string.Empty;
            string password = Request.Form["password"] ?? string.Empty;
            string orderbvin = Request.Form["orderbvin"] ?? string.Empty;

            SimpleResponse resp = new SimpleResponse();
            resp.Success = true;
            
            MerchantTribe.Commerce.Orders.Order order = MTApp.OrderServices.Orders.FindForCurrentStore(orderbvin);
            if (order == null) 
            {
                resp.Success = false;
                resp.Messages += "Order id was invalid for password reset. ";
            }
            else            
            {
                if (order.CustomProperties.Where(y => (y.DeveloperId == "bvsoftware")
                                            && (y.Key=="allowpasswordreset")
                                            && (y.Value=="1")).Count() < 1)
                {
                    resp.Success = false;
                    resp.Messages += "This order does not allow password reset anymore. Please use the 'Forgot Password' link when signing in. ";
                }
            }
            
            if (password.Trim().Length < WebAppSettings.PasswordMinimumLength)
            {
                resp.Success = false;
                resp.Messages += "Password must be at least " + WebAppSettings.PasswordMinimumLength + " characters long. ";
            }
            
            if (resp.Success)
            {
                MTApp.MembershipServices.ResetPasswordForCustomer(email, password);                                

                // Turn off reset key so that this can only happen once.
                var prop = order.CustomProperties.Where(y => (y.DeveloperId == "bvsoftware")
                                            && (y.Key=="allowpasswordreset")
                                            && (y.Value=="1")).FirstOrDefault();
                if (prop != null)
                {
                    prop.Value = "0";
                }
                MTApp.OrderServices.Orders.Update(order);
            }
            
            return new PreJsonResult(MerchantTribe.Web.Json.ObjectToJson(resp));
        }
 public override Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context)
 {
     var response = new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) };
     return Task.FromResult(response);
 }
        private void ParseResponse(SimpleResponse response)
        {
            if (response.Status != "ok")
                Success = false;

            else
            {
                Success = true;
                int monitorId;
                if (int.TryParse(response.Data, out monitorId))
                    TestId = monitorId;
            }
        }