Пример #1
0
        public ActionResult CreatePromotionCoupons(FormCollection collection)
        {
            ResponseMessage result = new ResponseMessage();
            var name = collection["name"];
            var count = collection["count"];
            var values = collection["values"];
            var date1 = collection["date1"];
            var date2 = collection["date2"];
            var activity = collection["activity"];
            var morethan = collection["morethan"];
            var value1 = collection["value1"];
            var select = collection["select"];

            #region 优惠券
            promotion_coupons info = new promotion_coupons();
            info.Initial();
            info.name = name;
            info.issue_num = BaseTool.GetIntNumber(count);
            info.values = BaseTool.GetIntNumber(values);
            info.startdate = BaseTool.GetDateTime(date1);
            info.enddate = BaseTool.GetDateTime(date2);
            info.events_id = BaseTool.GetIntNumber(activity);
            info.issue_status = BaseTool.GetIntNumber(select);
            #endregion

            #region 条件
            List<promotion_coupons_usecase> usecasellist = new List<promotion_coupons_usecase>();
            if (BaseTool.GetIntNumber(morethan) > 0 && BaseTool.GetIntNumber(value1) > 0)
            {
                var usecase = new promotion_coupons_usecase();
                usecase.Initial();
                usecase.case_pamars = morethan;
                usecase.case_pamars_value = value1;
                usecasellist.Add(usecase);
            }
            #endregion

            #region 优惠券明细
            List<promotion_coupons_detail> detaillist = new List<promotion_coupons_detail>();
            for (int i = 0; i < info.issue_num; i++)
            {
                promotion_coupons_detail detail = new promotion_coupons_detail();
                detail.Initial();
                detail.code = string.Empty;
                detaillist.Add(detail);
            }
            #endregion

            promotion_events_Bll bll = new promotion_events_Bll();
            string error = string.Empty;
            bll.CreatePromotionCoupons(info, detaillist, usecasellist, out error);

            int record = 0;
            List<promotion_coupons_detail> list = bll.SearchPromotionCouponsList(info.pkid, 0, 0, 0, 0, null, null, null, null,
            null, null, 1, 1000, out record, out error);
            ViewBag.detaillist = list;

            result.bSuccess = true;
            return View(info);
        }
Пример #2
0
        public ResponseMessage SendEmail(string to, string cc, string bcc, string subject, string content)
        {
            WebUI.ServiceReferenceEmail.GeneralClient gc = new GeneralClient();
            WebUI.ServiceReferenceEmail.Message_Request mrequest = new Message_Request();
            WebUI.ServiceReferenceEmail.Message_Response mresponse = new Message_Response();
            WebUI.ServiceReferenceEmail.ResponseMessage rmessage = new ResponseMessage();

            mrequest.TypeMessage = "1";
            mrequest.To = to;
            mrequest.Cc = cc;
            mrequest.Bcc = bcc;
            mrequest.Subject = subject;
            mrequest.Content = content;
            mrequest.DatetimeCreated = DateTime.Now.ToString("yyyyMMddssmmHH");

            WebUI.ServiceReferenceEmail.Common_Request cr = new Common_Request();

            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

            cr.UserName = "******";
            cr.Password = "******";
            mresponse = gc.Send_Message(cr, mrequest, out rmessage);

            return rmessage;
        }
Пример #3
0
        public ResponseMessage Post([FromBody]md_docter value)
        {
            Model.ResponseMessage result = new ResponseMessage();
            try
            {
                string error = string.Empty;
                Base_Bll bll = new Base_Bll();
                md_docter info = bll.GetInfo<md_docter>(DoctorID);
                string encryptKey = string.Empty;
                var password = BaseTool.EncryptDES(value.oldpwd, encryptKey);

                if (info.login_pwd == password)
                {
                    var newpassword = BaseTool.EncryptDES(value.login_pwd, encryptKey);
                    info.login_pwd = newpassword;
                    info = new md_docter_Bll().UpdateDocter(info, out error);

                    if (string.IsNullOrEmpty(error))
                    {
                        result.bSuccess = true;
                        result.Message = "修改成功";
                    }
                    else
                    {
                        result.bSuccess = false;
                        result.Message = error;
                    }
                }
            }
            catch(Exception ex)
            {
                result.bSuccess=false;
            }
            return result;
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {

            bool inherit = true;
            if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
            {
                if (!IsAuthenticated())
                {
                    if (filterContext.HttpContext.Request.IsAjaxRequest())
                    {
                        ResponseMessage respMsg = new ResponseMessage
                        {
                            IsSuccess = false,
                            ErrorCode = "00003",
                            Message = "请先登录!"
                        };
                        JsonResult result = new JsonResult();
                        result.Data = respMsg;
                        result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                        filterContext.Result = result;
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult(LogOnUrl);
                    }
                }
            }

        }
Пример #5
0
        public Model.ResponseMessage Post([FromBody]md_cashdraw_app info)
        {
            md_cashdraw_app_Bll cashdrawBll = new md_cashdraw_app_Bll();
            string error = string.Empty;

            md_cashdraw_app cashdraw = new md_cashdraw_app();
            cashdraw.Initial();
            cashdraw.drid = DoctorID.ToString();
            cashdraw.drawmoney = info.drawmoney;
            cashdraw.in_bank = info.in_bank;
            cashdrawBll.CreateCashdrawApp(cashdraw, out error);

            Model.ResponseMessage result = new ResponseMessage();
            if (!string.IsNullOrEmpty(error))
            {
                result.bSuccess = true;
            }
            else
            {
                result.bSuccess = false;
                result.Message = error;
            }

            return result;
        }
 public SendQueryEventArgs(IPEndPoint endpoint, QueryMessage query, ResponseMessage response)
     : base(null)
 {
     EndPoint = endpoint;
     Query = query;
     Response = response;
 }
Пример #7
0
        // POST api/<controller>
        public ResponseMessage Post([FromBody]dr_message info)
        {
            dr_message_Bll messageBll = new dr_message_Bll();
            string error = string.Empty;

            dr_message message = new dr_message();
            message.Initial();
            message.drid = DoctorID;
            message.msg_content = info.msg_content;
            message.attach_file1 = info.attach_file1;
            message.attach_file2 = info.attach_file2;
            message.attach_file3 = info.attach_file3;
            messageBll.CreateDrMessage(message,out error);

            Model.ResponseMessage result = new ResponseMessage();
            if (!string.IsNullOrEmpty(error))
            {
                result.bSuccess = true;
            }
            else
            {
                result.bSuccess = false;
                result.Message = error;
            }
            return result;
        }
 public void TestConstructor()
 {
     var response = new ResponseMessage(
         VersionCode.V3,
         new Header(
             new Integer32(500),
             new Integer32(4000),
             Levels.Reportable),
         new SecurityParameters(
             OctetString.Empty,
             Integer32.Zero,
             Integer32.Zero,
             new OctetString("lextm"),
             OctetString.Empty,
             OctetString.Empty),
         new Scope(
             OctetString.Empty,
             OctetString.Empty,
             new ResponsePdu(0x2C6B, ErrorCode.NoError, 0, new List<Variable>{ new Variable(new ObjectIdentifier("1.3.6.1.1.2.5.0"), new Integer32(400))})),
         DefaultPrivacyProvider.DefaultPair,
         true,
         null);
     var registry = new UserRegistry();
     registry.Add(new OctetString("lextm"), DefaultPrivacyProvider.DefaultPair);
     var messages = MessageFactory.ParseMessages(response.ToBytes(), registry);
     Assert.AreEqual(1, messages.Count);
 }
Пример #9
0
        /// <summary>
        /// 清理资源
        /// </summary>
        public void Dispose()
        {
            this.reset.Reset();

            this.reset = null;
            this.message = null;
        }
Пример #10
0
        /// <summary>
        /// 提交一个响应给请求消息。
        /// </summary>
        /// <param name="configuration">响应消息配置。</param>
        /// <exception cref="ArgumentNullException"><paramref name="configuration"/> 为null。</exception>
        public void Post(Action<ResponseMessage> configuration)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration");

            var message = new ResponseMessage(_message.Id);
            configuration(message);
            _bus.Publish(message);
        }
Пример #11
0
        public static void GenerateExceptionResponse(this HttpActionContext actionContext, Type responsePayloadType, ResponseMessage message)
        {
            var response = responsePayloadType.GetConstructor(System.Type.EmptyTypes).Invoke(null);
            response.SetValue("Exception", message);

            actionContext.Response = actionContext.Request.CreateResponse();
            actionContext.Response.StatusCode = System.Net.HttpStatusCode.OK;
            actionContext.Response.Content = new ObjectContent(responsePayloadType, response, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
        }
Пример #12
0
 public JsonResult GetAll()
 {
     var respBody = ServiceClient.Execute<NoneRequest, GetAllResponse>("T.PC.GetAll",new NoneRequest{ }).Body;
     ResponseMessage resp = new ResponseMessage
     {
        Body = respBody
     };
     return Json(resp, JsonRequestBehavior.AllowGet);
 }
 private void CreateErrorMessage(HttpActionContext actionContext, String errorMessage)
 {
     ResponseMessage resp = new ResponseMessage
     {
         IsSuccess = false,
         ErrorCode = "00006",
         Message = errorMessage
     };
     actionContext.Response = actionContext.Request.CreateResponse<ResponseMessage>(resp);
 }
        public void TestBuiltinException()
        {
            var serializer = new ProtobufSerializer(null);

            var exception = new ArgumentException("Test");
            var obj = new ResponseMessage { Exception = exception };
            var bytes = serializer.ToBinary(obj);

            var obj2 = (ResponseMessage)serializer.FromBinary(bytes, null);
            Assert.Equal(obj.Exception.GetType(), obj2.Exception.GetType());
        }
Пример #15
0
        public static ResponseMessage DirectUserMessage(string userChannel, string userId, string text, ResponseMessage message = null)
        {
            if(message == null)
                message = new ResponseMessage();

            message.Channel = userChannel;
            message.ResponseType = ResponseType.DirectMessage;
            message.UserId = userId;
            message.Text = text;

            return message;
        }
Пример #16
0
        public static ResponseMessage ChannelMessage(string channel, string text, Attachment attachment, ResponseMessage message = null)
        {
            if (message == null)
                message = new ResponseMessage();

            message.Channel = channel;
            message.ResponseType = ResponseType.Channel;
            message.Text = text;
            message.Attachment = attachment;

            return message;
        }
        public void TestSourceSurrogate()
        {
            var serializer = new ProtobufSerializer(null);

            var obj = new ResponseMessage
            {
                ReturnPayload = new Source { Data = "Hello" }
            };

            var bytes = serializer.ToBinary(obj);

            var obj2 = (ResponseMessage)serializer.FromBinary(bytes, null);
            Assert.Equal(obj.ReturnPayload.Value, obj2.ReturnPayload.Value);
        }
Пример #18
0
        public void TestSeriDeseri_ReplyMessageWithNothing()
        {
            var serializer = new ProtobufSerializer(null);

            var obj = new ResponseMessage
            {
                RequestId = 12345678,
            };

            var bytes = serializer.ToBinary(obj);

            var obj2 = (ResponseMessage)serializer.FromBinary(bytes, null);
            Assert.Equal(obj.RequestId, obj2.RequestId);
        }
        public void TestSurrogateForAddress()
        {
            var serializer = new ProtobufSerializer(null);

            var obj = new ResponseMessage
            {
                RequestId = 12345678,
                ReturnPayload = new AddressReturnMessage { v = Address.Parse("akka://system@host:1234") }
            };

            var bytes = serializer.ToBinary(obj);

            var obj2 = (ResponseMessage)serializer.FromBinary(bytes, null);
            Assert.Equal(obj.ReturnPayload.Value.ToString(), obj2.ReturnPayload.Value.ToString());
        }
        public void TestTypeAliasException()
        {
            var serializer = new ProtobufSerializer(null);

            var exception = new TestException { ErrorCode = 1000, ErrorDetail = "Test" };
            var obj = new ResponseMessage { Exception = exception };
            var bytes = serializer.ToBinary(obj);

            var obj2 = (ResponseMessage)serializer.FromBinary(bytes, null);
            Assert.Equal(obj.Exception.GetType(), obj2.Exception.GetType());

            var exception2 = (TestException)obj2.Exception;
            Assert.Equal(exception.ErrorCode, exception2.ErrorCode);
            Assert.Equal(exception.ErrorDetail, exception2.ErrorDetail);
        }
Пример #21
0
        protected void QueueError(RequestMessage reqMsg, Exception error)
        {
            if (reqMsg != null)
            {
                var resMsg = new ResponseMessage
                {
                    TransactionId = reqMsg.TransactionId,
                    ReturnType = reqMsg.ReturnType,
                    ServiceName = reqMsg.ServiceName,
                    MethodName = reqMsg.MethodName,
                    Error = error
                };

                QueueMessage(resMsg);
            }
        }
Пример #22
0
        public static void GenerateExceptionResponseEnumToString(this HttpActionContext actionContext, Type responsePayloadType, ResponseMessage message)
        {
            var response = responsePayloadType.GetConstructor(System.Type.EmptyTypes).Invoke(null);
            response.SetValue("Exception", message);

            actionContext.Response = actionContext.Request.CreateResponse();
            actionContext.Response.StatusCode = System.Net.HttpStatusCode.OK;
            actionContext.Response.Content = new ObjectContent(responsePayloadType, response, new System.Net.Http.Formatting.JsonMediaTypeFormatter()
            {
                SerializerSettings = new JsonSerializerSettings
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    Converters = { new Newtonsoft.Json.Converters.StringEnumConverter() }
                }
            });
        }
