Exemplo n.º 1
0
        public static BaiduLicenseRecognition getLicenseRecognition(Newtonsoft.Json.Linq.JObject jObject)
        {
            if (jObject == null)
            {
                return(null);
            }
            BaiduLicenseRecognition license = new BaiduLicenseRecognition();

            Newtonsoft.Json.Linq.JToken jtError = jObject.SelectToken("error_code");
            if (jtError != null)
            {
                license.errorCode = jtError.ToString();
                license.ErrorMsg  = jObject.SelectToken("error_msg").ToString();
                return(license);
            }
            Newtonsoft.Json.Linq.JToken wordsResult = jObject.SelectToken("words_result");
            if (wordsResult != null)
            {
                license.companyName   = wordsResult.SelectToken("单位名称").SelectToken("words").ToString();
                license.expriseDate   = wordsResult.SelectToken("有效期").SelectToken("words").ToString();
                license.licenseNumber = wordsResult.SelectToken("证件编号").SelectToken("words").ToString();
                license.creditNumber  = wordsResult.SelectToken("社会信用代码").SelectToken("words").ToString();
                license.address       = wordsResult.SelectToken("地址").SelectToken("words").ToString();
                license.logalPerson   = wordsResult.SelectToken("法人").SelectToken("words").ToString();
            }
            return(license);
        }
        public async Task <IActionResult> ChangeUserStatus(string id, [FromBody] Newtonsoft.Json.Linq.JObject obj)
        {
            ApplicationUser user = await dbContext.ApplicationUsers.FirstOrDefaultAsync(u => u.Id == id);

            if (user == null)
            {
                return(NotFound(new { Code = "404", Message = "Not Found" }));
            }
            else
            {
                Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();

                if (payload.SelectToken("userStatus") != null &&
                    payload.SelectToken("userStatus").ToString() != string.Empty)
                {
                    string Status = payload.SelectToken("userStatus").ToObject <string>();
                    user.userStatus = Status;
                    dbContext.ApplicationUsers.Update(user);
                }
            }

            var result = await dbContext.SaveChangesAsync();

            if (result > 0)
            {
                return(Ok(new { Code = "200", Message = "User Status Changed" }));
            }
            else
            {
                return(BadRequest(new { Code = "400", Message = "UserStatus field is required" }));
            }
        }
Exemplo n.º 3
0
        public static baiduIDRecogniton getIDRecognition(Newtonsoft.Json.Linq.JObject jObject)
        {
            if (jObject == null)
            {
                return(null);
            }
            baiduIDRecogniton id = new baiduIDRecogniton();

            Newtonsoft.Json.Linq.JToken jtError = jObject.SelectToken("error_code");
            if (jtError != null)
            {
                id.errorCode = jtError.ToString();
                id.ErrorMsg  = jObject.SelectToken("error_msg").ToString();
                return(id);
            }
            Newtonsoft.Json.Linq.JToken wordsResult = jObject.SelectToken("words_result");
            if (wordsResult != null)
            {
                id.name      = wordsResult.SelectToken("姓名").SelectToken("words").ToString();
                id.address   = wordsResult.SelectToken("住址").SelectToken("words").ToString();
                id.birthDate = wordsResult.SelectToken("出生").SelectToken("words").ToString();
                id.IdNumber  = wordsResult.SelectToken("公民身份号码").SelectToken("words").ToString();
                id.sex       = wordsResult.SelectToken("性别").SelectToken("words").ToString();
                id.nation    = wordsResult.SelectToken("民族").SelectToken("words").ToString();
            }
            return(id);
        }
Exemplo n.º 4
0
        public static NIMReceivedMessage Deserialize(Newtonsoft.Json.Linq.JObject obj)
        {
            NIMReceivedMessage msg = new NIMReceivedMessage();
            var resCode            = obj.SelectToken(NIMReceivedMessage.ResCodePath);
            var feature            = obj.SelectToken(NIMReceivedMessage.FeaturePath);
            var token = obj.SelectToken(NIMReceivedMessage.MessageContentPath);

            if (resCode != null)
            {
                msg.ResponseCode = resCode.ToObject <ResponseCode>();
            }
            if (feature != null)
            {
                msg.Feature = feature.ToObject <NIMMessageFeature>();
            }

            if (token != null && token.Type == Newtonsoft.Json.Linq.JTokenType.Object)
            {
                var contentObj = token.ToObject <Newtonsoft.Json.Linq.JObject>();
                msg.TeamPushMsg = TeamForecePushMessage.Deserialize(contentObj);
                var realMsg = MessageFactory.CreateMessage(contentObj);
                msg.MessageContent = realMsg;
            }
            return(msg);
        }
Exemplo n.º 5
0
        public static baiduVehicleRecognition getvehicleRecognition(Newtonsoft.Json.Linq.JObject jObject)
        {
            if (jObject == null)
            {
                return(null);
            }
            baiduVehicleRecognition vehicle = new baiduVehicleRecognition();

            Newtonsoft.Json.Linq.JToken jtError = jObject.SelectToken("error_code");
            if (jtError != null)
            {
                vehicle.errorCode = jtError.ToString();
                vehicle.ErrorMsg  = jObject.SelectToken("error_msg").ToString();
                return(vehicle);
            }
            MyHelper.ConsoleHelper.writeLine(jObject.ToString());
            Newtonsoft.Json.Linq.JToken wordsResult = jObject.SelectToken("words_result");
            if (wordsResult != null)
            {
                vehicle.brand               = wordsResult.SelectToken("品牌型号").SelectToken("words").ToString();
                vehicle.SendTime            = wordsResult.SelectToken("发证日期").SelectToken("words").ToString();
                vehicle.useType             = wordsResult.SelectToken("使用性质").SelectToken("words").ToString();
                vehicle.engineNumber        = wordsResult.SelectToken("发动机号码").SelectToken("words").ToString();
                vehicle.carNumber           = wordsResult.SelectToken("号牌号码").SelectToken("words").ToString();
                vehicle.owner               = wordsResult.SelectToken("所有人").SelectToken("words").ToString();
                vehicle.address             = wordsResult.SelectToken("住址").SelectToken("words").ToString();
                vehicle.registerDate        = wordsResult.SelectToken("注册日期").SelectToken("words").ToString();
                vehicle.carRecongnitionCode = wordsResult.SelectToken("车辆识别代号").SelectToken("words").ToString();
                vehicle.carType             = wordsResult.SelectToken("车辆类型").SelectToken("words").ToString();
            }
            return(vehicle);
        }
