예제 #1
0
 public Response GetVenueCalendar(string venueId)
 {
     var requestObject = new RequestObject();
     return (Response)requestObject
         .SetUri(Constants.Uri)
         .AppendPath("venue")
         .AppendPath(venueId)
         .AppendPath("calendar.json")
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(Response));
 }
예제 #2
0
 public ResultsPage GetArtistCalendar(string artistId)
 {
     RequestObject requestObject = new RequestObject();
     return (ResultsPage)requestObject
         .SetUri(Constants.Uri)
         .AppendPath("artist")
         .AppendPath(artistId)
         .AppendPath("calendar.json")
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(ResultsPage));
 }
예제 #3
0
 public ResultsPage GetUserPastEvents(string username)
 {
     RequestObject requestObject = new RequestObject();
     return (ResultsPage)requestObject
         .SetUri(Constants.Uri)
         .AppendPath("users")
         .AppendPath(username)
         .AppendPath("gigography.json")
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(ResultsPage));
 }
예제 #4
0
 public ResultsPage GetLocationCalendar(string locationId)
 {
     RequestObject requestObject = new RequestObject();
     return (ResultsPage)requestObject
         .SetUri(Constants.Uri)
         .AppendPath("metro_areas")
         .AppendPath(locationId)
         .AppendPath("calendar.json")
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(ResultsPage));
 }
예제 #5
0
 public ResultsPage SearchLocations(string location)
 {
     RequestObject requestObject = new RequestObject();
     return (ResultsPage)requestObject
         .SetUri(Constants.Uri)
         .AppendPath("search")
         .AppendPath("locations.json")
         .Param("query", location)
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(ResultsPage));
 }
예제 #6
0
 public Response SearchVenue(string venue)
 {
     var requestObject = new RequestObject();
     return (Response)requestObject
         .Get()
         .SetUri(Constants.Uri)
         .AppendPath("search")
         .AppendPath("venues.json")
         .Param("query", venue)
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(Response));
 }
예제 #7
0
 public Response GetTrackedArtistsCalendar(string username)
 {
     var requestObject = new RequestObject();
        return (Response)requestObject
         .Get()
         .SetUri(Constants.Uri)
         .AppendPath("users")
         .AppendPath(username)
         .AppendPath("calendar.json")
         .Param("reason", "tracked_artist")
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(Response));
 }
예제 #8
0
 public Response GetTrackedLocations(string username)
 {
     var requestObject = new RequestObject();
     return (Response)requestObject
         .Get()
         .SetUri(Constants.Uri)
         .AppendPath("users")
         .AppendPath(username)
         .AppendPath("metro_areas")
         .AppendPath("tracked.json")
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(Response));
 }
예제 #9
0
 public Response GetTrackedArtists(string username, int page)
 {
     var requestObject = new RequestObject();
     return (Response)requestObject
         .Get()
         .SetUri(Constants.Uri)
         .AppendPath("users")
         .AppendPath(username)
         .AppendPath("artists")
         .AppendPath("tracked.json")
         .Param("page", page.ToString())
         .Param("apikey", Constants.APIKey)
         .ToResponseEntity(typeof(Response));
 }
 public static void Fetch_Object(Virtusales.Biblio.API.Session Session)
 {
     dbg("Requesting some Data as an object...");
     dynamic Req = Session.NewRequest(Page: "work-editions", Path: "default");
     RequestObject ReqObject = new RequestObject();
     ReqObject.id = WorkID;
     ReturnObject Results = Req.SendObject<RequestObject, ReturnObject>(ReqObject);
     dbg(Req.Response);
     dbg("Got " + Results.editions.Count + " editions and " + Results.products.Count + " products...");
     foreach (KeyValuePair<string,Edition> kvp_loopVariable in Results.editions) {
         KeyValuePair<string,Edition> kvp = kvp_loopVariable;
         Edition edition = kvp.Value;
         dbg(kvp.Key + "...");
         dbg("    " + edition.edition_id + " ... " + edition.edition_ean);
     }
 }
예제 #11
0
 public ResultsPage SearchEvents(long location, string artistName = "", string minDate = "", string maxDate = "")
 {
     RequestObject requestObject = new RequestObject();
     if (location != 0)
     {
         requestObject.Param("location", location.ToString(CultureInfo.InvariantCulture));
     }
     return (ResultsPage)requestObject
         .SetUri(Constants.Uri)
         .AppendPath("events.json")
         .Get()
         .Param("apikey", Constants.APIKey)
         .Param("artist_name", artistName)
         .Param("min_date", minDate)
         .Param("max_date", maxDate)
         .ToResponseEntity(typeof(ResultsPage));
 }
예제 #12
0
 public async Task <ResponseObject <TButtonsModel, bool> > Delete(RequestObject <TButtonsModel> requestObject)
 {
     return(await _service.DeleteAsync(requestObject));
 }
예제 #13
0
 /// <summary>
 /// 添加请求
 /// </summary>
 /// <param name="route">路由</param>
 /// <param name="req">请求对象</param>
 RequestObject pushRequestObject(string route, RequestObject req)
 {
     return(requests[generateKey(route)] = req);
 }