Пример #23
0
        public void ProvideFault(
            Exception error,
            MessageVersion version,
            ref Message fault)
        {
            if (error is WebFaultException)
                return;

            object responseMessage;
            HttpStatusCode responseStatusCode;
            if (error is UserException)
            {
                var userError = (UserException)error;
                var localizer = AutofacServiceHostFactory.Container.Resolve<ILocalizer>();

                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage = new ResponseMessage { UserMessage = localizer[userError.Message, userError.MessageParameters], SystemMessage = userError.SystemMessage };
            }
            else if (error is LegacyClientException)
            {
                responseStatusCode = ((LegacyClientException)error).HttpStatusCode;
                responseMessage = error.Message;
            }
            else if (error is ClientException)
            {
                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage = new ResponseMessage { SystemMessage = error.Message };
            }
            else
            {
                responseStatusCode = HttpStatusCode.InternalServerError;
                responseMessage = new ResponseMessage { SystemMessage = "Internal server error occurred (" + error.GetType().Name + "). See RhetosServer.log for more information." };
            }

            fault = Message.CreateMessage(version, "", responseMessage,
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(responseMessage.GetType()));

            fault.Properties.Add(WebBodyFormatMessageProperty.Name,
                new WebBodyFormatMessageProperty(WebContentFormat.Json));

            fault.Properties.Add(HttpResponseMessageProperty.Name,
                new HttpResponseMessageProperty {StatusCode = responseStatusCode});

            var response = WebOperationContext.Current.OutgoingResponse;
            response.ContentType = "application/json; charset=" + response.BindingWriteEncoding.WebName;
            response.StatusCode = responseStatusCode;
        }
        public void OnException(ExceptionContext filterContext)
        {
            ResponseMessage resp = new ResponseMessage
            {
                IsSuccess = false,
                ErrorCode = "00001",
                Message = filterContext.Exception.Message
            };
            if (filterContext.Exception is AhooException)
            {
                AhooException meEx = filterContext.Exception as AhooException;
                resp.ErrorCode = meEx.ErrorCode;
            }
            Logger.Error(filterContext.Exception);
            filterContext.Result = new JsonResult { Data = resp, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

        }
Пример #25
0
    public static NetworkResponse Parse(MemoryStream dataStream)
    {
        ResponseMessage response = new ResponseMessage();
        response.status = DataReader.ReadShort(dataStream);

        if (response.status == 0) {
            response.type = DataReader.ReadShort(dataStream);

            if (response.type == 0 || response.type == 2) {
                response.username = DataReader.ReadString(dataStream);
            }

            response.message = DataReader.ReadString(dataStream);
        }

        return response;
    }
Пример #26
0
        /// <summary>
        /// 异步调用方法
        /// </summary>
        /// <param name="reqMsg"></param>
        public ResponseMessage CallService(RequestMessage reqMsg)
        {
            var context = OperationContext.Current;

            //实例化异步调用器
            var worker = smart.QueueWorkItem<OperationContext, RequestMessage, ResponseMessage>
                                            (GetResponse, context, reqMsg);

            //等待响应
            ResponseMessage resMsg = null;

            try
            {
                resMsg = worker.GetResult(elapsedTime, true);
            }
            catch (Exception ex)
            {
                //结束当前线程
                if (!worker.IsCompleted) worker.Cancel(true);

                var body = string.Format("Call service ({0}, {1}) timeout ({2}) ms. Error: {4}\r\nParameters => {3}"
                    , reqMsg.ServiceName, reqMsg.MethodName, (int)elapsedTime.TotalMilliseconds, reqMsg.Parameters.ToString(), ex.Message);

                //获取异常
                var error = IoCHelper.GetException(OperationContext.Current, reqMsg, body);

                //将异常信息写出
                logger.Write(error);

                //处理异常
                resMsg = new ResponseMessage
                {
                    TransactionId = reqMsg.TransactionId,
                    ReturnType = reqMsg.ReturnType,
                    ServiceName = reqMsg.ServiceName,
                    MethodName = reqMsg.MethodName,
                    Parameters = reqMsg.Parameters,
                    Error = error
                };
            }

            //返回响应的消息
            return resMsg;
        }
Пример #27
0
        // POST api/<controller>
        public Model.ResponseMessage Post([FromBody]patient_druguse_suggest info, List<patient_druguse_suggest_rcd> drugList)
        {
            patient_druguse_suggest_Bll suggestBll = new patient_druguse_suggest_Bll();
            string error = string.Empty;
            bool success = suggestBll.CreateDrugSuggest(info, drugList, out error);

            Model.ResponseMessage result = new ResponseMessage();
            if (success)
            {
                result.bSuccess = true;
            }
            else
            {
                result.bSuccess = false;
                result.Message = error;
            }

            return result;
        }
Пример #28
0
        public Model.ResponseMessage Post([FromBody] patient_message info)
        {
            patient_message_Bll messageBll = new patient_message_Bll();
            string error = string.Empty;
            info = messageBll.CreateMessage(info, out error);

            Model.ResponseMessage result = new ResponseMessage();

            if (string.IsNullOrEmpty(error))
            {
                result.bSuccess = true;
                result.Extend1 = info.pkid.ToString();
            }
            else
            {
                result.bSuccess = false;
                result.Message = error;
            }

            return result;
        }
Пример #29
0
        // POST api/<controller>
        public ResponseMessage Post([FromBody]string value)
        {
            dr_recall_rcd_Bll recallBll = new dr_recall_rcd_Bll();
            string error = string.Empty;

            dr_recall_rcd recallrcd = new dr_recall_rcd();
            recallrcd.Initial();
            recallrcd.drid = DoctorID;
            recallBll.CreateDrRecallRcd(recallrcd, out error);

            Model.ResponseMessage result = new ResponseMessage();
            if (!string.IsNullOrEmpty(error))
            {
                result.bSuccess = true;
            }
            else
            {
                result.bSuccess = false;
                result.Message = error;
            }
            return result;
        }
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            ResponseMessage resp = new ResponseMessage
            {
                IsSuccess = false,
                ErrorCode = "00001",
                Message = actionExecutedContext.Exception.Message
            };
            if (actionExecutedContext.Exception is AhooException)
            {
                AhooException meEx = actionExecutedContext.Exception as AhooException;
                resp.ErrorCode = String.IsNullOrEmpty(meEx.ErrorCode) ? "00002" : meEx.ErrorCode;
                Logger.Warn(actionExecutedContext.Exception);
            }
            else
            {
                Logger.Error(actionExecutedContext.Exception);
            }

            actionExecutedContext.Response = actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse<ResponseMessage>(resp);
            base.OnException(actionExecutedContext);
        }
        private async Task <List <T> > ToListAsync <T>(QueryStream createStreamQuery, Query <T> createQuery, string queryText)
        {
            FeedIterator feedStreamIterator = createStreamQuery(queryText, null, RequestOptions);
            List <T>     streamResults      = new List <T>();

            while (feedStreamIterator.HasMoreResults)
            {
                ResponseMessage response = await feedStreamIterator.ReadNextAsync();

                response.EnsureSuccessStatusCode();

                StreamReader sr     = new StreamReader(response.Content);
                string       result = await sr.ReadToEndAsync();

                ICollection <T> responseResults = JsonConvert.DeserializeObject <CosmosFeedResponseUtil <T> >(result).Data;
                Assert.IsTrue(responseResults.Count <= 1);

                streamResults.AddRange(responseResults);
            }

            string   continuationToken  = null;
            List <T> pagedStreamResults = new List <T>();

            do
            {
                FeedIterator    pagedFeedIterator = createStreamQuery(queryText, continuationToken, RequestOptions);
                ResponseMessage response          = await pagedFeedIterator.ReadNextAsync();

                response.EnsureSuccessStatusCode();

                ICollection <T> responseResults = CosmosSerializer.FromStream <CosmosFeedResponseUtil <T> >(response.Content).Data;
                Assert.IsTrue(responseResults.Count <= 1);

                pagedStreamResults.AddRange(responseResults);
                continuationToken = response.Headers.ContinuationToken;
            } while (continuationToken != null);

            Assert.AreEqual(pagedStreamResults.Count, streamResults.Count);

            // Both lists should be the same
            string streamResultString      = JsonConvert.SerializeObject(streamResults);
            string streamPagedResultString = JsonConvert.SerializeObject(pagedStreamResults);

            Assert.AreEqual(streamPagedResultString, streamResultString);

            FeedIterator <T> feedIterator = createQuery(queryText, null, RequestOptions);
            List <T>         results      = new List <T>();

            while (feedIterator.HasMoreResults)
            {
                FeedResponse <T> iterator = await feedIterator.ReadNextAsync();

                Assert.IsTrue(iterator.Count <= 1);
                Assert.IsTrue(iterator.Resource.Count() <= 1);

                results.AddRange(iterator);
            }

            continuationToken = null;
            List <T> pagedResults = new List <T>();

            do
            {
                FeedIterator <T> pagedFeedIterator = createQuery(queryText, continuationToken, RequestOptions);
                FeedResponse <T> iterator          = await pagedFeedIterator.ReadNextAsync();

                Assert.IsTrue(iterator.Count <= 1);
                Assert.IsTrue(iterator.Resource.Count() <= 1);
                pagedResults.AddRange(iterator);
                continuationToken = iterator.ContinuationToken;
            } while (continuationToken != null);

            Assert.AreEqual(pagedResults.Count, results.Count);

            // Both lists should be the same
            string resultString      = JsonConvert.SerializeObject(results);
            string pagedResultString = JsonConvert.SerializeObject(pagedResults);

            Assert.AreEqual(pagedResultString, resultString);

            Assert.AreEqual(streamPagedResultString, resultString);
            return(results);
        }
        public async Task ChangeFeedIteratorCore_Retries()
        {
            string          continuation    = "TBD";
            ResponseMessage responseMessage = new ResponseMessage(HttpStatusCode.OK);

            responseMessage.Headers.ETag = continuation;
            responseMessage.Headers[Documents.HttpConstants.HttpHeaders.ItemCount] = "1";

            Mock <CosmosClientContext> cosmosClientContext = new Mock <CosmosClientContext>();

            cosmosClientContext.Setup(c => c.ClientOptions).Returns(new CosmosClientOptions());
            cosmosClientContext
            .Setup(c => c.ProcessResourceOperationStreamAsync(
                       It.IsAny <Uri>(),
                       It.IsAny <Documents.ResourceType>(),
                       It.IsAny <Documents.OperationType>(),
                       It.IsAny <RequestOptions>(),
                       It.IsAny <ContainerCore>(),
                       It.IsAny <PartitionKey?>(),
                       It.IsAny <Stream>(),
                       It.IsAny <Action <RequestMessage> >(),
                       It.IsAny <CosmosDiagnosticsContext>(),
                       It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(responseMessage));

            ContainerCore containerCore = Mock.Of <ContainerCore>();

            Mock.Get(containerCore)
            .Setup(c => c.ClientContext)
            .Returns(cosmosClientContext.Object);
            FeedTokenInternal feedToken = Mock.Of <FeedTokenInternal>();

            Mock.Get(feedToken)
            .Setup(f => f.EnrichRequest(It.IsAny <RequestMessage>()));
            Mock.Get(feedToken)
            .SetupSequence(f => f.ShouldRetryAsync(It.Is <ContainerCore>(c => c == containerCore), It.IsAny <ResponseMessage>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(true))
            .Returns(Task.FromResult(false));

            ChangeFeedIteratorCore changeFeedIteratorCore = new ChangeFeedIteratorCore(containerCore, feedToken, null);
            ResponseMessage        response = await changeFeedIteratorCore.ReadNextAsync();

            Mock.Get(feedToken)
            .Verify(f => f.UpdateContinuation(It.IsAny <string>()), Times.Exactly(2));

            Mock.Get(feedToken)
            .Verify(f => f.ShouldRetryAsync(It.Is <ContainerCore>(c => c == containerCore), It.IsAny <ResponseMessage>(), It.IsAny <CancellationToken>()), Times.Exactly(2));

            Mock.Get(cosmosClientContext.Object)
            .Verify(c => c.ProcessResourceOperationStreamAsync(
                        It.IsAny <Uri>(),
                        It.IsAny <Documents.ResourceType>(),
                        It.IsAny <Documents.OperationType>(),
                        It.IsAny <RequestOptions>(),
                        It.IsAny <ContainerCore>(),
                        It.IsAny <PartitionKey?>(),
                        It.IsAny <Stream>(),
                        It.IsAny <Action <RequestMessage> >(),
                        It.IsAny <CosmosDiagnosticsContext>(),
                        It.IsAny <CancellationToken>()), Times.Exactly(2));
        }
        public HttpResponseMessage SendEnvelope(TemplateSend template)
        {
            HttpResponseMessage responseToClient = new HttpResponseMessage();
            try
            {                
                int displayCode = 0;
                bool flagRole = true;
                System.Collections.Generic.IEnumerable<string> iHeader;
                Request.Headers.TryGetValues("AuthToken", out iHeader);
                string authToken = iHeader.ElementAt(0);
                Envelope envelope = new Envelope();
                Dictionary<string, string> roleDic = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);

                EnvelopeHelperMain objEnvelope = new EnvelopeHelperMain();
                EntityCollection<Recipients> recipients = new EntityCollection<Recipients>();
                Recipients recipint = new Recipients();

                using (var dbContext = new eSignEntities())
                {
                    List<Roles> roleList = new List<Roles>();
                    UserTokenRepository tokenRepository = new UserTokenRepository(dbContext);
                    EnvelopeRepository envelopeRepository = new EnvelopeRepository(dbContext);                    
                    string userEmail = tokenRepository.GetUserEmailByToken(authToken);

                    Guid UserId = tokenRepository.GetUserProfileUserIDByID(tokenRepository.GetUserProfileIDByEmail(userEmail));
                    envelope = envelopeRepository.GetTemplateDetails(template.TemplateCode, UserId);
                    
                    if (envelope == null)
                    {
                        ResponseMessage responseMessage = new ResponseMessage();
                        responseMessage.StatusCode = HttpStatusCode.NoContent;
                        responseMessage.StatusMessage = "NoContent";
                        responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["NoContent"].ToString());
                        responseToClient = Request.CreateResponse(HttpStatusCode.NoContent, responseMessage);
                        return responseToClient;                     
                    }

                    envelope.Message = template.MailBody;
                    envelope.Subject = template.MailSubject;
                    roleList = envelopeRepository.GetRoles(envelope.ID);
                    envelope.IsEnvelopeComplete = true;
                    envelope.IsEnvelopePrepare = true;
                    
                    if (template.Recipients.Count != roleList.Count)
                    {
                        ResponseMessage responseMessage = new ResponseMessage();
                        responseMessage.StatusCode = HttpStatusCode.Forbidden;
                        responseMessage.StatusMessage = "Forbidden";
                        responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["RolesCount"].ToString());
                        responseToClient = Request.CreateResponse(HttpStatusCode.Forbidden, responseMessage);
                        return responseToClient;   
                    }



                    foreach (var recip in template.Recipients)
                    {
                        flagRole = EnvelopeHelper.IsEmailValid(recip.EmailAddress);
                        if (!flagRole)
                        {
                            ResponseMessage responseMessage = new ResponseMessage();
                            responseMessage.StatusCode = HttpStatusCode.Forbidden;
                            responseMessage.StatusMessage = "Forbidden";
                            responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["Email"].ToString());
                            responseToClient = Request.CreateResponse(HttpStatusCode.Forbidden, responseMessage);
                            return responseToClient;   
                        }

                        foreach (var role in roleList)
                        {
                            if (role.Name.ToLower() == recip.Role.ToLower())
                            {
                                recipint.EmailAddress = recip.EmailAddress;
                                recipint.Name = recip.Role;
                                recipint.Order = role.Order;
                                recipint.RecipientTypeID = role.RecipientTypeID;
                                roleDic.Add(recipint.Name, recipint.EmailAddress);
                            }
                        }
                    }
                   


                    foreach (var role in roleList)
                    {
                        if (!roleDic.ContainsKey(role.Name))
                            flagRole = false;

                    }

                    if (!flagRole)
                    {
                        ResponseMessage responseMessage = new ResponseMessage();
                        responseMessage.StatusCode = HttpStatusCode.Forbidden;
                        responseMessage.StatusMessage = "Forbidden";
                        responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["RolesCount"].ToString());
                        responseToClient = Request.CreateResponse(HttpStatusCode.Forbidden, responseMessage);
                        return responseToClient;   
                    }

                    string Password = string.Empty;

                    if (envelope.PasswordReqdtoSign)
                    {
                        Password = ModelHelper.Decrypt(envelope.PasswordtoSign, envelope.PasswordKey, (int)envelope.PasswordKeySize);
                        envelope.PasswordtoSign = Password;
                    }
                    else
                        envelope.PasswordtoSign = null;


                    if (envelope.PasswordReqdtoOpen)
                    {
                        Password = ModelHelper.Decrypt(envelope.PasswordtoOpen, envelope.PasswordKey, (int)envelope.PasswordKeySize);
                        envelope.PasswordtoOpen = Password;
                    }
                    else
                        envelope.PasswordtoOpen = null;

                   roleDic.Add("Sender", userEmail);

                   objEnvelope.SetApiCallFlag();
                   bool status = objEnvelope.UpdatedEnvelope(envelope, template.TemplateCode, roleDic, userEmail, out displayCode);
                  if (status == false)
                  {                     
                      ResponseMessage responseMessageFail = new ResponseMessage();
                      responseMessageFail.StatusCode = HttpStatusCode.Ambiguous;
                      responseMessageFail.StatusMessage = "Ambiguous";
                      responseMessageFail.Message = Convert.ToString(ConfigurationManager.AppSettings["EnvelopeFail"].ToString());
                      responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessageFail);
                      return responseToClient;
                  }
                }
                ResponseMessageWithEnvID responseMessageSuccess = new ResponseMessageWithEnvID();
                responseMessageSuccess.StatusCode = HttpStatusCode.OK;
                responseMessageSuccess.StatusMessage = "OK";
                responseMessageSuccess.EnvId = displayCode;
                responseMessageSuccess.Message = Convert.ToString(ConfigurationManager.AppSettings["EnvelopeSucess"].ToString());
                responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessageSuccess);
                return responseToClient;
            }
            catch (Exception ex)
            {                
                responseToClient = Request.CreateResponse((HttpStatusCode)422);
                responseToClient.Content = new StringContent(Convert.ToString(ConfigurationManager.AppSettings["EnvelopeFail"].ToString()), Encoding.Unicode);
                throw new HttpResponseException(responseToClient);
            }
        }
        public async Task <ResponseMessage <string> > ModifySimpleContract(UserInfo User, [FromBody] ContractContentInfoRequest request)
        {
            Logger.Trace($"用户{User?.UserName ?? ""}({User?.Id ?? ""})保存合同基础信息(PutBuildingBaseInfo):\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));

            var response = new ResponseMessage <string>();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                return(response);
            }

            try
            {
                //写发送成功后的表
                var guid = Guid.NewGuid().ToString();

                //审核提交
                GatewayInterface.Dto.ExamineSubmitRequest exarequest = new GatewayInterface.Dto.ExamineSubmitRequest();
                exarequest.ContentId      = request.BaseInfo.ID;
                exarequest.ContentType    = "ContractCommit";
                exarequest.ContentName    = "Modify";
                exarequest.SubmitDefineId = guid;
                exarequest.Source         = "";
                exarequest.CallbackUrl    = "";
                exarequest.Action         = "TEST" /*"TEST" exarequest.ContentType*/;
                exarequest.TaskName       = $"{User.UserName}修改合同{exarequest.ContentName}的动态{exarequest.ContentType}";

                GatewayInterface.Dto.UserInfo userinfo = new GatewayInterface.Dto.UserInfo()
                {
                    Id               = User.Id,
                    KeyWord          = User.KeyWord,
                    OrganizationId   = User.OrganizationId,
                    OrganizationName = User.OrganizationName,
                    UserName         = User.UserName
                };

                var examineInterface = ApplicationContext.Current.Provider.GetRequiredService <IExamineInterface>();
                var reponse          = await examineInterface.Submit(userinfo, exarequest);

                if (reponse.Code != ResponseCodeDefines.SuccessCode)
                {
                    response.Code    = ResponseCodeDefines.ServiceError;
                    response.Message = "向审核中心发起审核请求失败:" + reponse.Message;
                    return(response);
                }

                Logger.Trace($"{exarequest.ContentId}发生审核成功");
                request.BaseInfo.Num = string.IsNullOrEmpty(request.BaseInfo.Num) ? await _contractInfoManager.GetContractNum(request.BaseInfo.ID, HttpContext.RequestAborted) : request.BaseInfo.Num;

                await _contractInfoManager.ModifyContractBeforCheckAsync(User, request, guid, "TEST", HttpContext.RequestAborted);


                response.Extension = guid;
                response.Message   = "modify simple ok";
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.ToString();
                Logger.Error($"用户{User?.UserName ?? ""}({User?.Id ?? ""})合同动态提交审核(UpdateRecordSubmit)报错:\r\n{e.ToString()},\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));
            }

            return(response);
        }
        public async Task <ResponseMessage> SubmitContractCallback([FromBody] ExamineResponse examineResponse)
        {
            Logger.Trace($"合同提交审核中心回调(SubmitContractCallback):\r\n请求参数为:\r\n" + (examineResponse != null ? JsonHelper.ToJson(examineResponse) : ""));

            ResponseMessage response = new ResponseMessage();

            if (examineResponse == null)
            {
                response.Code = ResponseCodeDefines.ModelStateInvalid;
                Logger.Trace($"合同提交审核中心回调(SubmitContractCallback)模型验证失败:\r\n{response.Message ?? ""},\r\n请求参数为:\r\n" + (examineResponse != null ? JsonHelper.ToJson(examineResponse) : ""));
                return(response);
            }
            try
            {
                var building = await _contractInfoManager.FindByIdAsync(examineResponse.ContentId);

                response.Code = ResponseCodeDefines.SuccessCode;
                if (building == null)
                {
                    response.Code    = ResponseCodeDefines.NotFound;
                    response.Message = "合同不存在:" + examineResponse.ContentId;
                    Logger.Trace($"合同提交审核中心回调(SubmitBuildingCallback)失败:合同不存在,\r\n请求参数为:\r\n" + (examineResponse != null ? JsonHelper.ToJson(examineResponse) : ""));
                    return(response);
                }

                if (examineResponse.ExamineStatus == ExamineStatus.Examined)
                {
                    var modifyre = await _contractInfoManager.OperModifyInfoAsync(examineResponse.SubmitDefineId, examineResponse.ContentId, ExamineStatusEnum.Approved);

                    if (modifyre.Type == ContractInfoManager.ModifyContract)
                    {
                        await _contractInfoManager.ModifyContractAfterCheckAsync(modifyre.ID, modifyre.ContractID, modifyre.Ext1, ExamineStatusEnum.Approved);
                    }
                    else if (modifyre.Type == ContractInfoManager.AddAnnexContract)
                    {
                        List <FileInfoRequest> fileInfoRequests = JsonHelper.ToObject <List <FileInfoRequest> >(modifyre.Ext1);
                        List <string>          deleteList       = JsonHelper.ToObject <List <string> >(modifyre.Ext5);
                        //List<NWF> listnf = JsonHelper.ToObject<List<NWF>>(modifyre.Ext2);
                        UserInfo user = JsonHelper.ToObject <UserInfo>(modifyre.Ext3);
                        List <FileInfoCallbackRequest> filCallBackReq = new List <FileInfoCallbackRequest>();

                        int nindex = 0;
                        foreach (var item in fileInfoRequests)
                        {
                            try
                            {
                                //NameValueCollection nameValueCollection = new NameValueCollection();
                                //nameValueCollection.Add("appToken", "app:nwf");
                                //Logger.Info("nwf协议");
                                //string response2 = await _restClient.Post(ApplicationContext.Current.NWFUrl, listnf.ElementAt(nindex++), "POST", nameValueCollection);
                                //Logger.Info("返回:\r\n{0}", response2);


                                await _fileScopeManager.CreateAsync(user, modifyre.Ext4, modifyre.ContractID, modifyre.ID, item);

                                //response.Message = response2;
                            }
                            catch (Exception e)
                            {
                                response.Code     = ResponseCodeDefines.PartialFailure;
                                response.Message += $"文件:{item.FileGuid}处理出错,错误信息:{e.ToString()}。\r\n";
                                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})批量上传文件信息(UploadFiles)报错:\r\n{e.ToString()},请求参数为:\r\n,(dest){modifyre.Ext4 ?? ""},(contractId){ modifyre.ContractID ?? ""}," + (fileInfoRequests != null ? JsonHelper.ToJson(fileInfoRequests) : ""));
                            }
                        }
                        try
                        {
                            await _fileInfoManager.CreateListAsync(user.Id, fileInfoRequests, HttpContext.RequestAborted);

                            await _fileScopeManager.DeleteContractFileListAsync(user.Id, modifyre.ContractID, deleteList, HttpContext.RequestAborted);
                        }
                        catch (Exception e)
                        {
                            response.Code    = ResponseCodeDefines.ServiceError;
                            response.Message = e.ToString();
                            Logger.Trace($"合同文件添加或删除失败,审核中心回调(SubmitBuildingCallback)报错:\r\n{e.ToString()},\r\n请求参数为:\r\n" + fileInfoRequests != null ? JsonHelper.ToJson(fileInfoRequests) : "\r\n" + deleteList != null ? JsonHelper.ToJson(deleteList) : "");
                        }
                    }
                    else if (modifyre.Type == ContractInfoManager.UpdateComplementContract)
                    {
                        UserInfo User = JsonHelper.ToObject <UserInfo>(modifyre.Ext1);
                        List <ContractComplementRequest> request = JsonHelper.ToObject <List <ContractComplementRequest> >(modifyre.Ext2);
                        await _contractInfoManager.AddComplementAsync(User, modifyre.ContractID, modifyre.ID, "TEST", request);
                    }
                }
                else if (examineResponse.ExamineStatus == ExamineStatus.Reject)
                {
                    await _contractInfoManager.SubmitAsync(examineResponse.SubmitDefineId, ExamineStatusEnum.Reject);
                }
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.ToString();
                Logger.Trace($"合同提交审核中心回调(SubmitBuildingCallback)报错:\r\n{e.ToString()},\r\n请求参数为:\r\n" + examineResponse != null ? JsonHelper.ToJson(examineResponse) : "");
            }
            return(response);
        }