Exemplo n.º 6
0
        public static SchemaReference GetSchemaReference(this Newtonsoft.Json.Linq.JObject self, FileModel file, string rootSchema)
        {
            var schema = (string)self.SelectToken("$schema");

            if (!string.IsNullOrEmpty(schema))
            {
                var schemaItem = GetSchemaReference(schema);


                if (schema.ToLower().StartsWith("http://"))
                {
                    schemaItem.SchemaIdKind = SchemaIdKindEnum.Url;
                    if (schemaItem.Kind == KindSchemaEnum.Schema)
                    {
                        schemaItem.Type = (string)self.SelectToken("id");
                        if (schemaItem.Type.ToLower().StartsWith(rootSchema.ToLower()))
                        {
                            var o = schemaItem.Type.Substring(rootSchema.Length).Trim('/').Split('/');
                            if (o[0].ToLower() == "links")
                            {
                                schemaItem.Type = o[1];
                                schemaItem.Kind = KindSchemaEnum.SchemaLink;
                            }
                            else if (o[0].ToLower() == "entities")
                            {
                                schemaItem.Type = o[1];
                                schemaItem.Kind = KindSchemaEnum.SchemaEntity;
                            }
                        }
                    }
                }
                else
                {
                    try
                    {
                        var folderTargetFile = new FileInfo(file.FullPath).Directory.FullName;
                        var _file            = new FileInfo(Path.Combine(folderTargetFile, schema));
                        schemaItem.FilePath            = _file.FullName;
                        schemaItem.SchemaIdKind        = SchemaIdKindEnum.File;
                        schemaItem.IsValidExistingFile = _file.Exists;
                    }
                    catch (Exception)
                    {
                    }
                }

                return(schemaItem);
            }

            return(null);
        }
        public async Task <ActionResult> EditUser(string id, [FromBody] Newtonsoft.Json.Linq.JObject obj)
        {
            Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();

            var account = await userManager.FindByIdAsync(id.ToString());

            if (account != null)
            {
                List <string> errors = ValidateResponseMessagesList(payload);

                if (errors.Count == 0)
                {
                    account.UserName   = payload.SelectToken("userName").ToObject <string>();
                    account.firstName  = payload.SelectToken("firstName").ToObject <string>();
                    account.department = payload.SelectToken("department").ToObject <string>();
                    account.Email      = payload.SelectToken("email").ToObject <string>();
                    account.lastName   = payload.SelectToken("lastName").ToObject <string>();
                    account.middleName = payload.SelectToken("middleName").ToObject <string>();
                    account.rank       = Convert.ToInt32(payload.SelectToken("rank").ToObject <Int32>());
                    account.userType   = payload.SelectToken("userType").ToObject <string>();
                    account.userStatus = payload.SelectToken("userStatus").ToObject <string>();

                    dbContext.Update(account);
                    await dbContext.SaveChangesAsync();
                }
                else
                {
                    return(BadRequest(new ResponseMessage()
                    {
                        Code = "404",
                        Message = errors
                    }));
                }
            }
            else
            {
                return(BadRequest(ResponseMessage = new ResponseMessage {
                    Code = "400",
                    Message = new List <string>()
                    {
                        "Not found"
                    }
                }));
            }

            return(Json(new
            {
                Id = account.Id, UserName = account.UserName,
                firstName = account.firstName, lastName = account.lastName, department = account.department,
                Email = account.Email, middleName = account.middleName,
                rank = account.rank, userType = account.userType,
                DateAcctCreated = account.DateAcctCreated.ToString("MM/dd/yyyy HH:mm")
            }));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Builds a string representation of a transaction for the Transaction History Box.
        /// </summary>
        /// <param name="req">The request to stringify.</param>
        /// <returns>A string representation of the transaction.</returns>
        public string requestToString(Newtonsoft.Json.Linq.JToken req)
        {
            string res;

            Newtonsoft.Json.Linq.JToken deviceType = completeRequest.SelectToken("DeviceType", true);
            if (deviceType.ToString() == "PAX S300")
            {
                res = PAX_Request_toString(req);
            }
            else
            {
                res = Innowi_Request_toString(req);
            }
            return(res);
        }
Exemplo n.º 9
0
        public async Task KnowMore(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var message = await argument;

            if (message.Text.ToLower().Contains("yes"))
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "6248d2caa0a744a3823f9df847d862a3");
                var queryString = HttpUtility.ParseQueryString(string.Empty);
                queryString["q"] = "what is a lion?";
                var query = "https://api.cognitive.microsoft.com/bing/v5.0/search?" + queryString;

                // Run the query
                HttpResponseMessage httpResponseMessage = client.GetAsync(query).Result;

                // Deserialize the response content
                var responseContentString = httpResponseMessage.Content.ReadAsStringAsync().Result;
                Newtonsoft.Json.Linq.JObject responseObjects = Newtonsoft.Json.Linq.JObject.Parse(responseContentString);

                Newtonsoft.Json.Linq.JToken snippet = responseObjects.SelectToken("webPages.value[0].snippet");

                string result = snippet.ToString();

                await context.PostAsync(result);
            }

            await context.PostAsync("Do you want to play again?");

            context.Wait(MessageReceivedOperationChoice);
        }