예제 #14
0
        /// <summary>
        /// Analyze customer-engagement tone.
        ///
        /// Use the customer-engagement endpoint to analyze the tone of customer service and customer support
        /// conversations. For each utterance of a conversation, the method reports the most prevalent subset of the
        /// following seven tones: sad, frustrated, satisfied, excited, polite, impolite, and sympathetic.
        ///
        /// If you submit more than 50 utterances, the service returns a warning for the overall content and analyzes
        /// only the first 50 utterances. If you submit a single utterance that contains more than 500 characters, the
        /// service returns an error for that utterance and does not analyze the utterance. The request fails if all
        /// utterances have more than 500 characters. Per the JSON specification, the default character encoding for
        /// JSON content is effectively always UTF-8.
        ///
        /// **See also:** [Using the customer-engagement
        /// endpoint](https://cloud.ibm.com/docs/services/tone-analyzer?topic=tone-analyzer-utco#utco).
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="utterances">An array of `Utterance` objects that provides the input content that the service is
        /// to analyze.</param>
        /// <param name="contentLanguage">The language of the input text for the request: English or French. Regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input
        /// content must match the specified language. Do not submit content that contains both languages. You can use
        /// different languages for **Content-Language** and **Accept-Language**.
        /// * **`2017-09-21`:** Accepts `en` or `fr`.
        /// * **`2016-05-19`:** Accepts only `en`. (optional, default to en)</param>
        /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use
        /// different languages for **Content-Language** and **Accept-Language**. (optional, default to en)</param>
        /// <returns><see cref="UtteranceAnalyses" />UtteranceAnalyses</returns>
        public bool ToneChat(Callback <UtteranceAnalyses> callback, List <Utterance> utterances, string contentLanguage = null, string acceptLanguage = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ToneChat`");
            }
            if (utterances == null)
            {
                throw new ArgumentNullException("`utterances` is required for `ToneChat`");
            }

            RequestObject <UtteranceAnalyses> req = new RequestObject <UtteranceAnalyses>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("tone_analyzer", "V3", "ToneChat"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"]   = VersionDate;
            req.Headers["Content-Type"] = "application/json";
            req.Headers["Accept"]       = "application/json";

            if (!string.IsNullOrEmpty(contentLanguage))
            {
                req.Headers["Content-Language"] = contentLanguage;
            }

            if (!string.IsNullOrEmpty(acceptLanguage))
            {
                req.Headers["Accept-Language"] = acceptLanguage;
            }

            JObject bodyObject = new JObject();

            if (utterances != null && utterances.Count > 0)
            {
                bodyObject["utterances"] = JToken.FromObject(utterances);
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));

            req.OnResponse = OnToneChatResponse;

            RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/tone_chat", GetServiceUrl());

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
        private static void AddTokenizedCardToProfileAndMakePayment()
        {
            Console.WriteLine("Adding Tokenized Card to Profile... ");

            ProfileResponse response = _bambora.Profiles.CreateProfile(
                new Card()
            {
                Name        = "Jane Doe",
                Number      = "5100000010001004",
                ExpiryMonth = "12",
                ExpiryYear  = "18",
                Cvd         = "123"
            },
                new Address()
            {
                Name         = "Jane Doe",
                AddressLine1 = "123 Fake St.",
                City         = "victoria",
                Province     = "bc",
                Country      = "ca",
                PostalCode   = "v9t2g6",
                PhoneNumber  = "12501234567",
                EmailAddress = "*****@*****.**"
            });

            Console.WriteLine("Created profile with ID: " + response.Id);
            Assert.IsNotNull(response);
            Assert.AreEqual("Operation Successful", response.Message);

            PaymentProfile profile = _bambora.Profiles.GetProfile(response.Id);

            // get a legato token representing the credit card
            string url  = "https://web.na.bambora.com/scripts/tokenization/tokens";
            var    data = new {
                number       = "4030000010001234",
                expiry_month = "12",
                expiry_year  = "18",
                cvd          = "123"
            };

            var requestInfo             = new RequestObject(HttpMethod.Post, url, null, data);
            var command                 = new ExecuteWebRequest(requestInfo);
            WebCommandExecuter executer = new WebCommandExecuter();
            var result = executer.ExecuteCommand(command);

            LegatoTokenResponse token = JsonConvert.DeserializeObject <LegatoTokenResponse>(result.Response);

            response = profile.AddCard(_bambora.Profiles, new Token {
                Name = "Jane Doe",
                Code = token.Token,
            });
            Console.WriteLine("Added tokenized card to profile");
            Assert.IsNotNull(response);
            Assert.AreEqual("Operation Successful", response.Message);

            PaymentResponse pResp = _bambora.Payments.MakePayment(new ProfilePaymentRequest {
                Amount         = 7.91M,
                OrderNumber    = getRandomOrderId("profile"),
                PaymentProfile = new PaymentProfileField()
                {
                    CardId       = 2,
                    CustomerCode = response.Id
                }
            });

            Assert.IsNotNull(pResp);

            // delete it so when we create a profile again with the same card we won't get an error
            _bambora.Profiles.DeleteProfile(response.Id);
        }
예제 #16
0
 /// <summary>
 /// 删除T_SM_RolePermissions数据,通过主表主键删除数据
 /// </summary>
 /// <param name="requestObject">响应结果对象</param>
 /// <returns></returns>
 public Task <ResponseObject <int, bool> > DeleteAsync(RequestObject <int> requestObject, int iUserId)
 {
     return(DeleteAsync <int>(requestObject, iUserId));
 }
예제 #17
0
        /// <summary>
        /// 新增T_SM_RolePermissions数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象,包括响应代码,新增操作结果</param>
        /// <param name="iUserId">用户ID</param>
        /// <returns></returns>
        public async Task <ResponseObject <TSMRolePermissionsAddModel, bool> > PostAsync(RequestObject <TSMRolePermissionsAddModel> requestObject, int iUserId)
        {
            var currDb = _db.Instance;

            try
            {
                //如果没有新增数据,返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostDataList.Count < 1)
                {
                    return(ResponseUtil <TSMRolePermissionsAddModel, bool> .FailResult(requestObject, false, "PostDataList不能为null"));
                }
                var userModel = _db.Instance.Queryable <TSMUserAccountDbModel>().Where(p => p.ID == iUserId).First();
                if (userModel == null)
                {
                    return(ResponseUtil <TSMRolePermissionsAddModel, bool> .FailResult(requestObject, false, "未找到该用户"));
                }
                var result = false;
                //获取当前角色所有已有权限,根据提交
                var permissions = currDb.Queryable <TSMRolePermissionsDbModel>()
                                  .Where(p => p.RoleId == requestObject.PostDataList[0].RoleId)
                                  .ToList();
                //新增或修改权限
                foreach (var item in requestObject.PostDataList)
                {
                    //新增或修改
                    var dbCurrItem = permissions.Where(p => p.RoleId == item.RoleId && p.MenuId == item.MenuId).FirstOrDefault();
                    if (dbCurrItem == null)
                    {
                        var dbModel = _mapper.Map <TSMRolePermissionsDbModel>(item);
                        dbModel.CompanyId = (int)userModel.CompanyId;
                        result            = await currDb.Insertable(dbModel).ExecuteCommandIdentityIntoEntityAsync();

                        item.Id = dbModel.Id;
                    }
                    else
                    {
                        result = await currDb.Updateable(_mapper.Map <TSMRolePermissionsDbModel>(item)).UpdateColumns(p => p.ButtonIds)
                                 .Where(p => p.RoleId == item.RoleId && p.MenuId == item.MenuId && p.CompanyId == userModel.CompanyId)
                                 .ExecuteCommandAsync() > 0;

                        item.Id = dbCurrItem.Id;
                    }

                    if (!result)
                    {
                        break;
                    }
                }

                //删除不存在的权限
                if (result)
                {
                    //删除不存在的权限
                    var ids = requestObject.PostDataList.Select(p => p.Id).ToList();
                    result = await currDb.Deleteable <TSMRolePermissionsDbModel>()
                             .Where(p => !ids.Contains(p.Id) && p.RoleId == requestObject.PostDataList[0].RoleId && p.CompanyId == userModel.CompanyId)
                             .ExecuteCommandAsync() >= 0;
                }
                else
                {
                    currDb.RollbackTran();
                    return(ResponseUtil <TSMRolePermissionsAddModel, bool> .FailResult(requestObject, false, "保存权限信息失败!"));
                }

                //返回执行结果
                if (result)
                {
                    return(ResponseUtil <TSMRolePermissionsAddModel, bool> .SuccessResult(requestObject, true));
                }
                return(ResponseUtil <TSMRolePermissionsAddModel, bool> .FailResult(requestObject, false, "新增数据失败!"));
            }
            catch (Exception ex)
            {
                //返回异常结果
                return(ResponseUtil <TSMRolePermissionsAddModel, bool> .FailResult(requestObject, false, ex.Message));
            }
        }
예제 #18
0
 public IHttpActionResult Get([FromUri] RequestObject obj)
 {
     return(Json(HandleRequest(obj)));
 }
        /// <summary>
        /// 获取T_WM_OtherWhMain主表数据数据
        /// </summary>
        /// <param name="requestObject">Get请求参数</param>
        /// <param name="currentUser"></param>
        /// <returns>返回响应结果对象,包括响应代码,查询操作结果</returns>
        public async Task <ResponseObject <TWMOtherWhMainQueryModel, List <TWMOtherWhMainQueryModel> > > GetMainListAsync(RequestObject <TWMOtherWhMainQueryModel> requestObject,
                                                                                                                          CurrentUser currentUser)
        {
            try
            {
                List <TWMOtherWhMainQueryModel> queryData = null; //查询结果集对象
                RefAsync <int> totalNumber = -1;                  //总记录数
                var            query       = _db.Instance.Queryable <TWMOtherWhMainDbModel, TSMUserAccountDbModel, TSMUserAccountDbModel, TSMUserAccountDbModel>(
                    (t, t0, t1, t2) => new object[]
                {
                    JoinType.Left, t.OperatorId == t0.ID,
                    JoinType.Left, t.ReceiptId == t1.ID,
                    JoinType.Left, t.AuditId == t2.ID
                });
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    query.Where(conditionals);
                }
                //排序条件
                if (requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        var exp = SqlSugarUtil.GetOrderByLambda <TWMOtherWhMainDbModel>(item.Column);
                        if (exp == null)
                        {
                            continue;
                        }
                        if (item.Condition.ToLower() != "asc" &&
                            item.Condition.ToLower() != "desc")
                        {
                            continue;
                        }
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }

                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select((t, t0, t1, t2) => new TWMOtherWhMainQueryModel
                    {
                        ID = t.ID,
                        WarehousingType  = t.WarehousingType,
                        WarehousingDate  = t.WarehousingDate,
                        WarehousingOrder = t.WarehousingOrder,
                        AuditStatus      = t.AuditStatus,
                        OperatorId       = t.OperatorId,
                        OperatorName     = t0.AccountName,
                        ReceiptId        = t.ReceiptId,
                        ReceiptName      = t1.AccountName,
                        AuditId          = t.AuditId,
                        AuditName        = t2.AccountName,
                        AuditTime        = t.AuditTime,
                        DeleteFlag       = t.DeleteFlag,
                        Number           = t.Number,
                        Amount           = t.Amount,
                        AllowEdit        = currentUser.UserID == t.OperatorId && t.AuditStatus != 2
                    })
                                .Where(t => t.CompanyId == currentUser.CompanyID && !(bool)t.DeleteFlag)
                                .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select((t, t0, t1, t2) => new TWMOtherWhMainQueryModel
                    {
                        ID = t.ID,
                        WarehousingType  = t.WarehousingType,
                        WarehousingDate  = t.WarehousingDate,
                        WarehousingOrder = t.WarehousingOrder,
                        AuditStatus      = t.AuditStatus,
                        OperatorId       = t.OperatorId,
                        OperatorName     = t0.AccountName,
                        ReceiptId        = t.ReceiptId,
                        ReceiptName      = t1.AccountName,
                        AuditId          = t.AuditId,
                        AuditName        = t2.AccountName,
                        AuditTime        = t.AuditTime,
                        DeleteFlag       = t.DeleteFlag,
                        Number           = t.Number,
                        Amount           = t.Amount,
                        AllowEdit        = currentUser.UserID == t.OperatorId && t.AuditStatus != 2
                    })
                                .Where(t => t.CompanyId == currentUser.CompanyID && !(bool)t.DeleteFlag)
                                .ToListAsync();
                }

                //返回执行结果
                return(ResponseUtil <TWMOtherWhMainQueryModel, List <TWMOtherWhMainQueryModel> > .SuccessResult(requestObject, queryData, totalNumber));
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return(ResponseUtil <TWMOtherWhMainQueryModel, List <TWMOtherWhMainQueryModel> > .FailResult(requestObject, null, ex.Message));
            }
        }
        /// <summary>
        /// 修改T_WM_OtherWhMain数据
        /// </summary>
        /// <param name="requestObject">Put请求参数</param>
        /// <returns>返回响应结果对象,包括响应代码,修改操作结果</returns>
        public async Task <ResponseObject <TWMOtherWhMainEditModel, bool> > PutAsync(RequestObject <TWMOtherWhMainEditModel> requestObject)
        {
            var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例

            try
            {
                if (requestObject.PostData == null)
                {
                    return(ResponseUtil <TWMOtherWhMainEditModel, bool> .FailResult(requestObject, false, "PostData不能为null"));
                }
                if (requestObject.PostData.ChildList == null || requestObject.PostData.ChildList.Count < 1)
                {
                    return(ResponseUtil <TWMOtherWhMainEditModel, bool> .FailResult(requestObject, false, "PostData.ChildList至少包含一条数据"));
                }
                //开启事务
                currDb.BeginTran();
                //修改主表信息
                var mainModel = _mapper.Map <TWMOtherWhMainDbModel>(requestObject.PostData);
                mainModel.Number = requestObject.PostData.ChildList.Sum(p => p.ActualNumber);
                mainModel.Amount = requestObject.PostData.ChildList.Sum(p => p.Amount);
                var mainFlag = await currDb.Updateable(mainModel)
                               .UpdateColumns(p => new
                {
                    p.WarehousingType,
                    p.WarehousingDate,
                    p.Number,
                    p.Amount,
                    p.ReceiptId
                })
                               .ExecuteCommandAsync() > 0;

                /*
                 * 修改明细逻辑
                 * 1.根据主单ID查询现有明细数据
                 * 2.PostData.ChildList中明细ID <= 0的新增
                 * 3.PostData.ChildList中明细ID > 0的修改
                 * 4.删除不在PostData.CihldList中的数据
                 */
                var detailFlag   = true;
                var detailModels = _mapper.Map <List <TWMOtherWhDetailEditModel>,
                                                List <TWMOtherWhDetailDbModel> >(requestObject.PostData.ChildList);
                foreach (var item in detailModels)
                {
                    if (!detailFlag)
                    {
                        break;
                    }
                    item.MainId = mainModel.ID;
                    //新增或修改明细数据
                    detailFlag = item.ID <= 0
                        ? await currDb.Insertable(item).ExecuteCommandIdentityIntoEntityAsync()
                        : await currDb.Updateable(item).ExecuteCommandAsync() > 0;
                }

                //删除明细数据
                if (detailFlag)
                {
                    var detailIds = detailModels.Select(p => p.ID).ToList();
                    detailFlag = currDb.Deleteable <TWMOtherWhDetailDbModel>()
                                 .Where(p => !detailIds.Contains(p.ID) && p.MainId == mainModel.ID)
                                 .ExecuteCommand() >= 0;
                }

                //提交事务
                currDb.CommitTran();
                //返回执行结果
                return(mainFlag && detailFlag
                    ? ResponseUtil <TWMOtherWhMainEditModel, bool> .SuccessResult(requestObject, true)
                    : ResponseUtil <TWMOtherWhMainEditModel, bool> .FailResult(requestObject, false, "修改数据失败!"));
            }
            catch (Exception ex)
            {
                //回滚事务
                currDb.RollbackTran();
                //返回异常结果
                return(ResponseUtil <TWMOtherWhMainEditModel, bool> .FailResult(requestObject, false, ex.Message));
            }
        }
        /// <summary>
        /// 新增T_WM_OtherWhMain数据
        /// </summary>
        /// <param name="requestObject">Post请求参数</param>
        /// <param name="currentUser"></param>
        /// <returns>返回响应结果对象,包括响应代码,新增操作结果</returns>
        public async Task <ResponseObject <TWMOtherWhMainAddModel, TWMOtherWhMainQueryModel> > PostAsync(RequestObject <TWMOtherWhMainAddModel> requestObject, CurrentUser currentUser)
        {
            var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例

            try
            {
                //没有新增数据,返回错误信息
                if (requestObject.PostData == null)
                {
                    return(ResponseUtil <TWMOtherWhMainAddModel, TWMOtherWhMainQueryModel> .FailResult(requestObject, null, "PostData不能为null"));
                }
                //开启事务
                currDb.BeginTran();
                //插入主表数据
                var mapMainModel = _mapper.Map <TWMOtherWhMainDbModel>(requestObject.PostData);
                mapMainModel.OperatorId = currentUser.UserID;
                mapMainModel.CompanyId  = currentUser.CompanyID;
                mapMainModel.Number     = requestObject.PostData.ChildList.Sum(p => p.ActualNumber);
                mapMainModel.Amount     = requestObject.PostData.ChildList.Sum(p => p.Amount);
                var mainId = await currDb.Insertable(mapMainModel).ExecuteReturnIdentityAsync();

                //更新明细表外键ID值
                requestObject.PostData.ChildList.ForEach(p => p.MainId = mainId);
                //插入从表数据
                var mapDetailModelList = _mapper.Map <List <TWMOtherWhDetailAddModel>, List <TWMOtherWhDetailDbModel> >(requestObject.PostData.ChildList);
                var result             = await currDb.Insertable(mapDetailModelList).ExecuteCommandAsync() > 0;

                //提交事务
                currDb.CommitTran();
                TWMOtherWhMainQueryModel returnObject = null;
                if (result)
                {
                    returnObject = await GetMainData(mainId);
                }

                //返回执行结果
                return(result
                    ? ResponseUtil <TWMOtherWhMainAddModel, TWMOtherWhMainQueryModel> .SuccessResult(requestObject, returnObject)
                    : ResponseUtil <TWMOtherWhMainAddModel, TWMOtherWhMainQueryModel> .FailResult(requestObject, null, "新增数据失败!"));
            }
            catch (Exception ex)
            {
                //回滚事务
                currDb.RollbackTran();
                //返回异常结果
                return(ResponseUtil <TWMOtherWhMainAddModel, TWMOtherWhMainQueryModel> .FailResult(requestObject, null, ex.Message));
            }
        }
        /// <summary>
        /// 获取T_WM_OtherWhDetail数据
        /// </summary>
        /// <param name="requestObject">Get请求参数</param>
        /// <returns>返回响应结果对象,包括响应代码,查询操作结果</returns>
        public async Task <ResponseObject <int, List <TWMOtherWhDetailQueryModel> > > GetDetailListAsync(RequestObject <int> requestObject)
        {
            try
            {
                //查询结果集对象
                List <TWMOtherWhDetailQueryModel> queryData = null;
                //总记录数
                RefAsync <int> totalNumber = -1;
                var            query       = _db.Instance.Queryable <TWMOtherWhDetailDbModel, TBMMaterialFileDbModel, TBMDictionaryTypeDbModel
                                                                     , TBMDictionaryDbModel, TBMDictionaryDbModel, TBMDictionaryDbModel>(
                    (t, t0, t1, t2, t3, t4) => new object[]
                {
                    JoinType.Left, t.MaterialId == t0.ID,
                    JoinType.Left, t0.MaterialTypeId == t1.ID,
                    JoinType.Left, t0.ColorId == t2.ID,
                    JoinType.Left, t0.BaseUnitId == t3.ID,
                    JoinType.Left, t0.WarehouseUnitId == t4.ID
                }
                    );

                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select((t, t0, t1, t2, t3, t4) => new TWMOtherWhDetailQueryModel
                    {
                        ID                = t.ID,
                        MainId            = t.MainId,
                        MaterialId        = t.MaterialId,
                        WarehouseId       = t.WarehouseId,
                        BatchNumber       = t.BatchNumber,
                        ShouldNumber      = t.ShouldNumber,
                        ActualNumber      = t.ActualNumber,
                        MaterialCode      = t0.MaterialCode,
                        MaterialName      = t0.MaterialName,
                        MaterialTypeId    = t0.MaterialTypeId,
                        MaterialTypeName  = t1.TypeName,
                        ColorId           = t0.ColorId,
                        ColorName         = t2.DicValue,
                        BaseUnitId        = t0.BaseUnitId,
                        BaseUnitName      = t3.DicValue,
                        WarehouseUnitId   = t0.WarehouseUnitId,
                        WarehouseUnitName = SqlFunc.IsNullOrEmpty(t4.ID) ? t3.DicValue : t4.DicValue,
                        WarehouseRate     = t0.WarehouseRate,
                        Spec              = t0.Spec,
                        UnitPrice         = t.UnitPrice,
                        Amount            = t.Amount,
                        ValidityPeriod    = t.ValidityPeriod,
                    })
                                .Where(t => t.MainId == requestObject.PostData)
                                .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select((t, t0, t1, t2, t3, t4) => new TWMOtherWhDetailQueryModel
                    {
                        ID                = t.ID,
                        MainId            = t.MainId,
                        MaterialId        = t.MaterialId,
                        WarehouseId       = t.WarehouseId,
                        BatchNumber       = t.BatchNumber,
                        ShouldNumber      = t.ShouldNumber,
                        ActualNumber      = t.ActualNumber,
                        MaterialCode      = t0.MaterialCode,
                        MaterialName      = t0.MaterialName,
                        MaterialTypeId    = t0.MaterialTypeId,
                        MaterialTypeName  = t1.TypeName,
                        ColorId           = t0.ColorId,
                        ColorName         = t2.DicValue,
                        BaseUnitId        = t0.BaseUnitId,
                        BaseUnitName      = t3.DicValue,
                        WarehouseUnitId   = t0.WarehouseUnitId,
                        WarehouseUnitName = SqlFunc.IsNullOrEmpty(t4.ID) ? t3.DicValue : t4.DicValue,
                        WarehouseRate     = t0.WarehouseRate,
                        Spec              = t0.Spec,
                        UnitPrice         = t.UnitPrice,
                        Amount            = t.Amount,
                        ValidityPeriod    = t.ValidityPeriod,
                    })
                                .Where(t => t.MainId == requestObject.PostData)
                                .ToListAsync();
                }
                //返回执行结果
                return(ResponseUtil <int, List <TWMOtherWhDetailQueryModel> > .SuccessResult(requestObject, queryData, totalNumber));
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return(ResponseUtil <int, List <TWMOtherWhDetailQueryModel> > .FailResult(requestObject, null, ex.Message));
            }
        }
        /// <summary>
        /// Create a classifier.
        ///
        /// Train a new multi-faceted classifier on the uploaded image data. Create your custom classifier with positive
        /// or negative examples. Include at least two sets of examples, either two positive example files or one
        /// positive and one negative file. You can upload a maximum of 256 MB per call.
        ///
        /// Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier
        /// and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters.
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="name">The name of the new classifier. Encode special characters in UTF-8.</param>
        /// <param name="positiveExamples">A dictionary that contains the value for each classname. The value is a .zip
        /// file of images that depict the visual subject of a class in the new classifier. You can include more than
        /// one positive example file in a call.
        ///
        /// Specify the parameter name by appending `_positive_examples` to the class name. For example,
        /// `goldenretriever_positive_examples` creates the class **goldenretriever**.
        ///
        /// Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels.
        /// The maximum number of images is 10,000 images or 100 MB per .zip file.
        ///
        /// Encode special characters in the file name in UTF-8.</param>
        /// <param name="negativeExamples">A .zip file of images that do not depict the visual subject of any of the
        /// classes of the new classifier. Must contain a minimum of 10 images.
        ///
        /// Encode special characters in the file name in UTF-8. (optional)</param>
        /// <param name="negativeExamplesFilename">The filename for negativeExamples. (optional)</param>
        /// <returns><see cref="Classifier" />Classifier</returns>
        public bool CreateClassifier(Callback <Classifier> callback, string name, Dictionary <string, System.IO.MemoryStream> positiveExamples, System.IO.MemoryStream negativeExamples = null, string negativeExamplesFilename = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `CreateClassifier`");
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("`name` is required for `CreateClassifier`");
            }
            if (positiveExamples == null)
            {
                throw new ArgumentNullException("`positiveExamples` is required for `CreateClassifier`");
            }
            if (positiveExamples.Count == 0)
            {
                throw new ArgumentException("`positiveExamples` must contain at least one dictionary entry");
            }

            RequestObject <Classifier> req = new RequestObject <Classifier>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "CreateClassifier"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            req.Forms = new Dictionary <string, RESTConnector.Form>();
            if (!string.IsNullOrEmpty(name))
            {
                req.Forms["name"] = new RESTConnector.Form(name);
            }
            if (positiveExamples != null && positiveExamples.Count > 0)
            {
                foreach (KeyValuePair <string, System.IO.MemoryStream> entry in positiveExamples)
                {
                    var partName = string.Format("{0}_positive_examples", entry.Key);
                    req.Forms[partName] = new RESTConnector.Form(entry.Value, entry.Key + ".zip", "application/octet-stream");
                }
            }
            if (negativeExamples != null)
            {
                req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamples, negativeExamplesFilename, "application/octet-stream");
            }

            req.OnResponse = OnCreateClassifierResponse;

            RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/classifiers");

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
예제 #24
0
        /// <summary>
        /// 获取T_SM_CompanyApply数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象,包括响应代码,查询操作结果</param>
        /// <returns></returns>
        public async Task <ResponseObject <TSMCompanyApplyQueryModel, List <TSMCompanyApplyQueryModel> > > GetAsync(RequestObject <TSMCompanyApplyQueryModel> requestObject, CurrentUser currentUser)
        {
            try
            {
                List <TSMCompanyApplyQueryModel> queryData = null; //查询结果集对象
                RefAsync <int> totalNumber = -1;                   //总记录数
                var            query       = _db.Instance.Queryable <TSMCompanyApplyDbModel, TSMUserAccountDbModel, TSMUserInfoDbModel>((t, t1, t2) => new object[] {
                    JoinType.Inner, t.AccountId == t1.ID,
                    JoinType.Inner, t1.UserInfoId == t2.ID
                }).Where((t, t1, t2) => t.CompanyId == currentUser.CompanyID);

                var company = _db.Instance.Queryable <TSMCompanyDbModel>().Where(p => p.ID == currentUser.CompanyID).First();

                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    List <IConditionalModel> conditionals = SqlSugarUtil.GetConditionalModels(requestObject.QueryConditions);
                    foreach (ConditionalModel item in conditionals)
                    {
                        if (item.FieldName.ToLower() == "telaccount")
                        {
                            item.FieldName = $"t1.{item.FieldName}";
                        }
                        else
                        {
                            if (item.ConditionalType == ConditionalType.LessThanOrEqual)
                            {
                                item.FieldValue = Convert.ToDateTime(item.FieldValue).AddDays(1).ToString("yyyyMMdd");
                            }
                            item.FieldName = $"t.{item.FieldName}";
                        }
                    }

                    query.Where(conditionals);
                }
                //排序条件
                if (requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    requestObject.OrderByConditions.ForEach(p => query.OrderBy($"{p.Column} {p.Condition}"));
                }

                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
                        (t, t1, t2) => new TSMCompanyApplyQueryModel
                    {
                        Id           = t.Id,
                        AccountId    = t.AccountId,
                        CompanyId    = t.CompanyId,
                        ApplyTime    = t.ApplyTime,
                        ApplyStatus  = t.ApplyStatus,
                        AccountName  = t1.AccountName,
                        TelAccount   = t1.TelAccount,
                        EmailAccount = t1.EmailAccount,
                        CompanyName  = company.CompanyName
                    })
                                .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
                        (t, t1, t2) => new TSMCompanyApplyQueryModel
                    {
                        Id           = t.Id,
                        AccountId    = t.AccountId,
                        CompanyId    = t.CompanyId,
                        ApplyTime    = t.ApplyTime,
                        ApplyStatus  = t.ApplyStatus,
                        AccountName  = t1.AccountName,
                        TelAccount   = t1.TelAccount,
                        EmailAccount = t1.EmailAccount,
                        CompanyName  = company.CompanyName
                    })
                                .ToListAsync();
                }

                //返回执行结果
                return(ResponseUtil <TSMCompanyApplyQueryModel, List <TSMCompanyApplyQueryModel> > .SuccessResult(requestObject, queryData, totalNumber));
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return(ResponseUtil <TSMCompanyApplyQueryModel, List <TSMCompanyApplyQueryModel> > .FailResult(requestObject, null, ex.Message));
            }
        }
예제 #25
0
 /// <summary>
 /// 删除T_SM_CompanyApply数据,通过主表主键删除数据,批量删除
 /// </summary>
 /// <param name="requestObject">响应结果对象</param>
 /// <returns></returns>
 public Task <ResponseObject <int[], bool> > DeleteAsync(RequestObject <int[]> requestObject)
 {
     return(DeleteAsync <int[]>(requestObject));
 }
예제 #26
0
        public string CreateAnalysis([FromBody] RequestObject request)
        {
            SearchConsoleData dataResult = GetSearchConsoleData(request);

            try
            {
                using SqlConnection conn = new SqlConnection(connString.SQLConnection);

                // Output the ID from the newly generated analysis for later use
                var sqlQuery = "INSERT INTO Analyses (Customer, Url, CreatedDate) output INSERTED.Id " +
                               "VALUES (@Customer, @Url, @CreatedDate) ";

                conn.Open();

                using SqlCommand cmd = new SqlCommand(sqlQuery, conn);
                cmd.Parameters.Add("@Customer", SqlDbType.NVarChar).Value     = request.customerName;
                cmd.Parameters.Add("@Url", SqlDbType.NVarChar).Value          = request.siteUrl;
                cmd.Parameters.Add("@CreatedDate", SqlDbType.DateTime2).Value = DateTime.UtcNow;

                var newId = (int)cmd.ExecuteScalar();

                // Datatable for quickly bulk inserting new analysis into DB.
                var table    = new DataTable();
                var idColumn = new DataColumn("Id", typeof(int))
                {
                    DefaultValue = newId
                };

                table.Columns.Add(idColumn);
                table.Columns.Add("DataId", typeof(int));
                table.Columns.Add("Keyword", typeof(string));
                table.Columns.Add("SiteUrl", typeof(string));
                table.Columns.Add("Impressions", typeof(int));
                table.Columns.Add("Clicks", typeof(int));
                table.Columns.Add("CTR", typeof(double));
                table.Columns.Add("Position", typeof(int));
                table.Columns.Add("Category", typeof(string));
                table.Columns.Add("SubCategory1", typeof(string));
                table.Columns.Add("SubCategory2", typeof(string));
                table.Columns.Add("Intent", typeof(string));
                table.Columns.Add("Colour", typeof(string));

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

                // Populate datatable using data fetched from google.
                // Also adds all keywords to seperate list, for splitting later.
                foreach (var data in dataResult.Results)
                {
                    var row = table.NewRow();
                    row["Keyword"]     = data.Keyword;
                    row["SiteUrl"]     = data.Page;
                    row["Clicks"]      = data.Clicks;
                    row["Impressions"] = data.Impressions;
                    row["CTR"]         = data.Ctr;
                    row["Position"]    = data.Position;
                    keywords.AddRange(data.Keyword.Split());

                    table.Rows.Add(row);
                }

                using var bulk            = new SqlBulkCopy(conn);
                bulk.DestinationTableName = "AnalysisData";
                bulk.WriteToServer(table);

                var keywordsTable = new DataTable();
                keywordsTable.Columns.Add("Id", typeof(int));
                var analysisIdColumn = new DataColumn("AnalysisId", typeof(int))
                {
                    DefaultValue = newId
                };

                keywordsTable.Columns.Add(analysisIdColumn);
                keywordsTable.Columns.Add("Keyword", typeof(string));
                keywordsTable.Columns.Add("Count", typeof(int));

                // Remove all keywords length 2 or less, and return only unique keywords.
                var distinctKeywords = keywords.Distinct().ToList();
                distinctKeywords.RemoveAll(word => word.Length <= 2);
                Dictionary <string, int> keywordDictionary = distinctKeywords.ToDictionary(d => d, x => keywords.Count(s => x == s));

                foreach (var keyword in keywordDictionary)
                {
                    var row = keywordsTable.NewRow();
                    row["Keyword"] = keyword.Key;
                    row["Count"]   = keyword.Value;
                    keywordsTable.Rows.Add(row);
                }

                bulk.DestinationTableName = "SplitKeywords";
                bulk.WriteToServer(keywordsTable);

                conn.Close();

                // SQL Server does a bit of formatting on floats/decimals, so we fetch the newly saved data
                // from the database, and serve it directly. Ensures same result every time.
                var responseData = GetAnalysis(conn, newId);

                responseData.NumberOfRows = responseData.Results.Count;
                responseData.AnalysisId   = newId;
                responseData.CustomerName = request.customerName;
                responseData.SiteUrl      = request.siteUrl;

                return(JsonConvert.SerializeObject(responseData));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }

            return(JsonConvert.SerializeObject("No data found"));
        }
예제 #27
0
 public IHttpActionResult Post(RequestObject obj)
 {
     return(Json(HandleRequest(obj)));
 }
예제 #28
0
        /// <summary>
        /// 修改T_SM_RolePermissions数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象,包括响应代码,修改操作结果</param>
        /// <returns></returns>
        public async Task <ResponseObject <TSMRolePermissionsEditModel, bool> > PutAsync(RequestObject <TSMRolePermissionsEditModel> requestObject)
        {
            try
            {
                //执行结果
                var result = false;
                //没有修改信息,返回错误信息
                if (requestObject.PostDataList == null && requestObject.PostData == null)
                {
                    return(ResponseUtil <TSMRolePermissionsEditModel, bool> .FailResult(requestObject, false, "PostData,PostDataList不能都为null"));
                }
                //批量更新优先级高于单记录更新
                if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
                {
                    //批量更新
                    var editList = _mapper.Map <List <TSMRolePermissionsEditModel>, List <TSMRolePermissionsDbModel> >(requestObject.PostDataList);
                    result = await _db.Instance.Updateable(editList).ExecuteCommandAsync() > 0;
                }
                else
                {
                    //单记录更新
                    var editModel = _mapper.Map <TSMRolePermissionsDbModel>(requestObject.PostData);
                    result = await _db.Instance.Updateable(editModel).ExecuteCommandAsync() > 0;
                }

                //返回执行结果
                if (result)
                {
                    return(ResponseUtil <TSMRolePermissionsEditModel, bool> .SuccessResult(requestObject, true));
                }
                return(ResponseUtil <TSMRolePermissionsEditModel, bool> .FailResult(requestObject, false, "修改数据失败!"));
            }
            catch (Exception ex)
            {
                //返回异常结果
                return(ResponseUtil <TSMRolePermissionsEditModel, bool> .FailResult(requestObject, false, ex.Message));
            }
        }
예제 #29
0
 private ResponseObject HandleRequest(RequestObject obj)
 {
     return(RequestHandlerFactory.Instance.GetRequestHandlerByReqest(obj).HandleRequest(obj));
 }
예제 #30
0
        /// <summary>
        /// 获取T_SM_RolePermissions数据
        /// </summary>
        /// <param name="requestObject">返回响应结果对象,包括响应代码,查询操作结果</param>
        /// <returns></returns>
        public async Task <ResponseObject <TSMRolePermissionsQueryModel, List <TSMRolePermissionsQueryModel> > > GetAsync(RequestObject <TSMRolePermissionsQueryModel> requestObject)
        {
            try
            {
                List <TSMRolePermissionsQueryModel> queryData = null; //查询结果集对象
                RefAsync <int> totalNumber = -1;                      //总记录数
                var            query       = _db.Instance.Queryable <TSMRolePermissionsDbModel>();
                //查询条件
                if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0)
                {
                    var expressionList = SqlSugarUtil.GetQueryExpressions(requestObject.QueryConditions);
                    expressionList.ForEach(p => query.Where(p));
                }
                //排序条件
                if (requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0)
                {
                    foreach (var item in requestObject.OrderByConditions)
                    {
                        var exp = SqlSugarUtil.GetOrderByLambda <TSMRolePermissionsDbModel>(item.Column);
                        if (exp == null)
                        {
                            continue;
                        }
                        if (item.Condition.ToLower() != "asc" &&
                            item.Condition.ToLower() != "desc")
                        {
                            continue;
                        }
                        query.OrderBy($"{item.Column} {item.Condition}");
                    }
                }

                //执行查询
                if (requestObject.IsPaging)
                {
                    queryData = await query.Select(
                        (t) => new TSMRolePermissionsQueryModel
                    {
                        Id         = t.Id,
                        CompanyId  = t.CompanyId,
                        RoleId     = t.RoleId,
                        MenuId     = t.MenuId,
                        ButtonIds  = t.ButtonIds,
                        CreateId   = t.CreateId,
                        CreateTime = t.CreateTime,
                    })
                                .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber);
                }
                else
                {
                    queryData = await query.Select(
                        (t) => new TSMRolePermissionsQueryModel
                    {
                        Id         = t.Id,
                        CompanyId  = t.CompanyId,
                        RoleId     = t.RoleId,
                        MenuId     = t.MenuId,
                        ButtonIds  = t.ButtonIds,
                        CreateId   = t.CreateId,
                        CreateTime = t.CreateTime,
                    })
                                .ToListAsync();
                }

                //返回执行结果
                return(ResponseUtil <TSMRolePermissionsQueryModel, List <TSMRolePermissionsQueryModel> > .SuccessResult(requestObject, queryData, totalNumber));
            }
            catch (Exception ex)
            {
                //返回查询异常结果
                return(ResponseUtil <TSMRolePermissionsQueryModel, List <TSMRolePermissionsQueryModel> > .FailResult(requestObject, null, ex.Message));
            }
        }
        public async Task <ResponseObject <DeleteModel, bool> > Delete(RequestObject <DeleteModel> requestObject)
        {
            CurrentUser currentUser = TokenManager.GetCurentUserbyToken(Request.Headers);

            return(await _service.DeleteAsync(requestObject, currentUser));
        }
예제 #32
0
        /// <summary>
        /// Analyze general tone.
        ///
        /// Use the general-purpose endpoint to analyze the tone of your input content. The service analyzes the content
        /// for emotional and language tones. The method always analyzes the tone of the full document; by default, it
        /// also analyzes the tone of each individual sentence of the content.
        ///
        /// You can submit no more than 128 KB of total input content and no more than 1000 individual sentences in
        /// JSON, plain text, or HTML format. The service analyzes the first 1000 sentences for document-level analysis
        /// and only the first 100 sentences for sentence-level analysis.
        ///
        /// Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8; per
        /// the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII
        /// character set). When specifying a content type of plain text or HTML, include the `charset` parameter to
        /// indicate the character encoding of the input text; for example: `Content-Type: text/plain;charset=utf-8`.
        /// For `text/html`, the service removes HTML tags and analyzes only the textual content.
        ///
        /// **See also:** [Using the general-purpose
        /// endpoint](https://cloud.ibm.com/docs/services/tone-analyzer?topic=tone-analyzer-utgpe#utgpe).
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="toneInput">JSON, plain text, or HTML input that contains the content to be analyzed. For JSON
        /// input, provide an object of type `ToneInput`.</param>
        /// <param name="contentType">The type of the input. A character encoding can be specified by including a
        /// `charset` parameter. For example, 'text/plain;charset=utf-8'. (optional)</param>
        /// <param name="sentences">Indicates whether the service is to return an analysis of each individual sentence
        /// in addition to its analysis of the full document. If `true` (the default), the service returns results for
        /// each sentence. (optional, default to true)</param>
        /// <param name="tones">**`2017-09-21`:** Deprecated. The service continues to accept the parameter for
        /// backward-compatibility, but the parameter no longer affects the response.
        ///
        /// **`2016-05-19`:** A comma-separated list of tones for which the service is to return its analysis of the
        /// input; the indicated tones apply both to the full document and to individual sentences of the document. You
        /// can specify one or more of the valid values. Omit the parameter to request results for all three tones.
        /// (optional)</param>
        /// <param name="contentLanguage">The language of the input text for the request: English or French. Regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. The input
        /// content must match the specified language. Do not submit content that contains both languages. You can use
        /// different languages for **Content-Language** and **Accept-Language**.
        /// * **`2017-09-21`:** Accepts `en` or `fr`.
        /// * **`2016-05-19`:** Accepts only `en`. (optional, default to en)</param>
        /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use
        /// different languages for **Content-Language** and **Accept-Language**. (optional, default to en)</param>
        /// <returns><see cref="ToneAnalysis" />ToneAnalysis</returns>
        public bool Tone(Callback <ToneAnalysis> callback, ToneInput toneInput, string contentType = null, bool?sentences = null, List <string> tones = null, string contentLanguage = null, string acceptLanguage = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `Tone`");
            }
            if (toneInput == null)
            {
                throw new ArgumentNullException("`toneInput` is required for `Tone`");
            }

            RequestObject <ToneAnalysis> req = new RequestObject <ToneAnalysis>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("tone_analyzer", "V3", "Tone"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            if (sentences != null)
            {
                req.Parameters["sentences"] = (bool)sentences ? "true" : "false";
            }
            if (tones != null && tones.Count > 0)
            {
                req.Parameters["tones"] = string.Join(",", tones.ToArray());
            }
            req.Headers["Accept"] = "application/json";

            if (!string.IsNullOrEmpty(contentType))
            {
                req.Headers["Content-Type"] = contentType;
            }

            if (!string.IsNullOrEmpty(contentLanguage))
            {
                req.Headers["Content-Language"] = contentLanguage;
            }

            if (!string.IsNullOrEmpty(acceptLanguage))
            {
                req.Headers["Accept-Language"] = acceptLanguage;
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(toneInput));

            req.OnResponse = OnToneResponse;

            RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/tone", GetServiceUrl());

            if (connector == null)
            {
                return(false);
            }

            return(connector.Send(req));
        }
예제 #33
0
 public ResponseObject <string> PostRegister(RequestObject <VerificationInputModel> requestObject)
 {
     return(_verificationService.SendRegisterVerificationCode(requestObject));
 }
        /// <summary>
        /// Get profile as csv.
        ///
        /// Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of
        /// input content, but it requires much less text to produce an accurate profile. The service can analyze text
        /// in Arabic, English, Japanese, Korean, or Spanish. It can return its results in a variety of languages.
        ///
        /// **See also:**
        /// * [Requesting a
        /// profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#input)
        /// * [Providing sufficient
        /// input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient)
        ///
        ///
        /// ### Content types
        ///
        ///  You can provide input content as plain text (`text/plain`), HTML (`text/html`), or JSON
        /// (`application/json`) by specifying the **Content-Type** parameter. The default is `text/plain`.
        /// * Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8.
        /// * Per the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the
        /// ASCII character set).
        ///
        /// When specifying a content type of plain text or HTML, include the `charset` parameter to indicate the
        /// character encoding of the input text; for example, `Content-Type: text/plain;charset=utf-8`.
        ///
        /// **See also:** [Specifying request and response
        /// formats](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#formats)
        ///
        /// ### Accept types
        ///
        ///  You must request a response as JSON (`application/json`) or comma-separated values (`text/csv`) by
        /// specifying the **Accept** parameter. CSV output includes a fixed number of columns. Set the **csv_headers**
        /// parameter to `true` to request optional column headers for CSV output.
        ///
        /// **See also:**
        /// * [Understanding a JSON
        /// profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-output#output)
        /// * [Understanding a CSV
        /// profile](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-outputCSV#outputCSV).
        /// </summary>
        /// <param name="callback">The callback function that is invoked when the operation completes.</param>
        /// <param name="content">A maximum of 20 MB of content to analyze, though the service requires much less text;
        /// for more information, see [Providing sufficient
        /// input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient).
        /// For JSON input, provide an object of type `Content`.</param>
        /// <param name="contentType">The type of the input. For more information, see **Content types** in the method
        /// description. (optional, default to text/plain)</param>
        /// <param name="contentLanguage">The language of the input text for the request: Arabic, English, Japanese,
        /// Korean, or Spanish. Regional variants are treated as their parent language; for example, `en-US` is
        /// interpreted as `en`.
        ///
        /// The effect of the **Content-Language** parameter depends on the **Content-Type** parameter. When
        /// **Content-Type** is `text/plain` or `text/html`, **Content-Language** is the only way to specify the
        /// language. When **Content-Type** is `application/json`, **Content-Language** overrides a language specified
        /// with the `language` parameter of a `ContentItem` object, and content items that specify a different language
        /// are ignored; omit this parameter to base the language on the specification of the content items. You can
        /// specify any combination of languages for **Content-Language** and **Accept-Language**. (optional, default to
        /// en)</param>
        /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional
        /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can specify
        /// any combination of languages for the input and response content. (optional, default to en)</param>
        /// <param name="rawScores">Indicates whether a raw score in addition to a normalized percentile is returned for
        /// each characteristic; raw scores are not compared with a sample population. By default, only normalized
        /// percentiles are returned. (optional, default to false)</param>
        /// <param name="csvHeaders">Indicates whether column labels are returned with a CSV response. By default, no
        /// column labels are returned. Applies only when the response type is CSV (`text/csv`). (optional, default to
        /// false)</param>
        /// <param name="consumptionPreferences">Indicates whether consumption preferences are returned with the
        /// results. By default, no consumption preferences are returned. (optional, default to false)</param>
        /// <returns><see cref="System.IO.MemoryStream" />System.IO.MemoryStream</returns>
        public bool ProfileAsCsv(Callback <System.IO.MemoryStream> callback, Content content, string contentType = null, string contentLanguage = null, string acceptLanguage = null, bool?rawScores = null, bool?csvHeaders = null, bool?consumptionPreferences = null)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("`callback` is required for `ProfileAsCsv`");
            }
            if (content == null)
            {
                throw new ArgumentNullException("`content` is required for `ProfileAsCsv`");
            }

            RequestObject <System.IO.MemoryStream> req = new RequestObject <System.IO.MemoryStream>
            {
                Callback               = callback,
                HttpMethod             = UnityWebRequest.kHttpVerbPOST,
                DisableSslVerification = DisableSslVerification
            };

            foreach (KeyValuePair <string, string> kvp in customRequestHeaders)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            ClearCustomRequestHeaders();

            foreach (KeyValuePair <string, string> kvp in Common.GetSdkHeaders("personality_insights", "V3", "ProfileAsCsv"))
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }

            req.Parameters["version"] = VersionDate;
            if (rawScores != null)
            {
                req.Parameters["raw_scores"] = (bool)rawScores ? "true" : "false";
            }
            if (csvHeaders != null)
            {
                req.Parameters["csv_headers"] = (bool)csvHeaders ? "true" : "false";
            }
            if (consumptionPreferences != null)
            {
                req.Parameters["consumption_preferences"] = (bool)consumptionPreferences ? "true" : "false";
            }
            req.Headers["Accept"] = "text/csv";

            if (!string.IsNullOrEmpty(contentType))
            {
                req.Headers["Content-Type"] = contentType;
            }

            if (!string.IsNullOrEmpty(contentLanguage))
            {
                req.Headers["Content-Language"] = contentLanguage;
            }

            if (!string.IsNullOrEmpty(acceptLanguage))
            {
                req.Headers["Accept-Language"] = acceptLanguage;
            }
            req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content));

            req.OnResponse = OnProfileAsCsvResponse;

            Connector.URL = GetServiceUrl() + "/v3/profile";
            Authenticator.Authenticate(Connector);

            return(Connector.Send(req));
        }
예제 #35
0
 public ResponseObject <string> PostForget(RequestObject <VerificationInputModel> requestObject)
 {
     return(_verificationService.SendForgetVerificationCode(requestObject));
 }
예제 #36
0
        private bool VerifyAadhaarOTP()
        {
            KYCRequest kYCRequest = new KYCRequest();

            kYCRequest.setAuthenticationType(ResidentAuthenticationType.OTP);
            kYCRequest.setDecryptionRequired(false);
            kYCRequest.setLocalLanguageRequired(false);
            kYCRequest.setPrintFormatRequired(false);

            RequestObject request = new RequestObject();

            request.setAadhaarNumber(ADSE.AadhaarNumber);
            request.setVersion("2.5");
            request.setUdc(ConfigurationSettings.AppSettings["UDCCode"].ToString());
            //request.setUdc("ASBD20171013100000");
            request.setTimeStamp(Util.getTimeStamp());
            request.setResidentConsent(true);

            request.setKycRequest(kYCRequest);

            PinValue pv = new PinValue();

            pv.setOtp(ADSE.AadhaarApplicantOTP);

            request.setTransaction(ADSE.AadhaarOTPResponseTransactionID);
            Response.Write("Verifying OTP(var): " + ADSE.AadhaarOTPResponseTransactionID + "\n");
            //request.setTransaction(UUID.randomUUID().toString());
            request.setPinValue(pv);


            KRDHConnectorImpl krdhConnector = new KRDHConnectorImpl();

            ResponseObject response = krdhConnector.requestKYC(request);

            Response.Write("Got Response\n");

            Response.Write(response.getInfo());
            if (response.getStatus().Equals("N"))
            {
                Response.Write("Failed to generate the request.\n");
                Response.Write(response.getError() + "\n");
                Response.Write(response.getErrorMessage() + "\n");
                Response.Write("Var : " + ADSE.AadhaarOTPResponseTransactionID + "\n");
                ADSE.OTPErrorCode    = response.getError();
                ADSE.OTPErrorMessage = response.getErrorMessage();
                WriteErrorLog(ADSE.OTPErrorCode, ADSE.OTPErrorMessage);
                return(false);
            }
            else
            {
                if (response.getResponseStatus().ToLower().Equals("y"))
                {
                    Response.Write(response.getTimeStamp() + "\n");
                    Response.Write(response.getTransaction() + "\n");
                    Response.Write("SUCCESS" + "\n");


                    lblToken.Text = ADSE.AadhaarVaultToken;

                    ADSE.DOB    = response.GetKycRes().UidData.Poi.dob;
                    ADSE.Gender = response.GetKycRes().UidData.Poi.gender;
                    ADSE.Name   = response.GetKycRes().UidData.Poi.name;

                    ADSE.State    = response.GetKycRes().UidData.Poa.state;
                    ADSE.District = response.GetKycRes().UidData.Poa.state;

                    ADSE.Photo   = response.GetKycRes().UidData.Pht;
                    ADSE.Pincode = response.GetKycRes().UidData.Poa.pc;
                    Response.Write("___" + ADSE.Name + "___" + ADSE.DOB + "_" + ADSE.Gender + "_" + ADSE.District + "_" + ADSE.State);
                    //string fileName = Path.Combine(Server.MapPath("C:\inetpub\wwwroot\AadhaarApplicantPhoto"));

                    return(true);
                }
                else
                {
                    Response.Write(response.getError() + "\n");
                    Response.Write(response.getErrorMessage() + "\n");
                    ADSE.OTPErrorCode    = response.getError();
                    ADSE.OTPErrorMessage = response.getErrorMessage();
                    WriteErrorLog(ADSE.OTPErrorCode, ADSE.OTPErrorMessage);

                    return(false);
                }
            }
        }
예제 #37
0
 public ResponseObject <string> PostTimePass(RequestObject <VerificationInputModel> requestObject)
 {
     return(_verificationService.SendTimePassVerificationCode(requestObject));
 }
예제 #38
0
 public async Task <ResponseObject <int, bool> > Delete(RequestObject <int> requestObject)
 {
     return(await _service.DeleteAsync(requestObject));
 }
예제 #39
0
 public ResponseObject <string> PostChangeMobile(RequestObject <VerificationInputModel> requestObject)
 {
     return(_verificationService.SendChangeMobileVerificationCode(requestObject));
 }
        public async Task <ResponseObject <TBMDictionaryTypeEditModel, bool> > Put(RequestObject <TBMDictionaryTypeEditModel> requestObject)
        {
            CurrentUser currentUser = TokenManager.GetCurentUserbyToken(Request.Headers);

            return(await _service.PutAsync(requestObject, currentUser));
        }
예제 #41
0
 /// <summary>
 /// 删除T_SM_CompanyApply数据
 /// </summary>
 /// <param name="requestObject"></param>
 /// <returns></returns>
 public async Task <ResponseObject <TSMCompanyApplyAddModel, bool> > DeleteAsync(RequestObject <TSMCompanyApplyAddModel> requestObject)
 {
     try
     {
         //执行结果
         var result = false;
         //没有删除数据,返回错误信息
         if (requestObject.PostDataList == null && requestObject.PostData == null)
         {
             return(ResponseUtil <TSMCompanyApplyAddModel, bool> .FailResult(requestObject, false, "PostData,PostDataList不能都为null"));
         }
         //批量删除的优先级高于单记录删除
         if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0)
         {
             //批量删除
             var delList = _mapper.Map <List <TSMCompanyApplyAddModel>, List <TSMCompanyApplyDbModel> >(requestObject.PostDataList);
             result = await _db.Instance.Deleteable(delList).ExecuteCommandAsync() > 0;
         }
         else
         {
             //单记录删除
             var delModel = _mapper.Map <TSMCompanyApplyDbModel>(requestObject.PostData);
             result = await _db.Instance.Deleteable(delModel).ExecuteCommandAsync() > 0;
         }
         //返回执行结果
         if (result)
         {
             return(ResponseUtil <TSMCompanyApplyAddModel, bool> .SuccessResult(requestObject, true));
         }
         return(ResponseUtil <TSMCompanyApplyAddModel, bool> .FailResult(requestObject, false, "删除数据失败!"));
     }
     catch (Exception ex)
     {
         //返回异常结果
         return(ResponseUtil <TSMCompanyApplyAddModel, bool> .FailResult(requestObject, false, ex.Message));
     }
 }