Пример #36
0
 protected abstract Task SendResponse(ResponseMessage message);
        public async Task <ResponseMessage <bool> > AddComplementContract(UserInfo User, [FromBody] List <ContractComplementRequest> request, [FromRoute] string contract)
        {
            Logger.Trace($"用户{User?.UserName ?? ""}({User?.Id ?? ""})添加补充协议基础信息(PutBuildingBaseInfo):\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));

            var response = new ResponseMessage <bool>();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                return(response);
            }

            try
            {
                string strModifyGuid = Guid.NewGuid().ToString();

                GatewayInterface.Dto.ExamineSubmitRequest exarequest = new GatewayInterface.Dto.ExamineSubmitRequest();
                exarequest.ContentId      = contract;
                exarequest.ContentType    = "ContractCommit";
                exarequest.ContentName    = "AddComplement";
                exarequest.SubmitDefineId = strModifyGuid;
                exarequest.Source         = "";
                exarequest.CallbackUrl    = "";
                exarequest.Action         = "TEST"; /* exarequest.ContentType*/;
                exarequest.TaskName       = $"{User.UserName}添加合同补充协议{exarequest.ContentName}的动态{exarequest.ContentType}";

                GatewayInterface.Dto.UserInfo userinfo = new GatewayInterface.Dto.UserInfo()
                {
                    Id               = User.Id,
                    KeyWord          = User.KeyWord,
                    OrganizationId   = User.OrganizationId,
                    OrganizationName = User.OrganizationName,
                    UserName         = User.UserName
                };

                var examineInterface = ApplicationContext.Current.Provider.GetRequiredService <IExamineInterface>();
                var reponse          = await examineInterface.Submit(userinfo, exarequest);

                if (reponse.Code != ResponseCodeDefines.SuccessCode)
                {
                    response.Code    = ResponseCodeDefines.ServiceError;
                    response.Message = "向审核中心发起审核请求失败:" + reponse.Message;
                    return(response);
                }

                //写发送成功后的表
                //response.Extension = await _contractInfoManager.AddComplementAsync(User, contract, strModifyGuid, "TEST", request, HttpContext.RequestAborted);
                await _contractInfoManager.CreateComplementModifyAsync(User, contract, strModifyGuid, "TEST", JsonHelper.ToJson(User), JsonHelper.ToJson(request), HttpContext.RequestAborted);

                response.Message = "addcomplement ok";
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.ToString();
                Logger.Error($"用户{User?.UserName ?? ""}({User?.Id ?? ""})合同动态提交审核(UpdateRecordSubmit)报错:\r\n{e.ToString()},\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));
            }

            return(response);
        }
Пример #38
0
        public async Task ChangeFeedIteratorCore_FromV2SDK()
        {
            int expected = 100;
            int count    = 0;

            await this.CreateRandomItems(this.LargerContainer, expected, randomPartitionKey : true);

            IReadOnlyList <FeedRange> feedRanges = await this.LargerContainer.GetFeedRangesAsync();

            List <string> continuations = new List <string>();

            // First do one request to construct the old model information based on Etag
            foreach (FeedRange feedRange in feedRanges)
            {
                ChangeFeedRequestOptions requestOptions = new ChangeFeedRequestOptions()
                {
                    StartTime = DateTime.MinValue.ToUniversalTime(), MaxItemCount = 1
                };
                ChangeFeedIteratorCore feedIterator  = this.LargerContainer.GetChangeFeedStreamIterator(feedRange: feedRange, changeFeedRequestOptions: requestOptions) as ChangeFeedIteratorCore;
                ResponseMessage        firstResponse = await feedIterator.ReadNextAsync();

                if (firstResponse.IsSuccessStatusCode)
                {
                    Collection <ToDoActivity> response = TestCommon.SerializerCore.FromStream <CosmosFeedResponseUtil <ToDoActivity> >(firstResponse.Content).Data;
                    count += response.Count;
                }

                // Construct the continuation's range, FeedRange.ToString() = [min,max)
                string         range     = feedRange.ToString();
                int            separator = range.IndexOf(',');
                string         min       = range.Substring(1, separator - 1);
                string         max       = range.Substring(separator + 1, range.IndexOf(')') - separator - 1);
                dynamic        ctRange   = new { min = min, max = max };
                List <dynamic> ct        = new List <dynamic>()
                {
                    new { min = min, max = max, token = firstResponse.Headers.ETag, range = ctRange }
                };
                // Extract Etag and manually construct the continuation
                dynamic oldContinuation = new { V = 0, Range = ctRange, Continuation = ct };
                continuations.Add(JsonConvert.SerializeObject(oldContinuation));
            }

            // Now start the new iterators with the constructed continuations from migration
            foreach (string continuation in continuations)
            {
                ChangeFeedRequestOptions requestOptions = new ChangeFeedRequestOptions()
                {
                    MaxItemCount = 100
                };
                ChangeFeedIteratorCore feedIterator  = this.LargerContainer.GetChangeFeedStreamIterator(continuationToken: continuation, changeFeedRequestOptions: requestOptions) as ChangeFeedIteratorCore;
                ResponseMessage        firstResponse = await feedIterator.ReadNextAsync();

                if (firstResponse.IsSuccessStatusCode)
                {
                    Collection <ToDoActivity> response = TestCommon.SerializerCore.FromStream <CosmosFeedResponseUtil <ToDoActivity> >(firstResponse.Content).Data;
                    count += response.Count;
                }
            }

            Assert.AreEqual(expected, count);
        }
Пример #39
0
        public async Task ShouldContinueUntilResponseOk()
        {
            // Setting 3 ranges, first one returns a 304, second returns Ok
            MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient();
            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration());
            mockContext.Setup(x => x.DocumentClient).Returns(documentClient);
            mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer);
            mockContext.Setup(x => x.Client).Returns(client);
            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(new Uri("/dbs/test/colls/test", UriKind.Relative));

            ResponseMessage firstResponse = new ResponseMessage(HttpStatusCode.NotModified);

            firstResponse.Headers.ETag = "FirstContinuation";
            ResponseMessage secondResponse = new ResponseMessage(HttpStatusCode.OK);

            secondResponse.Headers.ETag = "SecondContinuation";

            mockContext.SetupSequence(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                          It.IsAny <Uri>(),
                                          It.IsAny <Documents.ResourceType>(),
                                          It.IsAny <Documents.OperationType>(),
                                          It.IsAny <RequestOptions>(),
                                          It.IsAny <ContainerInternal>(),
                                          It.IsAny <PartitionKey?>(),
                                          It.IsAny <Stream>(),
                                          It.IsAny <Action <RequestMessage> >(),
                                          It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                          It.IsAny <CosmosDiagnosticsContext>(),
                                          It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(firstResponse))
            .Returns(Task.FromResult(secondResponse));

            DatabaseInternal databaseCore = new DatabaseInlineCore(mockContext.Object, "mydb");

            StandByFeedIteratorCore iterator = new StandByFeedIteratorCore(
                mockContext.Object,
                new ContainerInlineCore(mockContext.Object, databaseCore, "myColl"),
                new ChangeFeedRequestOptions()
            {
                MaxItemCount = 10,
                From         = ChangeFeedRequestOptions.StartFrom.CreateFromBeginning(),
            });
            ResponseMessage firstRequest = await iterator.ReadNextAsync();

            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(firstResponse.Headers.ETag), "Response should contain the first continuation");
            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(secondResponse.Headers.ETag), "Response should contain the second continuation");
            Assert.AreEqual(HttpStatusCode.OK, firstRequest.StatusCode);

            mockContext.Verify(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                   It.IsAny <Uri>(),
                                   It.IsAny <Documents.ResourceType>(),
                                   It.IsAny <Documents.OperationType>(),
                                   It.IsAny <RequestOptions>(),
                                   It.IsAny <ContainerInternal>(),
                                   It.IsAny <PartitionKey?>(),
                                   It.IsAny <Stream>(),
                                   It.IsAny <Action <RequestMessage> >(),
                                   It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                   It.IsAny <CosmosDiagnosticsContext>(),
                                   It.IsAny <CancellationToken>()), Times.Exactly(2));
        }