Exemplo n.º 10
0
 public static string Get(this Newtonsoft.Json.Linq.JObject input, string key)
 {
     if (input.SelectToken(key) == null)
     {
         return("");
     }
     else
     {
         string value = input.SelectToken(key).ToString();
         if (value.StartsWith("\"") && value.EndsWith("\""))
         {
             value = value.Substring(1, value.Length - 2);
         }
         return(value);
     }
 }
Exemplo n.º 11
0
 public JSON GetCategory(string token)
 {
     if (jToken == null)
     {
         return(new JSON(null));
     }
     else
     {
         return(new JSON(jToken.SelectToken(token)));
     }
 }
Exemplo n.º 12
0
        internal static NIMIMMessage CreateMessage(Newtonsoft.Json.Linq.JObject token)
        {
            if (!token.HasValues || token.Type != Newtonsoft.Json.Linq.JTokenType.Object)
            {
                return(null);
            }
            var msgTypeToken = token.SelectToken(NIMIMMessage.MessageTypePath);

            if (msgTypeToken == null)
            {
                throw new ArgumentException("message type must be seted:" + token.ToString(Formatting.None));
            }
            var          msgType = msgTypeToken.ToObject <NIMMessageType>();
            NIMIMMessage message = null;

            ConvertAttachStringToObject(token);
            switch (msgType)
            {
            case NIMMessageType.kNIMMessageTypeAudio:
                message = token.ToObject <NIMTextMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeFile:
                message = token.ToObject <NIMFileMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeImage:
                message = token.ToObject <NIMImageMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeLocation:
                message = token.ToObject <NIMLocationMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeText:
                message = token.ToObject <NIMTextMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeVideo:
                message = token.ToObject <NIMVedioMessage>();
                break;

            case NIMMessageType.kNIMMessageTypeNotification:
                message = token.ToObject <NIMTeamNotificationMessage>();
                break;

            default:
                message = token.ToObject <NIMUnknownMessage>();
                (message as NIMUnknownMessage).RawMessage = token.ToString(Formatting.None);
                break;
            }
            return(message);
        }
Exemplo n.º 13
0
        public static BaiduDriverLicenseRecognition getDriverRecognition(Newtonsoft.Json.Linq.JObject jObject)
        {
            if (jObject == null)
            {
                return(null);
            }
            BaiduDriverLicenseRecognition driver = new BaiduDriverLicenseRecognition();

            Newtonsoft.Json.Linq.JToken jtError = jObject.SelectToken("error_code");
            if (jtError != null)
            {
                driver.errorCode = jtError.ToString();
                driver.ErrorMsg  = jObject.SelectToken("error_msg").ToString();
                return(driver);
            }
            MyHelper.ConsoleHelper.writeLine(jObject.ToString());
            Newtonsoft.Json.Linq.JToken wordsResult = jObject.SelectToken("words_result");
            if (wordsResult != null)
            {
                driver.name   = wordsResult.SelectToken("姓名").SelectToken("words").ToString();
                driver.number = wordsResult.SelectToken("证号").SelectToken("words").ToString();
                try
                {
                    driver.endTime   = wordsResult.SelectToken("至").SelectToken("words").ToString();
                    driver.startTime = wordsResult.SelectToken("有效期限").SelectToken("words").ToString();
                }
                catch (Exception)
                {
                    driver.startTime   = wordsResult.SelectToken("有效起始日期").SelectToken("words").ToString();
                    driver.expriseDate = wordsResult.SelectToken("有效期限").SelectToken("words").ToString();
                }
                driver.sex       = wordsResult.SelectToken("性别").SelectToken("words").ToString();
                driver.birth     = wordsResult.SelectToken("出生日期").SelectToken("words").ToString();
                driver.country   = wordsResult.SelectToken("国籍").SelectToken("words").ToString();
                driver.type      = wordsResult.SelectToken("准驾车型").SelectToken("words").ToString();
                driver.address   = wordsResult.SelectToken("住址").SelectToken("words").ToString();
                driver.firstDate = wordsResult.SelectToken("初次领证日期").SelectToken("words").ToString();
            }
            return(driver);
        }
Exemplo n.º 14
0
        public void BuscarCoordenadasPorEndereço(ref Pessoa pessoa)
        {
            string apikey = _configuration.GetSection("ApiKey").Value.ToString();
            string url    = "https://maps.googleapis.com/maps/api/geocode/json?address={0}+{1}+{2},+{3},+{4}&oe=utf8&sensor=false&key={5}";

            string address = string.Format(url, pessoa.Endereço.Numero, pessoa.Endereço.Rua, pessoa.Endereço.Bairro,
                                           pessoa.Endereço.Cidade, pessoa.Endereço.Estado, apikey);

            using (HttpClient clientHttp = new HttpClient())
            {
                var response = clientHttp.GetStringAsync(address);
                var result   = response.Result.ToString();
                Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(result);

                var statuscode = json.SelectToken("status").ToString();
                if (statuscode == "OK")
                {
                    var lat   = json.SelectToken("results[0].geometry.location.lat");
                    var longt = json.SelectToken("results[0].geometry.location.lng");
                    pessoa.Endereço.Coordenadas = new Infrastructure.Database.Collections.Coordenadas(
                        new MongoDB.Driver.GeoJsonObjectModel.GeoJson2DGeographicCoordinates(Convert.ToDouble(lat), Convert.ToDouble(longt)));
                }
                else if (statuscode == "ZERO_RESULTS")
                {
                    // Nenhum resultado encontrado!;
                }
                else if (statuscode == "INVALID_REQUEST")
                {
                    //
                }
                else if (statuscode == "UNKNOWN_ERROR")
                {
                    // Erro ao incluir localização
                }
                else
                {
                    // Erro fatal
                }
            }
        }