Пример #40
0
        public async Task ChangeFeedIteratorCore_PartitionKey_ReadAll()
        {
            int totalCount    = 0;
            int firstRunTotal = 25;
            int batchSize     = 25;

            string pkToRead = "pkToRead";
            string otherPK  = "otherPK";

            for (int i = 0; i < batchSize; i++)
            {
                await this.Container.CreateItemAsync(this.CreateRandomToDoActivity(pkToRead));
            }

            for (int i = 0; i < batchSize; i++)
            {
                await this.Container.CreateItemAsync(this.CreateRandomToDoActivity(otherPK));
            }

            ContainerCore          itemsCore    = this.Container;
            ChangeFeedIteratorCore feedIterator = itemsCore.GetChangeFeedStreamIterator(new PartitionKey(pkToRead), changeFeedRequestOptions: new ChangeFeedRequestOptions()
            {
                StartTime = DateTime.MinValue.ToUniversalTime()
            }) as ChangeFeedIteratorCore;
            string continuation = null;

            while (feedIterator.HasMoreResults)
            {
                using (ResponseMessage responseMessage =
                           await feedIterator.ReadNextAsync(this.cancellationToken))
                {
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        Collection <ToDoActivity> response = TestCommon.SerializerCore.FromStream <CosmosFeedResponseUtil <ToDoActivity> >(responseMessage.Content).Data;
                        totalCount += response.Count;
                        foreach (ToDoActivity toDoActivity in response)
                        {
                            Assert.AreEqual(pkToRead, toDoActivity.status);
                        }
                    }

                    continuation = responseMessage.ContinuationToken;
                }
            }

            Assert.AreEqual(firstRunTotal, totalCount);

            int expectedFinalCount = 50;

            // Insert another batch of 25 and use the last FeedToken from the first cycle
            for (int i = 0; i < batchSize; i++)
            {
                await this.Container.CreateItemAsync(this.CreateRandomToDoActivity(pkToRead));
            }

            ChangeFeedIteratorCore setIteratorNew = itemsCore.GetChangeFeedStreamIterator(continuationToken: continuation, changeFeedRequestOptions: new ChangeFeedRequestOptions()
            {
                StartTime = DateTime.MinValue.ToUniversalTime()
            }) as ChangeFeedIteratorCore;

            while (setIteratorNew.HasMoreResults)
            {
                using (ResponseMessage responseMessage =
                           await setIteratorNew.ReadNextAsync(this.cancellationToken))
                {
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        Collection <ToDoActivity> response = TestCommon.SerializerCore.FromStream <CosmosFeedResponseUtil <ToDoActivity> >(responseMessage.Content).Data;
                        totalCount += response.Count;
                        foreach (ToDoActivity toDoActivity in response)
                        {
                            Assert.AreEqual(pkToRead, toDoActivity.status);
                        }
                    }
                }
            }

            Assert.AreEqual(expectedFinalCount, totalCount);
        }
Пример #41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Response"/> class.
 /// </summary>
 /// <param name="responseMessage">
 /// The response.
 /// </param>
 private Response(ResponseMessage responseMessage)
 {
     ResponseMessage = responseMessage;
 }
        public async Task ValidateResponseFactoryJsonSerializer()
        {
            ResponseMessage databaseResponse  = this.CreateResponse();
            ResponseMessage containerResponse = this.CreateResponse();
            ResponseMessage storedProcedureExecuteResponse = this.CreateResponse();
            ResponseMessage storedProcedureResponse        = this.CreateResponse();
            ResponseMessage triggerResponse = this.CreateResponse();
            ResponseMessage udfResponse     = this.CreateResponse();
            ResponseMessage itemResponse    = this.CreateResponse();
            ResponseMessage feedResponse    = this.CreateResponse();

            Mock <CosmosSerializer> mockUserJsonSerializer    = new Mock <CosmosSerializer>();
            Mock <CosmosSerializer> mockDefaultJsonSerializer = new Mock <CosmosSerializer>();
            CosmosResponseFactory   cosmosResponseFactory     = new CosmosResponseFactory(
                defaultJsonSerializer: mockDefaultJsonSerializer.Object,
                userJsonSerializer: mockUserJsonSerializer.Object);

            // Test the user specified response
            mockUserJsonSerializer.Setup(x => x.FromStream <ToDoActivity>(itemResponse.Content)).Returns(new ToDoActivity());
            mockUserJsonSerializer.Setup(x => x.FromStream <ToDoActivity>(storedProcedureExecuteResponse.Content)).Returns(new ToDoActivity());
            mockUserJsonSerializer.Setup(x => x.FromStream <CosmosFeedResponseUtil <ToDoActivity> >(feedResponse.Content)).Returns(new CosmosFeedResponseUtil <ToDoActivity>()
            {
                Data = new Collection <ToDoActivity>()
            });

            // Verify all the user types use the user specified version
            await cosmosResponseFactory.CreateItemResponseAsync <ToDoActivity>(Task.FromResult(itemResponse));

            await cosmosResponseFactory.CreateStoredProcedureExecuteResponseAsync <ToDoActivity>(Task.FromResult(storedProcedureExecuteResponse));

            cosmosResponseFactory.CreateQueryFeedResponse <ToDoActivity>(feedResponse);

            // Throw if the setups were not called
            mockUserJsonSerializer.VerifyAll();

            // Test the system specified response
            ContainerProperties containerSettings = new ContainerProperties("mockId", "/pk");
            DatabaseProperties  databaseSettings  = new DatabaseProperties()
            {
                Id = "mock"
            };

            StoredProcedureProperties cosmosStoredProcedureSettings = new StoredProcedureProperties()
            {
                Id = "mock"
            };

            TriggerProperties cosmosTriggerSettings = new TriggerProperties()
            {
                Id = "mock"
            };

            UserDefinedFunctionProperties cosmosUserDefinedFunctionSettings = new UserDefinedFunctionProperties()
            {
                Id = "mock"
            };

            mockDefaultJsonSerializer.Setup(x => x.FromStream <DatabaseProperties>(databaseResponse.Content)).Returns(databaseSettings);
            mockDefaultJsonSerializer.Setup(x => x.FromStream <ContainerProperties>(containerResponse.Content)).Returns(containerSettings);
            mockDefaultJsonSerializer.Setup(x => x.FromStream <StoredProcedureProperties>(storedProcedureResponse.Content)).Returns(cosmosStoredProcedureSettings);
            mockDefaultJsonSerializer.Setup(x => x.FromStream <TriggerProperties>(triggerResponse.Content)).Returns(cosmosTriggerSettings);
            mockDefaultJsonSerializer.Setup(x => x.FromStream <UserDefinedFunctionProperties>(udfResponse.Content)).Returns(cosmosUserDefinedFunctionSettings);

            Mock <Container> mockContainer = new Mock <Container>();
            Mock <Database>  mockDatabase  = new Mock <Database>();

            // Verify all the system types that should always use default
            await cosmosResponseFactory.CreateContainerResponseAsync(mockContainer.Object, Task.FromResult(containerResponse));

            await cosmosResponseFactory.CreateDatabaseResponseAsync(mockDatabase.Object, Task.FromResult(databaseResponse));

            await cosmosResponseFactory.CreateStoredProcedureResponseAsync(Task.FromResult(storedProcedureResponse));

            await cosmosResponseFactory.CreateTriggerResponseAsync(Task.FromResult(triggerResponse));

            await cosmosResponseFactory.CreateUserDefinedFunctionResponseAsync(Task.FromResult(udfResponse));

            // Throw if the setups were not called
            mockDefaultJsonSerializer.VerifyAll();
        }
        /// <summary>
        /// Processes the directory.
        /// </summary>
        public void ProcessDirectory()
        {
            long elapsedTime = 0;
            //// AuditId auditId = AuditId.PmseSync;
            //// string auditMethodName = "ProcessDirectory";
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

            service.Credentials = new NetworkCredential(Utils.Configuration["Email"], Utils.Configuration["Passcode"]);
            service.Url         = new Uri(Utils.Configuration["ExchangeURI"]);

            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));

            ItemView view = new ItemView(100);
            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

            foreach (Item item in findResults.Items.OrderBy(obj => obj.DateTimeReceived))
            {
                this.stopWatch = new Stopwatch();
                this.stopWatch.Start();
                try
                {
                    item.Load();
                    string replyMessage = string.Empty;
                    bool   signedEmail  = false;
                    if ((item.ItemClass == "IPM.Note.SMIME.MultipartSigned" && item.LastModifiedName == "*****@*****.**") || !Convert.ToBoolean(Utils.Configuration["CheckSignedEmail"]))
                    {
                        if (item.ItemClass == "IPM.Note.SMIME.MultipartSigned")
                        {
                            signedEmail = true;
                        }

                        List <PmseAssignment>      listPD = new List <PmseAssignment>();
                        List <DTTDataAvailability> listDA = new List <DTTDataAvailability>();

                        if (item.HasAttachments)
                        {
                            if (item.Attachments.Count == 1)
                            {
                                foreach (Attachment fileAttachment in item.Attachments)
                                {
                                    FileAttachment attachment = fileAttachment as FileAttachment;
                                    if (item.Subject.ToLower().Contains("unscheduled adjustment") || item.Subject.ToLower().Contains("pmse-wsd"))
                                    {
                                        var filePath = Path.Combine(Utils.GetLocalStorePath(), "Temp_File.csv");
                                        attachment.Load(filePath);
                                        string   fileName = this.ExtractFileNameFromSubject(item.Subject);
                                        bool     result   = false;
                                        string[] fileData = this.ParseSignedWSDFile(filePath, signedEmail);

                                        if (item.Subject.ToLower().Contains("unscheduled adjustment"))
                                        {
                                            result = this.ProcessUnscheduledAdjustments(fileData, fileName, out replyMessage);
                                            this.stopWatch.Stop();
                                            elapsedTime = this.stopWatch.ElapsedMilliseconds;

                                            // File.Delete(filePath);
                                            if (result)
                                            {
                                                this.PmseSyncStatus(Constants.PmseSync, Constants.UnscheduledAdjustmentsTableName, this.stopWatch.Elapsed);
                                            }
                                        }
                                        else
                                        {
                                            result = this.ProcessWSDAssignmentFile(fileData, fileName, out replyMessage);
                                            this.stopWatch.Stop();
                                            elapsedTime = this.stopWatch.ElapsedMilliseconds;

                                            // File.Delete(filePath);
                                            if (result)
                                            {
                                                this.PmseSyncStatus(Constants.PMSEAssignmentsTable, Constants.PMSEAssignmentsTable, this.stopWatch.Elapsed);
                                            }
                                        }

                                        string logMessage = string.Format("File {0} data has been successfully synchronized with WSDB. Synchronization Time:{1}", fileName, this.stopWatch.Elapsed);
                                        this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, logMessage);
                                    }
                                    else
                                    {
                                        replyMessage = Utils.Configuration["mailBodySubjectNotValid"];
                                    }
                                }
                            }
                            else
                            {
                                replyMessage = Utils.Configuration["mailBodyMoreThanOneAttachments"];
                                this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, replyMessage);
                            }
                        }
                        else
                        {
                            replyMessage = Utils.Configuration["mailBodyAttachmentNotFound"];
                            this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, replyMessage);
                        }
                    }
                    else
                    {
                        replyMessage = Utils.Configuration["mailBodyUnsignedMail"];
                    }

                    EmailMessage message = EmailMessage.Bind(service, item.Id);
                    ////bool replyToAll = false;
                    ////ResponseMessage responseMessage = message.CreateReply(replyToAll);
                    ////responseMessage.BodyPrefix = replyMessage;
                    ////responseMessage.CcRecipients.Add(message.From.Address);
                    ////responseMessage.SendAndSaveCopy();
                    bool            replyToAll      = false;
                    ResponseMessage responseMessage = message.CreateReply(replyToAll);
                    responseMessage.ToRecipients.Add(Utils.Configuration["ofcomEmailId"]);
                    responseMessage.BodyPrefix = replyMessage;
                    responseMessage.SendAndSaveCopy();
                    message.IsRead = true;
                    message.Update(ConflictResolutionMode.AutoResolve);
                }
                catch (Exception ex)
                {
                    this.PmseAssignmentLogger.Log(TraceEventType.Error, LoggingMessageId.PmseSyncGenericMessage, "Exception Occured :- " + ex.ToString());
                    continue;
                }
            }

            try
            {
                List <DynamicTableEntity> pmseSyncStatusDetails = this.PmseSync.FetchEntity <DynamicTableEntity>(Utils.GetRegionalTableName(Constants.PmseSyncStatusTableName), new { RowKey = Constants.UnscheduledAdjustmentsTableName });

                if (pmseSyncStatusDetails.Count > 0)
                {
                    // var lastSyncTime = pmseSyncStatusDetails[0].Timestamp.AddMinutes(Utils.Configuration["UnscheduledAdjustmentTimeMin"].ToInt32() + Utils.Configuration["AcceptableDelayInUnscheduledAdjustmentMin"].ToInt32());
                    // if (lastSyncTime < DateTimeOffset.Now)
                    // {
                    //    this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, "Sending mail for unscheduled adjustments");
                    //    EmailMessage message1 = new EmailMessage(service);
                    //    message1.From = Utils.Configuration["Email"];
                    //    message1.ToRecipients.Add(Utils.Configuration["ofcomEmailId"]);
                    //    message1.Subject = Utils.Configuration["mailSubjectUnscheduledMailNotFound"];
                    //    message1.Body = Utils.Configuration["mailBodyUnscheduledMailNotFound"];
                    //    message1.SendAndSaveCopy();
                    //    this.PmseAssignmentLogger.Log(TraceEventType.Information, LoggingMessageId.PmseSyncGenericMessage, "Mail sent for unscheduled adjustments");
                    // }
                }
            }
            catch (Exception ex)
            {
                this.PmseAssignmentLogger.Log(TraceEventType.Error, LoggingMessageId.PmseSyncGenericMessage, string.Format("Some exception occured while sending mail for unscheduled adjustments - {0}", ex.ToString()));
            }
        }