Exemplo n.º 15
0
        public string BingToSearch(string question)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "281dbe3f0d724b7eb3be917128cf6271");
            var query = "https://api.cognitive.microsoft.com/bing/v7.0/search?" + "q=" + question + "&count=100&mkt=zh-CN" + "site:nuaa.edu.cn";

            HttpResponseMessage httpResponseMessage = client.GetAsync(query).Result;

            var responseContentString = httpResponseMessage.Content.ReadAsStringAsync().Result;

            Newtonsoft.Json.Linq.JObject responseObjects = Newtonsoft.Json.Linq.JObject.Parse(responseContentString);
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                string[] rankingGroups = new string[] { "pole", "mainline", "sidebar" };
                foreach (string rankingName in rankingGroups)
                {
                    Newtonsoft.Json.Linq.JToken rankingResponseItems = responseObjects.SelectToken($"rankingResponse.{rankingName}.items");
                    if (rankingResponseItems != null)
                    {
                        Newtonsoft.Json.Linq.JObject rankingResponseItem = (Newtonsoft.Json.Linq.JObject)rankingResponseItems.ElementAt(0);
                        var resultIndex = rankingResponseItem.GetValue("resultIndex");
                        Newtonsoft.Json.Linq.JToken items = responseObjects.SelectToken("webPages.value");
                        Newtonsoft.Json.Linq.JToken item  = items.ElementAt((int)resultIndex);
                        string url     = (string)item["url"];
                        string snippet = (string)item["snippet"];
                        return(snippet);
                    }
                }
                return(null);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 16
0
        private string DisplayAllRankedResults(Newtonsoft.Json.Linq.JObject responseObjects)
        {
            string[] rankingGroups = new string[] { "mainline" };
            string   displaystr    = "";

            // Loop through the ranking groups in priority order
            foreach (string rankingName in rankingGroups)
            {
                Newtonsoft.Json.Linq.JToken rankingResponseItems = responseObjects.SelectToken($"rankingResponse.{rankingName}.items");
                if (rankingResponseItems != null)
                {
                    foreach (Newtonsoft.Json.Linq.JObject rankingResponseItem in rankingResponseItems)
                    {
                        Newtonsoft.Json.Linq.JToken resultIndex;
                        rankingResponseItem.TryGetValue("resultIndex", out resultIndex);
                        var answerType = rankingResponseItem.Value <string>("answerType");
                        switch (answerType)
                        {
                        case "WebPages":
                            displaystr = displaystr + DisplaySpecificResults(resultIndex, responseObjects.SelectToken("webPages.value"), "WebPage", "name", "url", "snippet");

                            break;
                            //case "News":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("news.value"), "News", "name", "url", "description");
                            //    break;
                            //case "Images":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("images.value"), "Image", "thumbnailUrl");
                            //    break;
                            //case "Videos":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("videos.value"), "Video", "embedHtml");
                            //    break;
                            //case "RelatedSearches":
                            //    DisplaySpecificResults(resultIndex, responseObjects.SelectToken("relatedSearches.value"), "RelatedSearch", "displayText", "webSearchUrl");
                            //    break;
                        }
                        if (displaystr != "")
                        {
                            return(displaystr);
                        }
                    }
                }
            }
            return(displaystr);
        }
        public async Task <IActionResult> CheckHash(string id, [FromBody] Newtonsoft.Json.Linq.JObject obj)
        {
            var user = await dbContext.ApplicationUsers.FirstOrDefaultAsync(u => u.Id == id);

            Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();

            if (user != null)
            {
                string HashAndSalt = user.PasswordAndSalt;
                string input       = payload.SelectToken("Hashpassword").ToObject <string>();

                if (Helpers.PasswordHash.IsPasswordValid(input, HashAndSalt))
                {
                    return(Ok(input + " " + HashAndSalt + "    match"));
                }
            }

            return(BadRequest());
        }
Exemplo n.º 18
0
        public static BaiduBandCardRecognition getBandCardRecognition(Newtonsoft.Json.Linq.JObject jObject)
        {
            if (jObject == null)
            {
                return(null);
            }
            BaiduBandCardRecognition card = new BaiduBandCardRecognition();
            string result = MyHelper.StringHelper.jsonCamelCaseToDBnameing(jObject.SelectToken("result").ToString());

            if (string.IsNullOrEmpty(result))
            {
                card = MyHelper.JsonHelper.JsonToObject(MyHelper.StringHelper.jsonCamelCaseToDBnameing(jObject.ToString()), typeof(BaiduBandCardRecognition)) as BaiduBandCardRecognition;
            }
            else
            {
                card = MyHelper.JsonHelper.JsonToObject(result, typeof(BaiduBandCardRecognition)) as BaiduBandCardRecognition;
            }
            return(card);
        }
Exemplo n.º 19
0
        private String responseToJsonString(HttpResponseMessage response)
        {
            if (response == null)
            {
                throw new BitPayException("Error: HTTP response is null");
            }

            // Get the response as a dynamic object for detecting a possible "error" or "data" object.
            // An "error" object raises an exception.
            // A "data" object has its content extracted (we throw away the "data" wrapper object).
            String  responseString = response.Content.ReadAsStringAsync().Result;
            dynamic obj            = Json.Decode(responseString);

            // Check for error response.
            if (dynamicObjectHasProperty(obj, "error"))
            {
                throw new BitPayException("Error: " + obj.error);
            }
            if (dynamicObjectHasProperty(obj, "errors"))
            {
                String message = "Multiple errors:";
                foreach (var errorItem in obj.errors)
                {
                    message += "\n" + errorItem.error + " " + errorItem.param;
                }
                throw new BitPayException(message);
            }

            // Get a JSON string representation of the object.
            Newtonsoft.Json.Linq.JObject j = Newtonsoft.Json.Linq.JObject.Parse(responseString);
            String jsonString = j.ToString();

            // Check for and exclude a "data" object from the response.
            if (dynamicObjectHasProperty(obj, "data"))
            {
                jsonString = (String)j.SelectToken("data").ToString();
            }

            return(Regex.Replace(jsonString, @"\r\n", ""));
        }