Пример #44
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertSerializes(org.neo4j.bolt.messaging.ResponseMessage msg) throws java.io.IOException
        private void AssertSerializes(ResponseMessage msg)
        {
            assertThat(SerializeAndDeserialize(msg), equalTo(msg));
        }
        public async Task <ResponseMessage <ContractInfoResponse> > AddSimpleContract(UserInfo User, [FromBody] ContractContentInfoRequest request)
        {
            Logger.Trace($"用户{User?.UserName ?? ""}({User?.Id ?? ""})保存合同基础信息(PutBuildingBaseInfo):\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));

            var response = new ResponseMessage <ContractInfoResponse>();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                return(response);
            }

            try
            {
                //写发送成功后的表
                if (!string.IsNullOrEmpty(User.OrganizationId))
                {
                    var resp = await _restClient.Get <ResponseMessage <string> >($"http://localhost:5000/api/Organization/{User.OrganizationId}", null);

                    request.BaseInfo.CreateDepartment = resp.Extension;
                }

                string strModifyGuid = "";
                if (request.Modifyinfo != null && request.Modifyinfo.Count > 0)
                {
                    strModifyGuid = request.Modifyinfo.ElementAt(0).ID;
                }
                else
                {
                    strModifyGuid      = Guid.NewGuid().ToString();
                    request.Modifyinfo = new List <ContractModifyResponse>();
                    request.Modifyinfo.Add(new ContractModifyResponse {
                        ID = strModifyGuid
                    });
                }


                GatewayInterface.Dto.ExamineSubmitRequest exarequest = new GatewayInterface.Dto.ExamineSubmitRequest();
                exarequest.ContentId      = request.BaseInfo.ID;
                exarequest.ContentType    = "ContractCommit";
                exarequest.ContentName    = "AddContract";
                exarequest.SubmitDefineId = strModifyGuid;
                exarequest.Source         = "";
                exarequest.CallbackUrl    = "";
                exarequest.Action         = "TEST"; /* exarequest.ContentType*/;
                exarequest.TaskName       = $"{User.UserName}添加合同{exarequest.ContentName}的动态{exarequest.ContentType}";

                GatewayInterface.Dto.UserInfo userinfo = new GatewayInterface.Dto.UserInfo()
                {
                    Id               = User.Id,
                    KeyWord          = User.KeyWord,
                    OrganizationId   = User.OrganizationId,
                    OrganizationName = User.OrganizationName,
                    UserName         = User.UserName
                };

                var examineInterface = ApplicationContext.Current.Provider.GetRequiredService <IExamineInterface>();
                var reponse          = await examineInterface.Submit(userinfo, exarequest);

                if (reponse.Code != ResponseCodeDefines.SuccessCode)
                {
                    response.Code    = ResponseCodeDefines.ServiceError;
                    response.Message = "向审核中心发起审核请求失败:" + reponse.Message;
                    return(response);
                }
                request.BaseInfo.Num = await _contractInfoManager.GetContractNum(request.BaseInfo.ID, HttpContext.RequestAborted);

                response.Extension = await _contractInfoManager.AddContractAsync(User, strModifyGuid, request, "TEST", HttpContext.RequestAborted);

                response.Message = "add simple ok";
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.ToString();
                Logger.Error($"用户{User?.UserName ?? ""}({User?.Id ?? ""})合同动态提交审核(UpdateRecordSubmit)报错:\r\n{e.ToString()},\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));
            }

            return(response);
        }
        // </ReadItemAsync>

        // <QueryItems>
        private static async Task QueryItems()
        {
            //******************************************************************************************************************
            // 1.4 - Query for items by a property other than Id
            //
            // NOTE: Operations like AsEnumerable(), ToList(), ToArray() will make as many trips to the database
            //       as required to fetch the entire result-set. Even if you set MaxItemCount to a smaller number.
            //       MaxItemCount just controls how many results to fetch each trip.
            //******************************************************************************************************************
            Console.WriteLine("\n1.4 - Querying for a item using its AccountNumber property");

            QueryDefinition query = new QueryDefinition(
                "select * from sales s where s.AccountNumber = @AccountInput ")
                                    .WithParameter("@AccountInput", "Account1");

            FeedIterator <SalesOrder> resultSet = container.GetItemQueryIterator <SalesOrder>(
                query,
                requestOptions: new QueryRequestOptions()
            {
                PartitionKey = new PartitionKey("Account1"),
                MaxItemCount = 1
            });

            List <SalesOrder> allSalesForAccount1 = new List <SalesOrder>();

            while (resultSet.HasMoreResults)
            {
                SalesOrder sale = (await resultSet.ReadNextAsync()).First();
                Console.WriteLine($"\n1.4.1 Account Number: {sale.AccountNumber}; Id: {sale.Id} ");
                allSalesForAccount1.Add(sale);
            }

            Console.WriteLine($"\n1.4.2 Query found {allSalesForAccount1.Count} items.");

            // Use the same query as before but get the cosmos response message to access the stream directly
            FeedIterator streamResultSet = container.GetItemQueryStreamIterator(
                query,
                requestOptions: new QueryRequestOptions()
            {
                PartitionKey   = new PartitionKey("Account1"),
                MaxItemCount   = 10,
                MaxConcurrency = 1
            });

            List <SalesOrder> allSalesForAccount1FromStream = new List <SalesOrder>();

            while (streamResultSet.HasMoreResults)
            {
                using (ResponseMessage responseMessage = await streamResultSet.ReadNextAsync())
                {
                    // Item stream operations do not throw exceptions for better performance
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        dynamic           streamResponse = FromStream <dynamic>(responseMessage.Content);
                        List <SalesOrder> salesOrders    = streamResponse.Documents.ToObject <List <SalesOrder> >();
                        Console.WriteLine($"\n1.4.3 - Item Query via stream {salesOrders.Count}");
                        allSalesForAccount1FromStream.AddRange(salesOrders);
                    }
                    else
                    {
                        Console.WriteLine($"Query item from stream failed. Status code: {responseMessage.StatusCode} Message: {responseMessage.ErrorMessage}");
                    }
                }
            }

            Console.WriteLine($"\n1.4.4 Query found {allSalesForAccount1FromStream.Count} items.");

            if (allSalesForAccount1.Count != allSalesForAccount1FromStream.Count)
            {
                throw new InvalidDataException($"Both query operations should return the same list");
            }
        }
        public async Task <ResponseMessage <ContractContentResponse> > GetContractByid(UserInfo user, [FromRoute] string contractId)
        {
            var Response = new ResponseMessage <ContractContentResponse>();

            if (string.IsNullOrEmpty(contractId))
            {
                Response.Code    = ResponseCodeDefines.ModelStateInvalid;
                Response.Message = "请求参数不正确";
                Logger.Error("error GetContractByid");
                return(Response);
            }
            try
            {
                var ret = await _contractInfoManager.GetAllinfoByIdAsync2(user, contractId, HttpContext.RequestAborted);

                if (ret == null)
                {
                    Response.Code    = ResponseCodeDefines.ModelStateInvalid;
                    Response.Message = "请求合同不存在";
                    Logger.Error("error GetContractByid");
                    return(Response);
                }
                Response.Extension = ret;

                foreach (var item in ret.Modifyinfo)
                {
                    if (item.ID == ret.BaseInfo.CurrentModify)
                    {
                        ret.BaseInfo.ExamineStatus = (int)item.ExamineStatus;
                        break;
                    }
                }
                foreach (var itm in ret.AnnexInfo)
                {
                    int annextype = int.Parse(itm.Group);
                    if (annextype == 1)
                    {
                        ret.BaseInfo.IsSubmmitContractScan = true;
                    }
                    else if (annextype == 2)
                    {
                        ret.BaseInfo.IsSubmmitContractAnnex = true;
                    }
                    else if (annextype == 3)
                    {
                        ret.BaseInfo.IsSubmmitRelation = true;
                    }
                    else if (annextype == 4)
                    {
                        ret.BaseInfo.IsSubmmitNet = true;
                    }
                }
                if (!string.IsNullOrEmpty(Response.Extension.BaseInfo.CreateUser))
                {
                    var resp = await _restClient.Get <ResponseMessage <string> >($"http://localhost:5000/api/user/{Response.Extension.BaseInfo.CreateUser}", null);

                    Response.Extension.BaseInfo.CreateUserName = resp.Extension;
                }
                List <FileInfo>         fileInfos = new List <FileInfo>();
                List <FileItemResponse> fileItems = new List <FileItemResponse>();
                fileInfos = await _fileScopeManager.FindByContractIdAsync(user.Id, contractId);

                if (fileInfos.Count() > 0)
                {
                    var f = fileInfos.Select(a => a.FileGuid).Distinct();
                    foreach (var item in f)
                    {
                        var f1 = fileInfos.Where(a => a.Type != "Attachment" && a.FileGuid == item).ToList();
                        if (f1?.Count > 0)
                        {
                            fileItems.Add(ConvertToFileItem(item, f1));
                        }
                    }
                    Response.Extension.FileList = fileItems;
                }
            }
            catch (Exception e)
            {
                Response.Code    = ResponseCodeDefines.ServiceError;
                Response.Message = "服务器错误:" + e.ToString();
                Logger.Error("error");
            }
            return(Response);
        }
Пример #48
0
        /// <summary>
        /// Shared Mail logic for replying to a mail
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            // ****************** getting the input values ************************
            ExchangeService objExchangeService = ObjExchangeService.Get(context);
            Item            mail           = Mail.Get(context);
            string          body           = Body.Get(context);
            bool            isBodyHTML     = IsBodyHTML.Get(context);
            string          recipientEmail = RecipientEmail.Get(context);
            string          cc             = Cc.Get(context);
            string          bcc            = Bcc.Get(context);
            string          sender         = Sender.Get(context);

            //******** Sending mail Logic ******
            EmailMessage    email          = EmailMessage.Bind(objExchangeService, mail.Id, new PropertySet(ItemSchema.Attachments));
            ResponseMessage forwardMessage = email.CreateForward();

            //Check for if body is a HTML content
            if (isBodyHTML)
            {
                forwardMessage.BodyPrefix = new MessageBody(BodyType.HTML, body);
            }
            else
            {
                forwardMessage.BodyPrefix = body;
            }

            //Adding recipients to mail
            string[] emails = recipientEmail.Split(';');
            foreach (string recipient in emails)
            {
                forwardMessage.ToRecipients.Add(recipient);
            }

            //Adding Cc to mail
            if (cc != null && cc.Length > 0)
            {
                string[] emailsCc = cc.Split(';');
                foreach (string recipient in emailsCc)
                {
                    forwardMessage.CcRecipients.Add(recipient);
                }
            }

            //Adding Bcc to mail
            if (bcc != null && bcc.Length > 0)
            {
                string[] emailsBcc = bcc.Split(';');
                foreach (string recipient in emailsBcc)
                {
                    forwardMessage.BccRecipients.Add(recipient);
                }
            }


            //Forwarding mail
            {
                FolderView view = new FolderView(10000);
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                view.PropertySet.Add(FolderSchema.DisplayName);
                view.Traversal = FolderTraversal.Deep;
                Mailbox            mailbox           = new Mailbox(sender);
                FindFoldersResults findFolderResults = objExchangeService.FindFolders(new FolderId(WellKnownFolderName.MsgFolderRoot, mailbox), view);

                foreach (Folder folder in findFolderResults)
                {
                    if (folder.DisplayName == "Sent Items")
                    {
                        forwardMessage.SendAndSaveCopy(folder.Id);
                    }
                }
            }
        }
        public async Task <ResponseMessage <bool> > AddContract(UserInfo User, [FromBody] ContractInfoRequest request)
        {
            Logger.Trace($"用户{User?.UserName ?? ""}({User?.Id ?? ""})保存合同基础信息(PutBuildingBaseInfo):\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));

            if (User.Id == null)
            {
                {
                    User.Id             = "66df64cb-67c5-4645-904f-704ff92b3e81";
                    User.UserName       = "******";
                    User.KeyWord        = "";
                    User.OrganizationId = "270";
                    User.PhoneNumber    = "18122132334";
                };
            }

            var response = new ResponseMessage <bool>();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                return(response);
            }

            try
            {
                GatewayInterface.Dto.ExamineSubmitRequest exarequest = new GatewayInterface.Dto.ExamineSubmitRequest();
                exarequest.ContentId      = request.ID;
                exarequest.ContentType    = "ContractCommit";
                exarequest.ContentName    = request.Name;
                exarequest.SubmitDefineId = Guid.NewGuid().ToString();
                exarequest.Source         = "";
                exarequest.CallbackUrl    = "";
                exarequest.Action         = "TEST" /*exarequest.ContentType*/;
                exarequest.TaskName       = $"{User.UserName}提交合同{exarequest.ContentName}的动态{exarequest.ContentType}";;
                GatewayInterface.Dto.UserInfo userinfo = new GatewayInterface.Dto.UserInfo()
                {
                    Id               = User.Id,
                    KeyWord          = User.KeyWord,
                    OrganizationId   = User.OrganizationId,
                    OrganizationName = User.OrganizationName,
                    UserName         = User.UserName
                };

                var examineInterface = ApplicationContext.Current.Provider.GetRequiredService <IExamineInterface>();
                var reponse          = await examineInterface.Submit(userinfo, exarequest);

                if (reponse.Code != ResponseCodeDefines.SuccessCode)
                {
                    response.Code    = ResponseCodeDefines.ServiceError;
                    response.Message = "向审核中心发起审核请求失败:" + reponse.Message;
                    return(response);
                }

                //写发送成功后的表
                await _contractInfoManager.CreateAsync(User, request, exarequest.SubmitDefineId, "TEST", HttpContext.RequestAborted);
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.ToString();
                Logger.Error($"用户{User?.UserName ?? ""}({User?.Id ?? ""})合同动态提交审核(UpdateRecordSubmit)报错:\r\n{e.ToString()},\r\n请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));
            }

            return(response);
        }
Пример #50
0
        private async Task ValidateItemStream(
            ItemRequestOptions requestOptions,
            Action <ResponseMessage> ValidateWrite,
            Action <ResponseMessage> ValidateRead)
        {
            ToDoActivity item = ToDoActivity.CreateRandomToDoActivity();

            using (ResponseMessage responseMessage = await this.container.CreateItemStreamAsync(
                       TestCommon.SerializerCore.ToStream(item),
                       new PartitionKey(item.status),
                       requestOptions: requestOptions))
            {
                Assert.AreEqual(HttpStatusCode.Created, responseMessage.StatusCode);
                ValidateWrite(responseMessage);
            }

            using (ResponseMessage responseMessage = await this.container.ReadItemStreamAsync(
                       item.id,
                       new PartitionKey(item.status),
                       requestOptions: requestOptions))
            {
                Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode);
                ValidateRead(responseMessage);
            }

            item.cost = 424242.42;
            using (ResponseMessage responseMessage = await this.container.UpsertItemStreamAsync(
                       TestCommon.SerializerCore.ToStream(item),
                       new PartitionKey(item.status),
                       requestOptions: requestOptions))
            {
                Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode);
                ValidateWrite(responseMessage);
            }

            item.cost = 9000.42;
            using (ResponseMessage responseMessage = await this.container.ReplaceItemStreamAsync(
                       TestCommon.SerializerCore.ToStream(item),
                       item.id,
                       new PartitionKey(item.status),
                       requestOptions: requestOptions))
            {
                Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode);
                ValidateWrite(responseMessage);
            }

            item.cost = 1000;
            List <PatchOperation> patch = new List <PatchOperation>()
            {
                PatchOperation.CreateReplaceOperation("/cost", item.cost)
            };

            using (ResponseMessage responseMessage = await this.containerInternal.PatchItemStreamAsync(
                       item.id,
                       new PartitionKey(item.status),
                       patchOperations: patch,
                       requestOptions: requestOptions))
            {
                Assert.AreEqual(HttpStatusCode.OK, responseMessage.StatusCode);
                ValidateWrite(responseMessage);
            }

            using (ResponseMessage responseMessage = await this.container.DeleteItemStreamAsync(
                       item.id,
                       new PartitionKey(item.status),
                       requestOptions: requestOptions))
            {
                Assert.AreEqual(HttpStatusCode.NoContent, responseMessage.StatusCode);
                this.ValidateItemStreamNoContentResponse(responseMessage);
            }
        }
        public virtual async Task <ResponseMessage <ModifyDetailResponse> > GetAllModifyInfoById(UserInfo user, string id)
        {
            ResponseMessage <ModifyDetailResponse> response = new ResponseMessage <ModifyDetailResponse>();

            try
            {
                Logger.Trace($"获取修改信息(getmodifyinfobyid):\r\n请求参数为:\r\n" + id);
                if (string.IsNullOrEmpty(id))
                {
                    response.Code    = ResponseCodeDefines.ModelStateInvalid;
                    response.Message = "请求参数不正确";
                    Logger.Error("error GetModifyInfoById");
                    return(response);
                }
                var modifyInfo = await _contractInfoManager.GetModifyInfo(id, HttpContext.RequestAborted);

                if (modifyInfo == null || string.IsNullOrEmpty(modifyInfo.Ext1))
                {
                    response.Code    = ResponseCodeDefines.ModelStateInvalid;
                    response.Message = "合同信息不存在";
                    Logger.Error("error getcontractmodifybyid");
                    return(response);
                }

                var info = new ModifyDetailResponse();
                info.ID              = modifyInfo.ID;
                info.ContractID      = modifyInfo.ContractID;
                info.ExamineStatus   = modifyInfo.ExamineStatus;
                info.ExamineTime     = modifyInfo.ExamineTime;
                info.Ext1            = modifyInfo.Ext1;
                info.Ext2            = modifyInfo.Ext2;
                info.Ext3            = modifyInfo.Ext3;
                info.Ext4            = modifyInfo.Ext4;
                info.Ext5            = modifyInfo.Ext5;
                info.ModifyCheck     = modifyInfo.ModifyCheck;
                info.ModifyPepole    = modifyInfo.ModifyPepole;
                info.ModifyStartTime = modifyInfo.ModifyStartTime;
                info.Type            = modifyInfo.Type;

                if (info.Type == 1 || info.Type == 2)
                {
                    info.ContractInfo = JsonHelper.ToObject <ContractContentResponse>(modifyInfo.Ext1);
                }
                else if (info.Type == 3)
                {
                    List <FileInfo>         fileInfos        = new List <FileInfo>();
                    List <FileItemResponse> fileItems        = new List <FileItemResponse>();
                    List <FileInfoRequest>  fileInfoRequests = JsonHelper.ToObject <List <FileInfoRequest> >(info.Ext1);
                    fileInfos = await _fileScopeManager.FindByContractIdAsync(user.Id, modifyInfo.ContractID);

                    foreach (var item in fileInfoRequests)
                    {
                        var fileInfo = new FileInfo();


                        fileInfo.Driver   = item.WXPath.Substring(0, 1);
                        fileInfo.Uri      = CovertPath(item.WXPath);
                        fileInfo.Type     = "ICON";
                        fileInfo.Name     = item.Name;
                        fileInfo.FileGuid = item.FileGuid;
                        fileInfo.Group    = item.Group;


                        fileInfos.Add(fileInfo);
                    }


                    if (fileInfos.Count() > 0)
                    {
                        var f = fileInfos.Select(a => a.FileGuid).Distinct();
                        foreach (var item in f)
                        {
                            var f1 = fileInfos.Where(a => a.Type != "Attachment" && a.FileGuid == item).ToList();
                            if (f1?.Count > 0)
                            {
                                fileItems.Add(ConvertToFileItem(item, f1));
                            }
                        }

                        info.FileList = fileItems;
                    }
                }
                else if (info.Type == 4)
                {
                    info.ComplementInfo = JsonHelper.ToObject <List <ContractComplementResponse> >(modifyInfo.Ext1);
                }
                response.Extension = info;
                response.Code      = "0";
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.ToString();
                Logger.Trace($"获取修改信息(GetAllModifyInfoById):\r\n请求参数为:\r\n" + id);
            }
            return(response);
        }
        public static void AddError <T>(this ResponseMessage <T> msg, Exception ex, bool includeStackTrace = false)
        {
            string exceptionMessage = string.Empty;
            string stackTrace       = ex.StackTrace;

            if (ex.InnerException == null)
            {
                exceptionMessage = ex.Message;
            }
            else
            {
                exceptionMessage = ex.InnerException.Message;
                stackTrace      += ex.InnerException.StackTrace;
            }

            if (ex is ValidationException)
            {
                var validationException = (ValidationException)ex;
                msg.Errors.Add(new ResponseError()
                {
                    Code       = validationException.Code,
                    Display    = validationException.UserFriendlyMessage,
                    Data       = validationException.Data,
                    Message    = exceptionMessage,
                    StackTrace = (includeStackTrace ? stackTrace : null)
                });

                if (validationException.ErrorMessages != null)
                {
                    foreach (var errorMessage in validationException.ErrorMessages)
                    {
                        msg.Errors.Add(new ResponseError()
                        {
                            Code    = validationException.Code,
                            Display = validationException.UserFriendlyMessage,
                            Message = errorMessage
                        });
                    }
                }
            }
            else if (ex is BaseException)
            {
                var baseException = (BaseException)ex;
                msg.Errors.Add(new ResponseError()
                {
                    Code       = baseException.Code,
                    Display    = baseException.UserFriendlyMessage,
                    Data       = baseException.Data,
                    Message    = exceptionMessage,
                    StackTrace = (includeStackTrace ? stackTrace : null)
                });
            }
            else
            {
                msg.Errors.Add(new ResponseError()
                {
                    Message    = exceptionMessage,
                    StackTrace = (includeStackTrace ? stackTrace : null)
                });
            }
        }
        public async Task PointOperationDiagnostic(bool disableDiagnostics)
        {
            ItemRequestOptions requestOptions = new ItemRequestOptions();

            if (disableDiagnostics)
            {
                requestOptions.DiagnosticContextFactory = () => EmptyCosmosDiagnosticsContext.Singleton;
            }
            ;

            //Checking point operation diagnostics on typed operations
            ToDoActivity testItem = ToDoActivity.CreateRandomToDoActivity();
            ItemResponse <ToDoActivity> createResponse = await this.Container.CreateItemAsync <ToDoActivity>(
                item : testItem,
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createResponse.Diagnostics,
                disableDiagnostics);

            ItemResponse <ToDoActivity> readResponse = await this.Container.ReadItemAsync <ToDoActivity>(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                readResponse.Diagnostics,
                disableDiagnostics);

            testItem.description = "NewDescription";
            ItemResponse <ToDoActivity> replaceResponse = await this.Container.ReplaceItemAsync <ToDoActivity>(
                item : testItem,
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            Assert.AreEqual(replaceResponse.Resource.description, "NewDescription");

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                replaceResponse.Diagnostics,
                disableDiagnostics);

            ItemResponse <ToDoActivity> deleteResponse = await this.Container.DeleteItemAsync <ToDoActivity>(
                partitionKey : new Cosmos.PartitionKey(testItem.status),
                id : testItem.id,
                requestOptions : requestOptions);

            Assert.IsNotNull(deleteResponse);
            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                deleteResponse.Diagnostics,
                disableDiagnostics);

            //Checking point operation diagnostics on stream operations
            ResponseMessage createStreamResponse = await this.Container.CreateItemStreamAsync(
                partitionKey : new PartitionKey(testItem.status),
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage readStreamResponse = await this.Container.ReadItemStreamAsync(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                readStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage replaceStreamResponse = await this.Container.ReplaceItemStreamAsync(
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                replaceStreamResponse.Diagnostics,
                disableDiagnostics);

            ResponseMessage deleteStreamResponse = await this.Container.DeleteItemStreamAsync(
                id : testItem.id,
                partitionKey : new PartitionKey(testItem.status),
                requestOptions : requestOptions);

            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                deleteStreamResponse.Diagnostics,
                disableDiagnostics);

            // Ensure diagnostics are set even on failed operations
            testItem.description = new string('x', Microsoft.Azure.Documents.Constants.MaxResourceSizeInBytes + 1);
            ResponseMessage createTooBigStreamResponse = await this.Container.CreateItemStreamAsync(
                partitionKey : new PartitionKey(testItem.status),
                streamPayload : TestCommon.SerializerCore.ToStream <ToDoActivity>(testItem),
                requestOptions : requestOptions);

            Assert.IsFalse(createTooBigStreamResponse.IsSuccessStatusCode);
            CosmosDiagnosticsTests.VerifyPointDiagnostics(
                createTooBigStreamResponse.Diagnostics,
                disableDiagnostics);
        }
 public static void AddError <T>(this ResponseMessage <T> msg, ResponseError error)
 {
     msg.Errors.Add(error);
 }
Пример #55
0
        public ResponseMessage GetOrderListByUser(ParameterUserBasic obj)
        {
            string                reply     = string.Empty;
            ResponseMessage       rM        = new ResponseMessage();
            List <AdminOrderInfo> orderList = new List <AdminOrderInfo>();

            try
            {
                TimeZoneInfo timeZoneInfo;
                DateTime     currentDateTime;
                //Set the time zone information to Central Asia Standard Time
                timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Asia Standard Time");
                //Get date and time in US Mountain Standard Time
                currentDateTime = TimeZoneInfo.ConvertTime(DateTime.Now, timeZoneInfo);


                var dt = adminRepository.GetAllOrderList(obj.UserId.Trim(), ref reply);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        AdminOrderInfo orderInfo = new AdminOrderInfo();
                        orderInfo.OrderId       = dr["OrderId"].ToString().Trim();
                        orderInfo.MenuId        = dr["MenuId"].ToString().Trim();
                        orderInfo.CustomerId    = dr["CustomerId"].ToString().Trim();
                        orderInfo.FirstName     = dr["FirstName"].ToString();
                        orderInfo.LastName      = dr["LastName"].ToString();
                        orderInfo.NickName      = dr["NickName"].ToString();
                        orderInfo.BirthDate     = dr["BirthDate"].ToString();
                        orderInfo.Gender        = dr["Gender"].ToString();
                        orderInfo.Email         = dr["Email"].ToString();
                        orderInfo.Phone         = dr["Phone"].ToString();
                        orderInfo.TitleBn       = dr["TitleBn"].ToString().Trim();
                        orderInfo.TitleEn       = dr["TitleEn"].ToString().Trim();
                        orderInfo.DescriptionBn = dr["DescriptionBn"].ToString().Trim();
                        orderInfo.DescriptionEn = dr["DescriptionEn"].ToString().Trim();
                        orderInfo.RegularPrice  = dr["RegularPrice"].ToString().Trim();
                        orderInfo.Discount      = dr["Discount"].ToString().Trim();
                        double price = (Convert.ToDouble(orderInfo.RegularPrice) - (Convert.ToDouble(orderInfo.RegularPrice) * Convert.ToDouble(orderInfo.Discount) / 100));
                        orderInfo.Price        = price.ToString();
                        orderInfo.Image        = dr["Image"].ToString().Trim();
                        orderInfo.OrderTime    = dr["OrderTime"].ToString().Trim();
                        orderInfo.DeleveryDate = dr["DeleveryDate"].ToString().Trim();

                        DateTime orderDate = Convert.ToDateTime(dr["DeleveryDate"].ToString().Trim());
                        if (currentDateTime < orderDate)
                        {
                            orderInfo.IsChangeAble = "Y";
                        }
                        else
                        {
                            orderInfo.IsChangeAble = "N";
                        }

                        orderInfo.DeleveryDayName = dr["DeleveryDayName"].ToString().Trim();
                        orderInfo.Quantity        = dr["Quantity"].ToString().Trim();
                        orderInfo.AddressId       = dr["AddressId"].ToString().Trim();
                        orderInfo.DeleveryAddress = dr["DeleveryAddress"].ToString().Trim();
                        orderInfo.ReceiverName    = dr["ReceiverName"].ToString().Trim();
                        orderInfo.UserRemarks     = dr["UserRemarks"].ToString().Trim();
                        orderInfo.AdminRemarks    = dr["AdminRemarks"].ToString().Trim();
                        orderInfo.OrderStatus     = dr["OrderStatus"].ToString().Trim();
                        orderInfo.UserStatus      = dr["UserStatus"].ToString().Trim();
                        orderList.Add(orderInfo);
                    }
                    rM.MessageCode   = "Y";
                    rM.Message       = "";
                    rM.SystemMessage = reply;
                    rM.Content       = orderList;
                }
                else
                {
                    rM.MessageCode   = "N";
                    rM.Message       = "No order found.";
                    rM.SystemMessage = reply;
                    rM.Content       = orderList;
                }
                return(rM);
            }
            catch (Exception ex)
            {
                rM.MessageCode   = "N";
                rM.Message       = "System Error";
                rM.SystemMessage = ex.Message;
                rM.Content       = orderList;
                return(rM);
            }


            return(rM);
        }
        private async Task <long> ExecuteQueryAndReturnOutputDocumentCount(
            string queryText,
            int expectedItemCount,
            bool disableDiagnostics)
        {
            QueryDefinition sql = null;

            if (queryText != null)
            {
                sql = new QueryDefinition(queryText);
            }

            QueryRequestOptions requestOptions = new QueryRequestOptions()
            {
                MaxItemCount   = 1,
                MaxConcurrency = 1,
            };

            if (disableDiagnostics)
            {
                requestOptions.DiagnosticContextFactory = () => EmptyCosmosDiagnosticsContext.Singleton;
            }
            ;

            // Verify the typed query iterator
            FeedIterator <ToDoActivity> feedIterator = this.Container.GetItemQueryIterator <ToDoActivity>(
                sql,
                requestOptions: requestOptions);

            List <ToDoActivity> results = new List <ToDoActivity>();
            long totalOutDocumentCount  = 0;
            bool isFirst = true;

            while (feedIterator.HasMoreResults)
            {
                FeedResponse <ToDoActivity> response = await feedIterator.ReadNextAsync();

                results.AddRange(response);
                if (queryText == null)
                {
                    CosmosDiagnosticsTests.VerifyPointDiagnostics(
                        response.Diagnostics,
                        disableDiagnostics);
                }
                else
                {
                    VerifyQueryDiagnostics(
                        response.Diagnostics,
                        isFirst,
                        disableDiagnostics);
                }

                isFirst = false;
            }

            Assert.AreEqual(expectedItemCount, results.Count);

            // Verify the stream query iterator
            FeedIterator streamIterator = this.Container.GetItemQueryStreamIterator(
                sql,
                requestOptions: requestOptions);

            List <ToDoActivity> streamResults = new List <ToDoActivity>();
            long streamTotalOutDocumentCount  = 0;

            isFirst = true;
            while (streamIterator.HasMoreResults)
            {
                ResponseMessage response = await streamIterator.ReadNextAsync();

                Collection <ToDoActivity> result = TestCommon.SerializerCore.FromStream <CosmosFeedResponseUtil <ToDoActivity> >(response.Content).Data;
                streamResults.AddRange(result);
                if (queryText == null)
                {
                    CosmosDiagnosticsTests.VerifyPointDiagnostics(
                        response.Diagnostics,
                        disableDiagnostics);
                }
                else
                {
                    VerifyQueryDiagnostics(
                        response.Diagnostics,
                        isFirst,
                        disableDiagnostics);
                }

                isFirst = false;
            }

            Assert.AreEqual(expectedItemCount, streamResults.Count);
            Assert.AreEqual(totalOutDocumentCount, streamTotalOutDocumentCount);

            return(results.Count);
        }