Exemplo n.º 20
0
        public static List <string> RequestCoins()
        {
            List <string> resultado = new List <string>();
            HttpClient    client    = new HttpClient();

            client.BaseAddress = new Uri(URL);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("").Result;

            if (response.IsSuccessStatusCode)
            {
                var resposta = response.Content.ReadAsStringAsync().Result;
                Newtonsoft.Json.Linq.JObject valores = Newtonsoft.Json.Linq.JObject.Parse(resposta);
                foreach (var k in valores.SelectToken("rows"))
                {
                    resultado.Add("(" + k.SelectToken("code").ToString() + ") " + k.SelectToken("name").ToString());
                }
            }
            resultado.Sort();

            return(resultado);
        }
Exemplo n.º 21
0
        static void ConvertAttachStringToObject(Newtonsoft.Json.Linq.JObject token)
        {
            //处理"msg_attach"值,该json原始值是一个string,需要转换为json object
            var attachmentToken = token.SelectToken(NIMIMMessage.AttachmentPath);

            if (attachmentToken == null)
            {
                return;
            }

            if (attachmentToken.Type == Newtonsoft.Json.Linq.JTokenType.String)
            {
                var attachValue = attachmentToken.ToObject <string>();
                if (string.IsNullOrEmpty(attachValue))
                {
                    token.Remove(NIMIMMessage.AttachmentPath);
                    return;
                }
                var newAttachToken = Newtonsoft.Json.Linq.JToken.Parse(attachValue);
                attachmentToken.Replace(newAttachToken);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Runs the test using the predifined parameters from the left text box with the
        /// appropriate device from the radio button selectors.
        /// </summary>
        private async void run_Click(object sender, EventArgs e)
        {
            /*
             * 1. Validate JSON request
             * 2. Initialize Payment Device
             * 3.
             */
            log.Write("runClicked");
            resultData.Text = "";
            Transaction transaction = new Transaction();

            source = new CancellationTokenSource();
            if (PAX_S300.Checked)
            {
                // Run the test on the PAX S300 Device
                Activity.Text = "Validating JSON";
                // Validate the JSON

                Activity.Text = "Initializing PAX S300";
                log.Write("Initializing PAX S300");
                // Initialize device with current settings
                PAXDevice s300 = new PAXDevice();
                if (!s300.initializeDevice(S300_DEVICE_CONFIG))
                {
                    log.Write("Device Initialization Failed");
                    Activity.Text = "Device initializaiton failed";
                }
                else
                {
                    bool errorCondition = false;
                    // Check Device Object Compatability
                    Activity.Text = "Checking Device Object Compatability";

                    // TO-DO: Check that all necessary fields are being sent to the respective device
                    //Newtonsoft.Json.Linq.JObject parameters = null;
                    //Newtonsoft.Json.Linq.JToken tests = null;
                    //Newtonsoft.Json.Linq.JToken[] testArray = null;
                    try
                    {
                        parameters = Newtonsoft.Json.Linq.JObject.Parse(requestData.Text);
                    }
                    catch (Exception parseException)
                    {
                        log.Write("Error: Invalid JSON: " + requestData.Text);
                        Activity.Text  = "Error: Invalid JSON";
                        errorCondition = true;
                    }
                    if (!errorCondition)
                    {
                        try
                        {
                            tests     = parameters.GetValue("TestSequenceData");
                            testArray = tests.ToArray();
                        }
                        catch (Exception noTestSequence)
                        {
                            log.Write("Error: No Test Sequenct Specified");
                            Activity.Text  = "Error: No Test Sequence Specified";
                            errorCondition = true;
                        }
                    }

                    int count           = 0;
                    int referenceNumber = 0;
                    while (!errorCondition && count < testArray.Length)
                    {
                        if (count > 0)
                        {
                            // Add the reference number to the request
                            Newtonsoft.Json.Linq.JObject to = (Newtonsoft.Json.Linq.JObject)testArray[count];
                            to.Add(new Newtonsoft.Json.Linq.JProperty("OrigRefNum", referenceNumber));
                        }
                        // Send Request to device
                        Activity.Text = "Sending Request to PAX S300 Device... Complete transaction on device";
                        string res = await Task.Run(() => s300.processTransaction(testArray[count]));

                        resultData.Text += res + Environment.NewLine + Environment.NewLine;

                        createListBoxItem(requestData.Text, count, res);

                        referenceNumber = s300.getOriginalReferenceNumber();

                        if (PrintReceipt.Checked)
                        {
                            string receipt = "";
                            if (NoSig.Checked)
                            {
                                receipt = await Task.Run(() => s300.printEMVReceiptNoSig());
                            }
                            else
                            {
                                receipt = await Task.Run(() => s300.printEMVReceipt());
                            }
                            saveReceipts(receipt);
                        }

                        count++;
                        Activity.Text = "Completed... Awaiting next command";
                        log.Write("Completed... Awaiting next command");
                    }
                }
            }
            else if (Innowi_ChecOut.Checked)
            {
                bool isAvailable = false;
                // Run the test on the PAX S300 Device
                Activity.Text = "Validating JSON";
                // Validate the JSON

                log.Write("Initializing Innowi ChecOutM Device");
                Activity.Text = "Initializing Innowi ChecOutM device";
                // Initialize device with current settings
                InnowiDevice checkOutM = new InnowiDevice();
                if (!checkOutM.initializeDevice(INNOWI_DEVICE_CONFIG))
                {
                    log.Write("Device Initialization Failed");
                    Activity.Text = "Device initializaiton failed";
                }
                else
                {
                    try
                    {
                        bool errorCondition = false;
                        // Check Device Object Compatability
                        Activity.Text = "Checking Device Object Compatability";

                        // TO-DO: Check that all necessary fields are being sent to the respective device

                        try
                        {
                            parameters = Newtonsoft.Json.Linq.JObject.Parse(requestData.Text);
                        }
                        catch (Exception parseException)
                        {
                            log.Write("Error: Invalid JSON: " + requestData.Text);
                            Activity.Text  = "Error: Invalid JSON";
                            errorCondition = true;
                        }
                        if (!errorCondition)
                        {
                            try
                            {
                                tests     = parameters.GetValue("TestSequenceData");
                                testArray = tests.ToArray();
                            }
                            catch (Exception noTestSequence)
                            {
                                log.Write("Error: No Test Sequence Specified");
                                Activity.Text  = "Error: No Test Sequence Specified";
                                errorCondition = true;
                            }
                        }
                        int count           = 0;
                        int referenceNumber = 0;
                        //Console.WriteLine("TestArray.Length: " + testArray.Length);
                        token = source.Token;
                        while (!errorCondition && count < testArray.Length && !token.IsCancellationRequested)
                        {
                            // Send Request to device
                            log.Write("Sending Request to Innowi ChecOut M Device...");
                            Activity.Text = "Sending Request to Innowi ChecOut M device...";
                            //Console.WriteLine("TestArray[count]: " + testArray[count]);

                            try
                            {
                                string res = await Task.Run(() => checkOutM.processTransaction(testArray[count]), token);

                                resultData.Text += res + Environment.NewLine + Environment.NewLine;
                                Activity.Text    = "Received Response from Innowi ChecOut M device";
                                log.Write("Received Response from Innowi Device: " + res);

                                createListBoxItem(requestData.Text, count, res);

                                if (PrintReceipt.Checked)
                                {
                                    string receipt = "";
                                    if (NoSig.Checked)
                                    {
                                        receipt = await Task.Run(() => checkOutM.printEMVReceiptNoSig());

                                        saveReceipts(receipt);
                                    }
                                    else
                                    {
                                        receipt = await Task.Run(() => checkOutM.printEMVReceipt());

                                        Newtonsoft.Json.Linq.JObject ex  = Newtonsoft.Json.Linq.JObject.Parse(res);
                                        Newtonsoft.Json.Linq.JArray  sig = (Newtonsoft.Json.Linq.JArray)ex.SelectToken("Signature", false);
                                        saveReceipts(receipt, sig);
                                    }
                                }
                                count++;
                                Activity.Text = "Completed... Awaiting next command";
                                log.Write("Completed... Awaiting next command");
                            }
                            catch (NullReferenceException nu)
                            {
                                errorCondition = true;
                                Activity.Text  = "Error: Connection lost to client... Awaiting next command";
                                log.Write("Error: Connection lost to client... Awaiting next command" + nu.StackTrace);
                            }
                            catch (OperationCanceledException cxl)
                            {
                                errorCondition = true;
                                Activity.Text  = "Operation Canceled... Awaiting next command";
                                log.Write("Operation Canceled... Awaiting next command");
                            }
                        }
                    }
                    catch (ArgumentNullException e1)
                    {
                        Console.WriteLine("ArgumentNullException: {0}", e1);
                        log.Write("ArgumentNullException: " + e1.ToString());
                    }
                    catch (SocketException e2)
                    {
                        Console.WriteLine("SocketException: {0}", e2);
                        log.Write("SocketException: " + e2.ToString());
                    }
                }
            }

            /*
             * Used for future device additions
             * Add additional device hooks here
             */
            else
            {
                Activity.Text = "Please select a device.";
            }
        }
Exemplo n.º 23
0
        public string mapInnowiResponseToString()
        {
            string str = "";

            Newtonsoft.Json.Linq.JObject res = Newtonsoft.Json.Linq.JObject.Parse(response);
            Newtonsoft.Json.Linq.JToken  o   = res.SelectToken("Status", true);

            switch (o.ToString())
            {
            case "0":
                str += "A";
                break;

            case "-1":
                str += "D";
                break;

            case "2":
                str += "Error";
                break;

            case "3":
                str += "Terminal not Available";
                break;

            case "4":
                str += "Terminal Busy";
                break;

            case "5":
                str += "R";
                break;

            case "6":
                str += "Innowi Internal Error";
                break;

            case "7":
                str += "Inalid Amount";
                break;

            case "8":
                str += "Transaction Timeout";
                break;

            case "9":
                str += "Transaction Cancelled";
                break;

            case "10":
                str += "Processor not selected";
                break;

            case "11":
                str += "Partial Authorization";
                break;

            case "12":
                str += "Invalid Parameter Value";
                break;

            case "13":
                str += "Need manual confirm";
                break;

            case "14":
                str += "Service Error";
                break;

            case "15":
                str += "Offline not supported";
                break;

            default:
                str += "Unknown Error";
                break;
            }
            return(str);
        }
        public async Task <ActionResult <ApplicationUser> > AddUser([FromBody] Newtonsoft.Json.Linq.JObject obj)
        {
            Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();
            List <string> error = ValidateResponseMessagesList(payload);

            if (error.Count == 0)
            {
                string username = payload.SelectToken("userName").ToObject <string>();
                var    user     = await userManager.FindByNameAsync(username);

                if (user == null)
                {
                    user = new ApplicationUser();

                    user.UserName        = username;
                    user.middleName      = payload.SelectToken("middleName").ToObject <string>();
                    user.firstName       = payload.SelectToken("firstName").ToObject <string>();
                    user.lastName        = payload.SelectToken("lastName").ToObject <string>();
                    user.rank            = Convert.ToInt32(payload.SelectToken("rank").ToObject <Int32>());
                    user.department      = payload.SelectToken("department").ToObject <string>();
                    user.userStatus      = payload.SelectToken("userStatus").ToObject <string>();
                    user.userType        = payload.SelectToken("userType").ToObject <string>();
                    user.Email           = payload.SelectToken("email").ToObject <string>();
                    user.DateAcctCreated = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy HH:mm"));

                    string Hash = payload.SelectToken("Hash").ToObject <string>();
                    user.PasswordAndSalt = Helpers.PasswordHash.CreatePasswordSalt(Hash);

                    await userManager.CreateAsync(user);

                    string ctoken = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    string ctokenlink = Url.Action("ConfirmEmail", "Account", new
                    {
                        userid = user.Id,
                        token  = ctoken
                    }, protocol: HttpContext.Request.Scheme);

                    var email   = user.Email;
                    var subject = "Confirm Email";
                    await emailSender.SendEmailAsync(email, subject, "Please confirm your account by clicking this button link : <br/> "
                                                     + " <button><a href=" + ctokenlink + "> Click </a></button> ");
                }
                else
                {
                    return(Conflict(ResponseMessage = new ResponseMessage {
                        Code = "409",
                        Message = new List <string>()
                        {
                            "Username already Exist"
                        }
                    }));
                }

                return(Json(new
                {
                    Id = user.Id, UserName = user.UserName,
                    firstName = user.firstName, department = user.department,
                    Email = user.Email, lastName = user.lastName,
                    middleName = user.middleName, rank = user.rank,
                    userType = user.userType, DateAcctCreated = DateTime.Now
                }));
            }
            else
            {
                return(BadRequest(new ResponseMessage()
                {
                    Code = "400", Message = error
                }));
            }
        }
Exemplo n.º 25
0
        //public async Task<HttpResponseMessage> RegisterEmail(Guid eventid, [FromBody] string returnedEmail)
        public async Task <HttpResponseMessage> RegisterEmail(Guid eventid, [FromBody] Newtonsoft.Json.Linq.JObject data)
        {
            string sourceUriTxt  = "";
            string returnedEmail = "";

            if (Request.Properties.ContainsKey("MS_HttpContext"))
            {
                var ctx = Request.Properties["MS_HttpContext"] as HttpContextBase;
                if (ctx != null)
                {
                    // var zz = ctx.Request.UserHostAddress;
                    var sourceUrl = ctx.Request.UrlReferrer;
                    sourceUriTxt = sourceUrl.AbsoluteUri.ToString();
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            Newtonsoft.Json.Linq.JToken j = (Newtonsoft.Json.Linq.JToken)data.SelectToken("recaptcha");
            Type   type             = typeof(string);
            string recapchaResponse = (string)System.Convert.ChangeType(j.ToString(), type);

            ReCaptcha.RecapchaControl challengeTest = new ReCaptcha.RecapchaControl();
            if (!challengeTest.CheckRecapchaChallenge(recapchaResponse))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }

            j             = (Newtonsoft.Json.Linq.JToken)data.SelectToken("email");
            returnedEmail = (string)System.Convert.ChangeType(j.ToString(), type);

            try
            {
                if (returnedEmail != null)
                {
                    Event @event = new Event();

                    @event = await db.Events.Where(s => s.GID == eventid && s.Active == true).FirstOrDefaultAsync();


                    if (@event == null)
                    {
                        // Event not found or not active
                        return(Request.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    // Okay the event is valid and active

                    BaseRegistration baseRegistration = new BaseRegistration()
                    {
                        Email = HttpUtility.HtmlEncode(returnedEmail),
                        Date  = DateTime.UtcNow
                    };

                    Contact @contact = await db.Contacts.Where(s => s.Email == baseRegistration.Email).FirstOrDefaultAsync();

                    if (@contact != null && !Settings.AllowDuplicateeMail)
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest));
                    }
                    var registrationUid = Guid.NewGuid();

                    IList <FieldTrip> fieldTrips = await db.FieldTrips.Where(s => s.EventId == @event.EventId).ToListAsync();

                    IList <FieldTripChoice> fieldTripChoices = new List <FieldTripChoice>();
                    foreach (var entry in fieldTrips)
                    {
                        fieldTripChoices.Add(new FieldTripChoice {
                            FieldTripId = entry.FieldTripId, RecordDeleted = false
                        });
                    }


                    IList <AvailableWorkshop> availableWorkshops = await db.AvailableWorkshops.Where(s => s.EventId == @event.EventId).ToListAsync();

                    IList <Workshop> workshops = new List <Workshop>();

                    foreach (var entry in availableWorkshops)
                    {
                        workshops.Add(new Workshop {
                            AvailableWorkshopId = entry.AvailableWorkshopId, RecordDeleted = false
                        });
                    }

                    Registration registration = new Registration()
                    {
                        ValidationUid = registrationUid,
                        Contact       = new Contact()
                        {
                            Email = baseRegistration.Email, RecordDeleted = false
                        },
                        // Field trip options need to be added here
                        EventId             = @event.EventId,
                        FieldTripChoices    = fieldTripChoices,
                        Workshops           = workshops,
                        InitialCreationDate = DateTime.Now,
                        RecordDeleted       = false
                    };

                    db.Registrations.Add(registration);

                    await db.SaveChangesAsync();

                    if (registration.RegistrationId > 0)
                    {
                        // PK value, so record has been saved okay
                        // var id = Guid.NewGuid();
                        // Send email
                        bool           testMode    = Settings.TestMode;
                        HttpStatusCode emailStatus = await SendEmail(baseRegistration.Email, @event.ContactEmail, registrationUid.ToString(), sourceUriTxt, testMode);

                        var response = new HttpResponseMessage(HttpStatusCode.Created)
                        {
                            Content = new StringContent(baseRegistration.Email)
                        };


                        //response.Headers.Location =
                        //    new Uri(Url.Link("DefaultApi", new { action = "status", id = id }));
                        return(response);
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest));
                    }

                    //var verify = db.Events.Select(s => s.Registrations.Where(w => w.EventId == @event.EventId && w.Contact.Email == baseRegistration.Email)).FirstOrDefaultAsync();

                    //if (verify != null)
                    //{
                    //    // var id = Guid.NewGuid();
                    //    // Send email
                    //    HttpStatusCode emailStatus = await SendEmail(baseRegistration.Email, @event.ContactEmail, registrationUid.ToString());

                    //    var response = new HttpResponseMessage(HttpStatusCode.Created)
                    //    {
                    //        Content = new StringContent(baseRegistration.Email)
                    //    };


                    //    //response.Headers.Location =
                    //    //    new Uri(Url.Link("DefaultApi", new { action = "status", id = id }));
                    //    return response;
                    //}
                    //else
                    //{
                    //    return Request.CreateResponse(HttpStatusCode.BadRequest);
                    //}
                    ////return CreatedAtRoute("DefaultApi", new { action = "status", id = id }, value);
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Starts running specific tests of the CertComplete Application.
        /// </summary>
        private async void debugCertCompleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String       str       = resultData.Text;
            InnowiDevice checkOutM = new InnowiDevice();

            if (str == null || str == "")
            {
                throw new Exception("Nothing to test");
            }
            else
            {
                //createListBoxItem(requestData.Text, count, res);

                if (PrintReceipt.Checked)
                {
                    string receipt = "";
                    if (NoSig.Checked)
                    {
                        receipt = await Task.Run(() => checkOutM.printEMVReceiptNoSig());

                        saveReceipts(receipt);
                    }
                    else
                    {
                        receipt = await Task.Run(() => checkOutM.printEMVReceipt());

                        Newtonsoft.Json.Linq.JObject ex  = Newtonsoft.Json.Linq.JObject.Parse(str);
                        Newtonsoft.Json.Linq.JArray  sig = (Newtonsoft.Json.Linq.JArray)ex.SelectToken("Signature", false);
                        saveReceipts(receipt, sig);
                    }
                }
            }
        }
Exemplo n.º 27
0
 static void GotData(Newtonsoft.Json.Linq.JObject obj)
 {
     Console.WriteLine(obj.SelectToken("success"));
 }
        public async Task <ActionResult> ChangePassword(string id, [FromBody] Newtonsoft.Json.Linq.JObject obj)
        {
            Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();
            try
            {
                var user = await userManager.FindByIdAsync(id);

                string password = payload.SelectToken("password").ToObject <string>();

                if (user == null)
                {
                    return(NotFound(ResponseMessage = new ResponseMessage {
                        Code = "404",
                        Message = new List <string>()
                        {
                            "Not found"
                        }
                    }));
                }

                if (password == string.Empty || password == null)
                {
                    return(NotFound(ResponseMessage = new ResponseMessage
                    {
                        Code = "400",
                        Message = new List <string>()
                        {
                            "Password is missing"
                        }
                    }));
                }

                string newPasswordHash = userManager.PasswordHasher.HashPassword(user, password);
                user.PasswordHash = newPasswordHash;
                dbContext.ApplicationUsers.Update(user);
            }
            catch (Exception)
            {
                return(BadRequest(ResponseMessage = new ResponseMessage {
                    Code = "400",
                    Message = new List <string>()
                    {
                        "Password field is missing"
                    }
                }));
            }

            var result = await dbContext.SaveChangesAsync();

            if (result > 0)
            {
                return(Ok(ResponseMessage = new ResponseMessage()
                {
                    Code = "200",
                    Message = new List <string>()
                    {
                        "Password Successfully changed"
                    }
                }));
            }
            else
            {
                return(BadRequest(ResponseMessage = new ResponseMessage {
                    Code = "400",
                    Message = new List <string>()
                    {
                        "Password failed to change"
                    }
                }));
            }
        }
        public static List <string> ValidateResponseMessagesList(Newtonsoft.Json.Linq.JObject obj)
        {
            List <string> error = new List <string>();

            Newtonsoft.Json.Linq.JObject payload = obj.ToObject <Newtonsoft.Json.Linq.JObject>();

            if (payload.SelectToken("userName") == null || payload.SelectToken("userName").ToString() == string.Empty)
            {
                error.Add("userName is required");
            }
            if (payload.SelectToken("firstName") == null || payload.SelectToken("firstName").ToString() == string.Empty)
            {
                error.Add("firstName is required");
            }
            if (payload.SelectToken("lastName") == null || payload.SelectToken("lastName").ToString() == string.Empty)
            {
                error.Add("lastName is required");
            }
            if (payload.SelectToken("rank") == null || Convert.ToInt32(payload.SelectToken("rank")) <= 0)
            {
                error.Add("rank is required");
            }
            if (payload.SelectToken("department") == null || payload.SelectToken("department").ToString() == string.Empty)
            {
                error.Add("department is required");
            }
            if (payload.SelectToken("userStatus") == null || payload.SelectToken("userStatus").ToString() == string.Empty)
            {
                error.Add("userStatus is required");
            }
            if (payload.SelectToken("userType") == null || payload.SelectToken("userType").ToString() == string.Empty)
            {
                error.Add("userType is required");
            }
            if (payload.SelectToken("email") == null || payload.SelectToken("email").ToString() == string.Empty)
            {
                error.Add("email is required");
            }

            return(error);
        }