Пример #57
0
        private async Task VerifyItemOperations(
            Cosmos.PartitionKey partitionKey,
            string partitionKeySerialized,
            dynamic testItem,
            ItemRequestOptions requestOptions = null)
        {
            ResponseMessage response            = null;
            HttpStatusCode  httpStatusCode      = HttpStatusCode.OK;
            int             testHandlerHitCount = 0;
            TestHandler     testHandler         = new TestHandler((request, cancellationToken) =>
            {
                Assert.IsTrue(request.RequestUri.OriginalString.StartsWith(@"dbs/testdb/colls/testcontainer"));
                Assert.AreEqual(requestOptions, request.RequestOptions);
                Assert.AreEqual(ResourceType.Document, request.ResourceType);
                Assert.IsNotNull(request.Headers.PartitionKey);
                Assert.AreEqual(partitionKeySerialized, request.Headers.PartitionKey);
                testHandlerHitCount++;
                response         = new ResponseMessage(httpStatusCode, request, errorMessage: null);
                response.Content = request.Content;
                return(Task.FromResult(response));
            });

            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient(
                (builder) => builder.AddCustomHandlers(testHandler));

            Container container = client.GetDatabase("testdb")
                                  .GetContainer("testcontainer");

            ItemResponse <dynamic> itemResponse = await container.CreateItemAsync <dynamic>(
                item : testItem,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.ReadItemAsync <dynamic>(
                partitionKey : partitionKey,
                id : testItem.id,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.UpsertItemAsync <dynamic>(
                item : testItem,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.ReplaceItemAsync <dynamic>(
                id : testItem.id,
                item : testItem,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            itemResponse = await container.DeleteItemAsync <dynamic>(
                partitionKey : partitionKey,
                id : testItem.id,
                requestOptions : requestOptions);

            Assert.IsNotNull(itemResponse);
            Assert.AreEqual(httpStatusCode, itemResponse.StatusCode);

            Assert.AreEqual(5, testHandlerHitCount, "An operation did not make it to the handler");

            using (Stream itemStream = MockCosmosUtil.Serializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.CreateItemStreamAsync(
                           partitionKey: partitionKey,
                           streamPayload: itemStream,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = MockCosmosUtil.Serializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.ReadItemStreamAsync(
                           partitionKey: partitionKey,
                           id: testItem.id,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = MockCosmosUtil.Serializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.UpsertItemStreamAsync(
                           partitionKey: partitionKey,
                           streamPayload: itemStream,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = MockCosmosUtil.Serializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.ReplaceItemStreamAsync(
                           partitionKey: partitionKey,
                           id: testItem.id,
                           streamPayload: itemStream,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            using (Stream itemStream = MockCosmosUtil.Serializer.ToStream <dynamic>(testItem))
            {
                using (ResponseMessage streamResponse = await container.DeleteItemStreamAsync(
                           partitionKey: partitionKey,
                           id: testItem.id,
                           requestOptions: requestOptions))
                {
                    Assert.IsNotNull(streamResponse);
                    Assert.AreEqual(httpStatusCode, streamResponse.StatusCode);
                }
            }

            Assert.AreEqual(10, testHandlerHitCount, "A stream operation did not make it to the handler");
        }
Пример #58
0
 public void StreamFakeMessage(ResponseMessage message)
 {
     throw new NotImplementedException();
 }
        public async Task <ResponseMessage <HumanInfoAdjustmentResponse> > CreateAsync(UserInfo user, HumanInfoAdjustmentRequest humanInfoAdjustmentRequest, CancellationToken cancellationToken = default(CancellationToken))
        {
            ResponseMessage <HumanInfoAdjustmentResponse> response = new ResponseMessage <HumanInfoAdjustmentResponse>();

            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }
            if (humanInfoAdjustmentRequest == null)
            {
                throw new ArgumentNullException(nameof(humanInfoAdjustmentRequest));
            }
            var humaninfo = await _humanInfoStore.GetAsync(a => a.Where(b => b.Id == humanInfoAdjustmentRequest.HumanId && !b.IsDeleted), cancellationToken);

            if (humaninfo == null)
            {
                response.Code    = ResponseCodeDefines.NotFound;
                response.Message = "操作的人事信息未找到";
                return(response);
            }
            var org = await _permissionExpansionManager.GetOrganizationOfPermission(user.Id, "HumanAdjustment");

            if (org == null || org.Count == 0 || !org.Contains(humanInfoAdjustmentRequest.DepartmentId) || !org.Contains(humaninfo.DepartmentId))
            {
                response.Code    = ResponseCodeDefines.NotAllow;
                response.Message = "没有权限";
                return(response);
            }

            if (string.IsNullOrEmpty(humanInfoAdjustmentRequest.Id))
            {
                humanInfoAdjustmentRequest.Id = Guid.NewGuid().ToString();
            }
            var gatwayurl = ApplicationContext.Current.AppGatewayUrl.EndsWith("/") ? ApplicationContext.Current.AppGatewayUrl.TrimEnd('/') : ApplicationContext.Current.AppGatewayUrl;

            GatewayInterface.Dto.ExamineSubmitRequest examineSubmitRequest = new GatewayInterface.Dto.ExamineSubmitRequest();
            examineSubmitRequest.ContentId       = humanInfoAdjustmentRequest.Id;
            examineSubmitRequest.ContentType     = "HumanAdjustment";
            examineSubmitRequest.ContentName     = humaninfo.Name;
            examineSubmitRequest.Content         = "新增员工人事调动信息";
            examineSubmitRequest.Source          = user.FilialeName;
            examineSubmitRequest.SubmitDefineId  = humanInfoAdjustmentRequest.Id;
            examineSubmitRequest.CallbackUrl     = gatwayurl + "/api/humanadjustment/humanadjustmentcallback";
            examineSubmitRequest.StepCallbackUrl = gatwayurl + "/api/humanadjustment/humanadjustmentstepcallback";
            examineSubmitRequest.Action          = "HumanAdjustment";
            examineSubmitRequest.TaskName        = $"新增员工人事调动信息:{humaninfo.Name}";
            examineSubmitRequest.Desc            = $"新增员工人事调动信息";

            GatewayInterface.Dto.UserInfo userInfo = new GatewayInterface.Dto.UserInfo()
            {
                Id               = user.Id,
                KeyWord          = user.KeyWord,
                OrganizationId   = user.OrganizationId,
                OrganizationName = user.OrganizationName,
                UserName         = user.UserName
            };
            examineSubmitRequest.UserInfo = userInfo;

            string tokenUrl         = $"{ApplicationContext.Current.AuthUrl}/connect/token";
            string examineCenterUrl = $"{ApplicationContext.Current.ExamineCenterUrl}";

            Logger.Info($"新增员工人事调动信息提交审核,\r\ntokenUrl:{tokenUrl ?? ""},\r\nexamineCenterUrl:{examineCenterUrl ?? ""},\r\nexamineSubmitRequest:" + (examineSubmitRequest != null ? JsonHelper.ToJson(examineSubmitRequest) : ""));
            var tokenManager = new TokenManager(tokenUrl, ApplicationContext.Current.ClientID, ApplicationContext.Current.ClientSecret);
            var response2    = await tokenManager.Execute(async (token) =>
            {
                return(await _restClient.PostWithToken <ResponseMessage>(examineCenterUrl, examineSubmitRequest, token));
            });

            if (response2.Code != ResponseCodeDefines.SuccessCode)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = "向审核中心发起审核请求失败:" + response2.Message;
                Logger.Info($"新增员工人事调动信息提交审核失败:" + response2.Message);
                return(response);
            }


            response.Extension = _mapper.Map <HumanInfoAdjustmentResponse>(await Store.CreateAsync(user, _mapper.Map <HumanInfoAdjustment>(humanInfoAdjustmentRequest), cancellationToken));
            return(response);
        }
Пример #60
0
        public bool TryFire(RequestMessage request, out ResponseMessage response)
        {
            response = ResponseMessage.Error;
            if (request.Path == null)
            {
                return(false);
            }

            string[] pathSplit = request.Path.Split('/');
            if (pathSplit.Length < 3)
            {
                return(false);
            }

            if (!this.controllerMethods.ContainsKey(pathSplit[1]))
            {
                return(false);
            }

            var data    = this.controllerMethods[pathSplit[1]];
            var actions = data.Methods.Where(m => m.Name.ToLower() == pathSplit[2]);
            //var action = data.Methods.First(m => m.Name.ToLower() == pathSplit[2]);
            //var action = this.GetBodyAction(pathSplit[2], data, request.Body, request.Method);

            //if (action == null) return false;



            //// YOU COULD RETURN NULL IN CONTROLLER AND FAKE TRYFIRE!
            object result = null;

            //var parameters = action.GetParameters();
            //if (parameters.Length > 1 || parameters.Length == 0)
            //{
            //    var objects = new List<object>();
            //    foreach (var parameter in parameters)
            //        objects.Add(null);

            //    result = (action.Invoke(data.ControllerInstance, objects.ToArray()));
            //}


            //if (request.Body is JsonContent && action.GetCustomAttribute<FromJson>() != null)
            //{
            //    var param = (request.Body as JsonContent).GetObject(action.GetParameters().First().ParameterType);
            //    result = (action.Invoke(data.ControllerInstance, new object[] { param }));
            //}

            //if (request.Body is StringContent && action.GetParameters().First().ParameterType == typeof(string))
            //{
            //    result = (action.Invoke(data.ControllerInstance, new object[] { (request.Body as StringContent).Value }));
            //}

            //if (request.Body is FormContent && action.GetParameters().First().ParameterType == typeof(FormContent))
            //    result = (action.Invoke(data.ControllerInstance, new object[] { (request.Body as FormContent) }));


            if (request.Body == null)
            {
                if (request.QueryParams.Count > 0)
                {
                    foreach (var queryAction in actions)
                    {
                        var args = queryAction.GetParameters();
                        if (queryAction.GetCustomAttribute <FromQuery>() != null && args.Length > 0 && args.First().ParameterType == typeof(QueryParams))
                        {
                            var method = queryAction.GetCustomAttribute <FromMethod>();
                            if (method != null && method.Method != request.Method)
                            {
                                continue;
                            }

                            result = queryAction.Invoke(data.ControllerInstance, new object[] { request.QueryParams });
                            if (result != null)
                            {
                                response = (ResponseMessage)this.GetResponse.Invoke(result, new object[] { });
                                return(true);
                            }

                            return(true);
                        }
                    }
                }

                actions = actions.Where(t =>
                {
                    var method = t.GetCustomAttribute <FromMethod>();
                    if (method != null && method.Method != request.Method)
                    {
                        return(false);
                    }

                    return(true);
                });

                if (actions.Count() <= 0)
                {
                    return(false);
                }
                var action = actions.OrderBy(t => t.GetParameters().Length).First();

                var objects = new List <object>();
                foreach (var parameter in action.GetParameters())
                {
                    objects.Add(null);
                }

                result = (action.Invoke(data.ControllerInstance, objects.ToArray()));

                response = (ResponseMessage)this.GetResponse.Invoke(result, new object[] { });
                return(true);
            }

            foreach (var action in actions)
            {
                var method = action.GetCustomAttribute <FromMethod>();
                if (method != null && method.Method != request.Method)
                {
                    continue;
                }

                result = request.Body.GetMvcResult(action, data.ControllerInstance);
                if (result != null)
                {
                    response = (ResponseMessage)this.GetResponse.Invoke(result, new object[] { });
                    return(true);
                }
            }


            //if (result != null)
            //    response = (ResponseMessage)this.GetResponse.Invoke(result, new object[] { });

            return(false);
        }