Example #1
0
        public static T GetState <T>(this JObject?state, string key, Func <T> defaultValue)
        {
            var item = state?.GetValue(key, StringComparison.OrdinalIgnoreCase);

            if (item == null || item.Type == JTokenType.Null)
            {
                return(defaultValue());
            }

            return(item.ToObject <T>(CreateSerializer()) !);
        }
Example #2
0
        public Track RetrieveTrackFromUrl(string url)
        {
            var trackJson = RetrieveJson("https://api.soundcloud.com/resolve.json?url=" + url);

            Console.WriteLine(trackJson);
            JObject track = JObject.Parse(trackJson);

            if (track?.GetValue("id") != null)
            {
                return(JsonConvert.DeserializeObject <Track>(track.ToString()));
            }

            return(null);
        }
Example #3
0
        private string GetDeviceAttribute(string payload, string attribute)
        {
            JObject device = null;

            try
            {
                var json = JObject.Parse(payload);
                device = JObject.Parse(json?.GetValue("device")?.ToString() ?? String.Empty);
            }
            catch (JsonReaderException)
            { }

            return(device?.GetValue(attribute)?.ToString() ?? String.Empty);
        }
        public static string ExtractContinuationToken(JObject bundle)
        {
            var links = bundle?.GetValue(FhirBundleConstants.LinkKey) as JArray;

            if (links != null)
            {
                foreach (var link in links)
                {
                    var linkRelation = (link as JObject)?.GetValue(FhirBundleConstants.LinkRelationKey)?.Value <string>();
                    if (string.Equals(linkRelation, FhirBundleConstants.NextLinkValue, StringComparison.OrdinalIgnoreCase))
                    {
                        var nextLink = (link as JObject)?.GetValue(FhirBundleConstants.LinkUrlKey)?.Value <string>();
                        return(ParseContinuationToken(nextLink));
                    }
                }
            }

            return(null);
        }
Example #5
0
        static string GetApplicationUrl(JObject settings, IDictionary <string, string> environmentVariables)
        {
            var applicationUrl = settings?.GetValue("applicationUrl")?.Value <string> ();

            if (applicationUrl != null)
            {
                return(applicationUrl);
            }

            if (environmentVariables.TryGetValue("ASPNETCORE_URLS", out string applicationUrls))
            {
                applicationUrl = applicationUrls.Split(';').FirstOrDefault();
                if (applicationUrl != null)
                {
                    return(applicationUrl);
                }
            }

            return("http://localhost:5000");
        }
Example #6
0
    private static JArray GetDataArray_FromJson(string strFileName)
    {
        JArray arrObject = new JArray();

        try
        {
            if (strFileName.Contains(".json") == false)
            {
                strFileName += ".json";
            }

            TextAsset pJsonFile = AssetDatabase.LoadAssetAtPath <TextAsset>($"{UnitySO_GeneratorConfig.instance.strJsonData_FolderPath}/{strFileName}");
            JObject   pObject   = (JObject)JsonConvert.DeserializeObject(pJsonFile.text);
            arrObject = (JArray)pObject?.GetValue("array");
        }
        catch
        {
            // ignored
        }

        return(arrObject);
    }
Example #7
0
        private static JToken BuildObjectDiff(JObject original, JObject patched)
        {
            var result     = new JObject();
            var properties = original?.Properties() ?? patched.Properties();

            foreach (var property in properties)
            {
                var propertyName   = property.Name;
                var originalJToken = original?.GetValue(propertyName);
                var patchedJToken  = patched?.GetValue(propertyName);

                var patchToken = BuildDiff(originalJToken, patchedJToken);
                if (patchToken != null)
                {
                    result.Add(propertyName, patchToken);
                }
            }

            if (result.Properties().Any())
            {
                return(result);
            }
            return(null);
        }
        public void GetValue()
        {
            JObject a = new JObject();
            a["Name"] = "Name!";
            a["name"] = "name!";
            a["title"] = "Title!";

            Assert.Equal(null, a.GetValue("NAME", StringComparison.Ordinal));
            Assert.Equal(null, a.GetValue("NAME"));
            Assert.Equal(null, a.GetValue("TITLE"));
            Assert.Equal("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase));
            Assert.Equal("name!", (string)a.GetValue("name", StringComparison.Ordinal));
            Assert.Equal(null, a.GetValue(null, StringComparison.Ordinal));
            Assert.Equal(null, a.GetValue(null));

            JToken v;
            Assert.False(a.TryGetValue("NAME", StringComparison.Ordinal, out v));
            Assert.Equal(null, v);

            Assert.False(a.TryGetValue("NAME", out v));
            Assert.False(a.TryGetValue("TITLE", out v));

            Assert.True(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v));
            Assert.Equal("Name!", (string)v);

            Assert.True(a.TryGetValue("name", StringComparison.Ordinal, out v));
            Assert.Equal("name!", (string)v);

            Assert.False(a.TryGetValue(null, StringComparison.Ordinal, out v));
        }
        public JsonResult PostInsertVisita([FromBody] JObject visita)
        {
            try
            {
                string       outMess          = null;
                VisitaInsert visitaIns        = new VisitaInsert();
                string       nombreEmpleado   = visita.GetValue("NombreEmp").ToString();
                string       ApellidoEmpleado = visita.GetValue("ApellidoEmp").ToString();
                rVP = new rVisitasPricipal();
                rVP.GetIdEmpleado(nombreEmpleado, ApellidoEmpleado);
                visitaIns.Nombre       = visita.GetValue("nombre").ToString();
                visitaIns.Empresa      = visita.GetValue("empresa").ToString();
                visitaIns.Asunto       = visita.GetValue("asunto").ToString();
                visitaIns.Tipo         = visita.GetValue("tipo").ToString();
                visitaIns.FechaEntrada = DateTime.Parse(visita.GetValue("fechaEnt").ToString());
                visitaIns.Empleado     = rVP.IdEmpleado;

                string email = rVP.CorreoEmpleado;

                //-------------------- Envio del correo ---------------------------------------

                MailMessage emailM = new MailMessage();
                emailM.To.Add(new MailAddress(email));
                emailM.From = new MailAddress("*****@*****.**");
                string asunto = "Visita " + visita.GetValue("nombre").ToString().ToUpper() + " " + visita.GetValue("empresa").ToString().ToUpper();
                emailM.Subject = asunto;
                string correoBody = "Buen día<br><br> Te informamos que el visitante <b>" + visita.GetValue("nombre").ToString().ToUpper() + "</b> de la empresa <b>" + visita.GetValue("empresa").ToString().ToUpper()
                                    + "</b> para <b>" + visita.GetValue("asunto").ToString().ToUpper() + "</b> ha llegado.<br><br> Favor de pasar a recepción a atenderlo.";
                emailM.Body       = correoBody;
                emailM.IsBodyHtml = true;
                emailM.Priority   = MailPriority.Normal;

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.ciatec.int";
                smtp.Port = 25;

                try
                {
                    smtp.Send(emailM);
                    emailM.Dispose();
                    outMess = "Corre electrónico fue enviado satisfactoriamente.";
                }
                catch (Exception ex)
                {
                    outMess = "Error enviando correo electrónico: " + ex.Message;
                }

                Console.WriteLine(outMess);

                //-----------------------------------------------------------


                rVP.insertarVisita(visitaIns);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(new JsonResult(rVP.Calificaciones));
        }
Example #10
0
        public int insert_relaCountry(JObject json, string stopman)
        {
            FormsIdentity identity  = HttpContext.Current.User.Identity as FormsIdentity;
            string        userName  = identity.Name;
            JObject       json_user = Extension.Get_UserInfo(userName);
//            string sql = @"insert into rela_country (id,declcountry,inspcountry,createman,stopman,createdate,startdate,enddate,enabled,remark,yearid)
//values(rela_country_id.nextval,'{0-declcountry}','{1-inspcountry}','{2-createman}','{3-stopman}',sysdate,to_date('4-startdate','yyyy-mm-dd hh24:mi:ss'),
//to_date('5-enddate','yyyy-mm-dd hh24:mi:ss'),'{6-enabled}','{7-remark}','')";
            string sql = @"insert into rela_country (id,declcountry,inspcountry,createman,stopman,createdate,startdate,enddate,enabled,remark,yearid)
                                  values(rela_country_id.nextval,'{0}','{1}','{2}','{3}',sysdate,to_date('{4}','yyyy-mm-dd hh24:mi:ss'),
                                  to_date('{5}','yyyy-mm-dd hh24:mi:ss'),'{6}','{7}','')";

            sql = string.Format(sql, json.Value <string>("DECLCOUNTRY"), json.Value <string>("INSPCOUNTRY"), json_user.GetValue("ID"), stopman,
                                json.Value <string>("STARTDATE") == "" ? DateTime.MinValue.ToShortDateString() : json.Value <string>("STARTDATE"),
                                json.Value <string>("ENDDATE") == "" ? DateTime.MaxValue.ToShortDateString() : json.Value <string>("ENDDATE"),
                                json.Value <string>("ENABLED"), json.Value <string>("REMARK"));
            int i = DBMgrBase.ExecuteNonQuery(sql);

            return(i);
        }
Example #11
0
        public Dictionary <int, List <int> > upload_RelaHarbor(string newfile, string fileName, string action, JObject json_formdata)
        {
            Sql.RelaPort bc = new Sql.RelaPort();
            //DataTable dtExcel = GetExcelData_Table(Server.MapPath(newfile), 0);
            DataTable     dtExcel    = GetExcelData_Table(newfile, 0);
            List <string> stringList = new List <string>();
            //停用人
            string stopman = "";

            //存放成功信息
            List <int> repeatListsuccess = new List <int>();
            //存放失败条数
            List <int> repeatListerror = new List <int>();
            //记住insert成功的条数
            int count = 0;
            //返回信息
            Dictionary <int, List <int> > dcInts = new Dictionary <int, List <int> >();

            for (int i = 0; i < dtExcel.Rows.Count; i++)
            {
                for (int j = 0; j < dtExcel.Columns.Count; j++)
                {
                    stringList.Add(dtExcel.Rows[i][j].ToString());
                }
                //报关
                string DECLPORT = stringList[0];
                //报检
                string INSPPORT = stringList[2];

                string REMARK = stringList[4];
                //string ENABLED = stringList[4] == "是" ? "1" : "0";
                string ENABLED = "1";
                //维护人
                string CREATEMANNAME = json_formdata.Value <string>("CREATEMANNAME");
                //启用时间
                string STARTDATE = json_formdata.Value <string>("STARTDATE") == "" ? DateTime.MinValue.ToShortDateString() : json_formdata.Value <string>("STARTDATE");

                //停用日期
                string ENDDATE = json_formdata.Value <string>("ENDDATE") == ""
                    ? DateTime.MaxValue.ToShortDateString()
                    : json_formdata.Value <string>("ENDDATE");

                if (ENABLED == "1")
                {
                    stopman = "";
                }
                else
                {
                    FormsIdentity identity  = HttpContext.Current.User.Identity as FormsIdentity;
                    string        userName  = identity.Name;
                    JObject       json_user = Extension.Get_UserInfo(userName);
                    stopman = (string)json_user.GetValue("ID");
                }
                //导入判断条件
                List <int> inlist = bc.CheckRepeat("", DECLPORT, INSPPORT);

                if (inlist.Count > 0)
                {
                    repeatListerror.Add(i + 2);
                }
                else
                {
                    bc.insert_rela_harbor_excel(DECLPORT, INSPPORT, ENABLED, REMARK, stopman, STARTDATE, ENDDATE);
                    count = count + 1;
                }

                //清除
                stringList.Clear();
            }
            repeatListsuccess.Add(count);
            dcInts.Add(1, repeatListsuccess);
            dcInts.Add(2, repeatListerror);
            return(dcInts);
        }
Example #12
0
        /// <summary>
        /// Converts a JSON object into a dictionary.
        /// </summary>
        /// <remarks>
        /// Used by GraphQL.Transports.AspNetCore.NewtonsoftJson project in server repo.
        /// </remarks>
        public static Inputs ToInputs(this JObject obj)
        {
            var variables = obj?.GetValue() as Dictionary <string, object>;

            return(variables.ToInputs());
        }
        public void sendRequest(
            string method,
            Uri url,
            int requestId,
            string[][] headers,
            JObject data,
            string responseType,
            bool useIncrementalUpdates,
            int timeout)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (responseType == null)
            {
                throw new ArgumentNullException(nameof(responseType));
            }
            if (responseType != "text" && responseType != "base64")
            {
                throw new ArgumentOutOfRangeException(nameof(responseType));
            }

            var request = new HttpRequestMessage(new HttpMethod(method), url);

            var headerData = default(HttpContentHeaderData);

            if (headers != null)
            {
                headerData = HttpContentHelpers.ExtractHeaders(headers);
                ApplyHeaders(request, headers);
            }

            if (data != null)
            {
                var body     = data.Value <string>("string");
                var uri      = default(string);
                var formData = default(JArray);
                if (body != null)
                {
                    if (headerData.ContentType == null)
                    {
                        OnRequestError(requestId, "Payload is set but no 'content-type' header specified.", false);
                        return;
                    }

                    request.Content = HttpContentHelpers.CreateFromBody(headerData, body);
                }
                else if ((uri = data.Value <string>("uri")) != null)
                {
                    if (headerData.ContentType == null)
                    {
                        OnRequestError(requestId, "Payload is set but no 'content-type' header specified.", false);
                        return;
                    }

                    _tasks.Add(requestId, token => ProcessRequestFromUriAsync(
                                   requestId,
                                   new Uri(uri),
                                   useIncrementalUpdates,
                                   timeout,
                                   request,
                                   responseType,
                                   token));

                    return;
                }
                else if ((formData = (JArray)data.GetValue("formData")) != null)
                {
                    if (headerData.ContentType == null)
                    {
                        headerData.ContentType = "multipart/form-data";
                    }

                    var formDataContent = new HttpMultipartFormDataContent();
                    foreach (var content in formData)
                    {
                        var fieldName = content.Value <string>("fieldName");

                        var stringContent = content.Value <string>("string");
                        if (stringContent != null)
                        {
                            formDataContent.Add(new HttpStringContent(stringContent), fieldName);
                        }
                    }

                    request.Content = formDataContent;
                }
            }

            _tasks.Add(requestId, token => ProcessRequestAsync(
                           requestId,
                           useIncrementalUpdates,
                           timeout,
                           request,
                           responseType,
                           token));
        }
Example #14
0
        static IEnumerable <string> GetJsonTestCases(string subset)
        {
            var val = (JArray)TestJsonInputs.GetValue(subset);

            return(val.Children().Select(token => token.ToString()));
        }
            /// <summary>
            ///     Convert JSON Data
            /// </summary>
            /// <param name="jsondata">JSON Object</param>
            /// <returns>List of Adverse Device Events</returns>
            /// <remarks></remarks>
            public static List<AdverseDeviceEvent> CnvJsonDataToList(JObject jsondata)
            {
                var result = new List<AdverseDeviceEvent>();
                //jsondata.dump("In")
                foreach (var obj in jsondata.GetValue("results"))
                {
                    //obj.Dump("Obj")
                    var tmp = new AdverseDeviceEvent();

                    tmp.AdverseEventFlag = Utilities.GetJTokenString(obj, "adverse_event_flag");
                    tmp.ProductProblemFlag = Utilities.GetJTokenString(obj, "product_problem_flag");
                    tmp.DateOfEvent = Utilities.GetJTokenString(obj, "date_of_event");
                    tmp.DateReport = Utilities.GetJTokenString(obj, "date_report");
                    tmp.DateReceived = Utilities.GetJTokenString(obj, "date_received");
                    tmp.NumberDevicesInEvent = Utilities.GetJTokenString(obj, "number_devices_in_event");
                    tmp.NumberPatientsInEvent = Utilities.GetJTokenString(obj, "number_patients_in_event");
                    //Source
                    tmp.ReportSourceCode = Utilities.GetJTokenString(obj, "report_source_code");
                    tmp.HealthProfessional = Utilities.GetJTokenString(obj, "health_professional");
                    tmp.ReporterOccupationCode = Utilities.GetJTokenString(obj, "reporter_occupation_code");
                    tmp.InitialReportToFda = Utilities.GetJTokenString(obj, "initial_report_to_fda");
                    tmp.ReprocessedAndReusedFlag = Utilities.GetJTokenString(obj, "reprocessed_and_reused_flag");

                    var reportTypes = obj.Value<JArray>("type_of_report");

                    if (reportTypes != null)
                    {
                        foreach (var itm in reportTypes)
                        {
                            tmp.TypeOfReport.Add((itm).ToString());
                        }
                    }

                    // Not an array
                    //var remedialAction = obj.Value<JArray>("remedial_action");

                    //if (remedialAction != null)
                    //{
                    //    foreach (var itm in remedialAction)
                    //    {
                    //        tmp.RemedialAction.Add((itm).ToString());
                    //    }
                    //}

                    var sourceType = obj.Value<JArray>("source_type");

                    if (sourceType != null)
                    {
                        foreach (var itm in sourceType)
                        {
                            tmp.SourceType.Add((itm).ToString());
                        }
                    }

                    tmp.DateFacilityAware = Utilities.GetJTokenString(obj, "date_facility_aware");
                    tmp.ReportDate = Utilities.GetJTokenString(obj, "report_date");
                    tmp.ReportToFda = Utilities.GetJTokenString(obj, "report_to_fda");
                    tmp.DateReportToFda = Utilities.GetJTokenString(obj, "date_report_to_fda");
                    tmp.ReportToManufacturer = Utilities.GetJTokenString(obj, "report_to_manufacturer");
                    tmp.DateReportToManufacturer = Utilities.GetJTokenString(obj, "date_report_to_manufacturer");
                    tmp.EventLocation = Utilities.GetJTokenString(obj, "event_location");

                    tmp.DistributorName = Utilities.GetJTokenString(obj, "distributor_name");
                    tmp.DistributorAddress1 = Utilities.GetJTokenString(obj, "distributor_address_1");
                    tmp.DistributorAddress2 = Utilities.GetJTokenString(obj, "distributor_address_2");
                    tmp.DistributorCity = Utilities.GetJTokenString(obj, "distributor_city");
                    tmp.DistributorState = Utilities.GetJTokenString(obj, "distributor_state");
                    tmp.DistributorZipCode = Utilities.GetJTokenString(obj, "distributor_zip_code");
                    tmp.DistributorZipCodeExt = Utilities.GetJTokenString(obj, "distributor_zip_code_ext");

                    tmp.ManufacturerName = Utilities.GetJTokenString(obj, "manufacturer_name");
                    tmp.ManufacturerAddress1 = Utilities.GetJTokenString(obj, "manufacturer_address_1");
                    tmp.ManufacturerAddress2 = Utilities.GetJTokenString(obj, "manufacturer_address_2");
                    tmp.ManufacturerCity = Utilities.GetJTokenString(obj, "manufacturer_city");
                    tmp.ManufacturerState = Utilities.GetJTokenString(obj, "manufacturer_state");
                    tmp.ManufacturerZipCode = Utilities.GetJTokenString(obj, "manufacturer_zip_code");
                    tmp.ManufacturerZipCodeExt = Utilities.GetJTokenString(obj, "manufacturer_zip_code_ext");
                    tmp.ManufacturerCountry = Utilities.GetJTokenString(obj, "manufacturer_country");
                    tmp.ManufacturerPostalCode = Utilities.GetJTokenString(obj, "manufacturer_postal_code");

                    tmp.EventType = Utilities.GetJTokenString(obj, "event_type");
                    tmp.DeviceDateOfManufacture = Utilities.GetJTokenString(obj, "device_date_of_manufacture");
                    tmp.SingleUseFlag = Utilities.GetJTokenString(obj, "single_use_flag");
                    tmp.PreviousUseCode = Utilities.GetJTokenString(obj, "previous_use_code");

                    tmp.RemovalCorrectionNumber = Utilities.GetJTokenString(obj, "removal_correction_number");

                    tmp.ManufactureContactNameTitle = Utilities.GetJTokenString(obj, "manufacturer_contact_t_name");
                    tmp.ManufactureContactNameFirst = Utilities.GetJTokenString(obj, "manufacturer_contact_f_name");
                    tmp.ManufactureContactNameLast = Utilities.GetJTokenString(obj, "manufacturer_contact_l_name");

                    tmp.ManufactureContactStreet1 = Utilities.GetJTokenString(obj, "manufacturer_contact_street_1");
                    tmp.ManufactureContactStreet2 = Utilities.GetJTokenString(obj, "manufacturer_contact_street_2");
                    tmp.ManufactureContactCity = Utilities.GetJTokenString(obj, "manufacturer_contact_city");
                    tmp.ManufactureContactState = Utilities.GetJTokenString(obj, "manufacturer_contact_state");
                    tmp.ManufactureContactZipCode = Utilities.GetJTokenString(obj, "manufacturer_contact_zip_code");
                    tmp.ManufactureContactZipCodeExt = Utilities.GetJTokenString(obj, "manufacturer_contact_zip_ext");
                    tmp.ManufactureContactPostal = Utilities.GetJTokenString(obj, "manufacturer_contact_postal");
                    tmp.ManufactureContactCountry = Utilities.GetJTokenString(obj, "manufacturer_contact_country");

                    tmp.ManufactureContactPhoneCountry = Utilities.GetJTokenString(obj, "manufacturer_contact_pcountry");
                    tmp.ManufactureContactPhoneAreaCode = Utilities.GetJTokenString(obj, "manufacturer_contact_area_code");
                    tmp.ManufactureContactPhoneExchange = Utilities.GetJTokenString(obj, "manufacturer_contact_exchange");
                    tmp.ManufactureContactPhoneExtension = Utilities.GetJTokenString(obj, "manufacturer_contact_extension");
                    tmp.ManufactureContactPhoneCity = Utilities.GetJTokenString(obj, "manufacturer_contact_pcity");
                    tmp.ManufactureContactPhoneNumber = Utilities.GetJTokenString(obj, "manufacturer_contact_phone_number");
                    tmp.ManufactureContactLocal = Utilities.GetJTokenString(obj, "manufacturer_contact_plocal");

                    tmp.ManufactureName = Utilities.GetJTokenString(obj, "manufacturer_g1_name");
                    tmp.ManufactureStreet1 = Utilities.GetJTokenString(obj, "manufacturer_g1_street_1");
                    tmp.ManufactureStreet2 = Utilities.GetJTokenString(obj, "manufacturer_g1_street_2");
                    tmp.ManufactureCity = Utilities.GetJTokenString(obj, "manufacturer_g1_city");
                    tmp.ManufactureState = Utilities.GetJTokenString(obj, "manufacturer_g1_state");
                    tmp.ManufactureZipCode = Utilities.GetJTokenString(obj, "manufacturer_g1_zip_code");
                    tmp.ManufactureZipCodeExt = Utilities.GetJTokenString(obj, "manufacturer_g1_zip_ext");
                    tmp.ManufacturePostalCode = Utilities.GetJTokenString(obj, "manufacturer_g1_postal_code");
                    tmp.ManufactureCountry = Utilities.GetJTokenString(obj, "manufacturer_g1_country");
                    tmp.DateManufacturerReceived = Utilities.GetJTokenString(obj, "date_manufacturer_received");

                    tmp.EventKey = Utilities.GetJTokenString(obj, "event_key");
                    tmp.MdrReportKey = Utilities.GetJTokenString(obj, "mdr_report_key");
                    tmp.ManufacturerLinkFlag = Utilities.GetJTokenString(obj, "manufacturer_link_flag_");

                    tmp.Device = DeviceEventDeviceData.CnvJsonDataToList((JArray) Utilities.GetJTokenObject(obj, "device"));
                    tmp.Patient = DeviceEventPatientData.CnvJsonDataToList((JArray) Utilities.GetJTokenObject(obj, "patient"));
                    tmp.MdrText = DeviceEventMdrTextData.CnvJsonDataToList((JArray) Utilities.GetJTokenObject(obj, "mdr_text"));

                    result.Add(tmp);
                }

                return result;
            }
Example #16
0
 public static StarEvent GetInstance(JObject data, bool starred)
 {
     return new StarEvent() {
         Id = data.GetValue("id").Value<string>(),
         Type = data.GetValue("type").Value<string>(),
         Starred = starred
     };
 }
Example #17
0
        public ActionResult CompleteVisit()
        {
            Stream req = Request.InputStream;

            req.Seek(0, System.IO.SeekOrigin.Begin);
            string json = new StreamReader(req).ReadToEnd();

            var    dbTransaction = db.Database.BeginTransaction();
            Object result;

            try
            {
                // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
                JObject input = (JObject)JsonConvert.DeserializeObject(json);

                int    idVisita   = input.GetValue("visita").ToObject <int>();
                string horaVisita = input.GetValue("hora").ToObject <string>();

                var latObject = input.GetValue("lat");
                var lngObject = input.GetValue("lng");

                Nullable <decimal> lat = null;
                Nullable <decimal> lng = null;

                if (latObject != null)
                {
                    lat = latObject.ToObject <decimal>();
                }

                if (lngObject != null)
                {
                    lng = lngObject.ToObject <decimal>();
                }

                string identificador = input.GetValue("identificador").ToObject <string>();
                string frascos       = input.GetValue("frascos").ToObject <string>();

                var detalles = input.GetValue("detalles");


                VISITA visita = db.VISITAs.Find(idVisita);

                visita.identificador = identificador;
                visita.no_frascos    = byte.Parse(frascos);
                visita.lat           = lat;
                visita.lng           = lng;

                var horas   = Int32.Parse(horaVisita.Substring(0, 2));
                var minutos = Int32.Parse(horaVisita.Substring(3, 2));

                visita.fecha_visita = new DateTime(visita.fecha_visita.Value.Year, visita.fecha_visita.Value.Month, visita.fecha_visita.Value.Day, horas, minutos, 0);

                List <DETALLE_VISITA> detallesVisita = db.DETALLE_VISITA.Where(dv => dv.id_visita == visita.id_visita).ToList();

                List <int> detallesVisitaInput = new List <int>();
                foreach (JObject detalle in detalles)
                {
                    byte   muestra = detalle.GetValue("muestra").ToObject <byte>();
                    string value   = detalle.GetValue("value").ToObject <string>();

                    DETALLE_VISITA detalleVisita = db.DETALLE_VISITA.SingleOrDefault(dv => dv.id_muestra == muestra && dv.id_visita == idVisita);

                    if (detalleVisita == null)
                    {
                        detalleVisita = new DETALLE_VISITA()
                        {
                            id_visita  = idVisita,
                            id_muestra = muestra,
                            value      = Decimal.Parse(value)
                        };

                        visita.DETALLE_VISITA.Add(detalleVisita);
                    }
                    else
                    {
                        detalleVisita.value = Decimal.Parse(value);
                    }

                    db.SaveChanges();
                    detallesVisitaInput.Add(detalleVisita.id_detalle_visita);
                }

                foreach (DETALLE_VISITA detalleVisita in detallesVisita)
                {
                    if (!detallesVisitaInput.Exists(d => d == detalleVisita.id_detalle_visita))
                    {
                        db.DETALLE_VISITA.Remove(detalleVisita);
                    }
                }
                db.SaveChanges();

                dbTransaction.Commit();

                result = new { isValid = true };
            }
            catch (Exception e)
            {
                dbTransaction.Rollback();

                var msg = e.Message;

                result = new { isValid = false, msg = msg };
            }

            return(Json(result));
        }
        public JsonResult GetGames()
        {
            var manager     = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new GameLoggerIden.Models.ApplicationDbContext()));
            var CurrentUser = manager.FindById(User.Identity.GetUserId());

            // If current user has a Steam account linked
            if (CurrentUser.Logins.Count > 0)
            {
                for (int q = 0; q < CurrentUser.Logins.Count; q++)
                {
                    if (CurrentUser.Logins.ToList()[q].LoginProvider == "Steam")
                    {
                        string url    = string.Format("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=BAC162F90A60259B7E7EB20A4EB46B63&steamid={0}&include_appinfo=1&format=json", this.GetSteamID());
                        string result = null;

                        using (var client = new WebClient())
                        {
                            result = client.DownloadString(url);
                        }

                        JObject jsonResults = JObject.Parse(result);
                        JObject steamGames  = JObject.Parse(jsonResults.GetValue("response").ToString());

                        JArray games = JArray.Parse(steamGames.GetValue("games").ToString());

                        using (BacklogDataContext db = new BacklogDataContext())
                        {
                            List <Game> dbGames = db.Games.AsNoTracking().ToList();

                            // Loop through all of user's Steam games and add them to backlog
                            for (int i = 0; i < games.Count; i++)
                            {
                                // Get game name
                                string gameName = games[i]["name"].ToString();

                                // Check to see if game exists in database
                                //Game dbGame = db.Games.AsNoTracking().FirstOrDefault(u => u.Name == gameName);
                                for (int x = 0; x < dbGames.Count; x++)
                                {
                                    if (dbGames[x].Name == gameName)
                                    {
                                        Game dbGame = dbGames[x];

                                        // Add game to backlog if it doesn't already exist
                                        if (dbGame != null)
                                        {
                                            Backlog backlogEntry = db.Backlogs.Find(User.Identity.Name, dbGame.Id); // Check to see if current user has this game in their backlog

                                            // If game doesn't exist in backlog, add it
                                            if (backlogEntry == null)
                                            {
                                                // Get game playtime
                                                int playTime = 0;
                                                Int32.TryParse(games[i]["playtime_forever"].ToString(), out playTime);

                                                // Add game to backlog
                                                Backlog newGame = new Backlog();
                                                newGame.GameId   = dbGame.Id;
                                                newGame.PlayTime = playTime;
                                                newGame.UserName = User.Identity.Name;

                                                Backlog userGame = db.Backlogs.Add(newGame);
                                            }
                                            else // If game exists in backlog already, update playtime
                                            {
                                                // Get game playtime
                                                int playTime = 0;
                                                Int32.TryParse(games[i]["playtime_forever"].ToString(), out playTime);

                                                backlogEntry.PlayTime = playTime;
                                            }
                                        }
                                    }
                                }
                            }

                            db.SaveChanges();
                        }

                        return(Json("{\"success\": true}", JsonRequestBehavior.AllowGet));
                    }
                }
            }

            return(Json("{\"success\": false}", JsonRequestBehavior.AllowGet));
        }
Example #19
0
        private void setupPayment()
        {
            try
            {
                string accessKey   = ConfigurationManager.AppSettings["accesskey"];
                string secretKey   = ConfigurationManager.AppSettings["secretkey"];
                string environment = ConfigurationManager.AppSettings["environment"];

                layerAPI = new clsLayer(accessKey, secretKey, environment);

                data                = new clsPaymentData();
                data.amount         = Convert.ToDecimal(ConfigurationManager.AppSettings["sampleDataAmount"]);
                data.currency       = ConfigurationManager.AppSettings["sampleDataCurrency"].ToString();
                data.name           = ConfigurationManager.AppSettings["sampleDataName"].ToString();
                data.contact_number = ConfigurationManager.AppSettings["sampleDataContactNumber"].ToString();
                data.email_id       = ConfigurationManager.AppSettings["sampleDataEmail"].ToString();
                data.mtx            = DateTime.Now.ToString("yyyyMMdd") + "-" + new Random().Next(1000, 9999).ToString();

                JObject jObject      = new JObject();
                JObject jObjectToken = new JObject();

                //create payment token
                var result = layerAPI.CreatePaymentToken(data);

                jObject = JsonConvert.DeserializeObject <JObject>(result);

                string errMessage = "";

                if (jObject["error"] != null)
                {
                    errMessage = "E55 Payment error. " + jObject.GetValue("error").ToString();
                    //add code for error list
                    if (jObject["error_data"] != null)
                    {
                        foreach (JProperty p in jObject["error_data"])
                        {
                            string e = p.Value.ToString().Replace("\r", "").Replace("\n", "").Replace("[", "").Replace("]", "").Trim();
                            errMessage += " " + e;
                        }
                    }
                }

                if (errMessage == "" && jObject["id"] != null && jObject.GetValue("id").ToString() == "")
                {
                    errMessage = "Payment error. Layer token ID cannot be empty.";
                }

                if (errMessage == "")
                {
                    //check that the payment is setup correctly and has not been pad
                    var resultToken = layerAPI.GetPaymentToken(jObject.GetValue("id").ToString());

                    jObjectToken = JsonConvert.DeserializeObject <JObject>(result);

                    if (jObjectToken["error"] != null)
                    {
                        errMessage = "E56 Payment error. " + jObjectToken.GetValue("error").ToString();
                        //add code for error list
                    }

                    if (errMessage == "" && jObjectToken["status"] != null && jObject.GetValue("status").ToString() == "paid")
                    {
                        errMessage = "Layer: this order has already been paid.";
                    }

                    if (errMessage == "" && jObjectToken["amount"] != null &&
                        Convert.ToDecimal(jObjectToken.GetValue("amount")) != Convert.ToDecimal(jObject.GetValue("amount")))
                    {
                        errMessage = "Layer: an amount mismatch occurred";
                    }
                }

                if (errMessage.Length > 0)
                {
                    lblError.Text = errMessage;
                    return;
                }

                //setup hidden values
                string paymentTokenId = jObjectToken.GetValue("id").ToString();
                string amount         = (Convert.ToDecimal(jObjectToken.GetValue("amount"))).ToString("#0.00");

                //create hash
                string hashValue = layerAPI.CreateHash(paymentTokenId,
                                                       Convert.ToDecimal(jObjectToken.GetValue("amount")), data.mtx);

                layer_pay_token_id.Value = paymentTokenId;
                tranid.Value             = data.mtx;
                layer_order_amount.Value = amount;
                layer_payment_id.Value   = "";
                fallback_url.Value       = "";
                hash.Value = hashValue;
                key.Value  = layerAPI.accessKey;
            }
            catch (Exception ex)
            {
                lblError.Text = "Error: " + ex.Message;
            }
        }
Example #20
0
        public void save(string formdata)
        {
            JObject json = (JObject)JsonConvert.DeserializeObject(formdata);

            Sql.RelaPort bcsql = new Sql.RelaPort();
            //禁用人
            string stopman = "";
            //返回重复结果
            string repeat = "";
            //返回前端的值
            string response = "";

            if (json.Value <string>("ENABLED") == "1")
            {
                stopman = "";
            }
            else
            {
                FormsIdentity identity  = HttpContext.Current.User.Identity as FormsIdentity;
                string        userName  = identity.Name;
                JObject       json_user = Extension.Get_UserInfo(userName);
                stopman = (string)json_user.GetValue("ID");
            }

            if (String.IsNullOrEmpty(json.Value <string>("ID")))
            {
                List <int> retunRepeat = bcsql.CheckRepeat(json.Value <string>("ID"), json.Value <string>("DECLPORT"), json.Value <string>("INSPPORT"));
                if (retunRepeat.Count > 0)
                {
                    repeat = "此报关口岸和报检口岸已经有对应关系存在,请检查";
                }
                else
                {
                    int i = bcsql.insert_relaPackage(json, stopman);
                    repeat = "5";
                }
            }
            else
            {
                List <int> retunRepeat = bcsql.CheckRepeat(json.Value <string>("ID"), json.Value <string>("DECLPORT"), json.Value <string>("INSPPORT"));
                if (retunRepeat.Count > 0)
                {
                    repeat = "此报关口岸和报检口岸已经有对应关系存在,请检查";
                }
                else
                {
                    DataTable dt = bcsql.LoadDataById(json.Value <string>("ID"));
                    int       i  = bcsql.update_relaHarbor(json, stopman);
                    if (i > 0)
                    {
                        bcsql.insert_base_alterrecord(json, dt);
                    }
                    repeat = "5";
                }
            }

            response = "{\"success\":\"" + repeat + "\"}";

            Response.Write(response);
            Response.End();
        }
Example #21
0
        /// <summary>
        /// Generates a final Path based on parameters in Dictionary and resource properties.
        /// </summary>
        /// <typeparam name="T">MPBase resource.</typeparam>
        /// <param name="path">Path we are processing.</param>
        /// <param name="mapParams">Collection of parameters that we will use to process the final path.</param>
        /// <param name="resource">Resource containing parameters values to include in the final path.</param>
        /// <param name="requestOptions">Object containing the request options.</param>
        /// <returns>Processed path to call the API.</returns>
        public static string ParsePath <T>(string path, Dictionary <string, string> mapParams, T resource, MPRequestOptions requestOptions) where T : MPBase
        {
            string          param_pattern = @":([a-z0-9_]+)";
            MatchCollection matches       = Regex.Matches(path, param_pattern);

            foreach (Match param in matches)
            {
                string param_string = param.Value.Replace(":", "");

                if (mapParams != null)
                {
                    foreach (KeyValuePair <String, String> entry in mapParams)
                    {
                        if (param_string == entry.Key)
                        {
                            path = path.Replace(param.Value, entry.Value);
                        }
                    }
                }

                if (resource != null)
                {
                    JObject json           = JObject.FromObject(resource);
                    var     resource_value = json.GetValue(ToPascalCase(param_string));
                    if (resource_value != null)
                    {
                        path = path.Replace(param.Value, resource_value.ToString());
                    }
                }
            }

            StringBuilder result = new StringBuilder();

            result.Insert(0, SDK.BaseUrl);
            result.Append(path);

            if (requestOptions == null)
            {
                requestOptions = new MPRequestOptions();
            }

            string accessToken;

            if (!String.IsNullOrEmpty(requestOptions.AccessToken))
            {
                accessToken = requestOptions.AccessToken;
            }
            else if (resource != null && !String.IsNullOrEmpty(resource.MarketplaceAccessToken))
            {
                accessToken = resource.MarketplaceAccessToken;
            }
            else
            {
                accessToken = SDK.GetAccessToken();
            }

            if (!String.IsNullOrEmpty(accessToken) && !path.Equals("/oauth/token", StringComparison.InvariantCultureIgnoreCase))
            {
                result.Append(string.Format("{0}{1}", "?access_token=", accessToken));
            }

            bool search = !path.Contains(':') && mapParams != null && mapParams.Any();

            if (search) //search url format, no :id type. Params after access_token
            {
                foreach (var elem in mapParams)
                {
                    if (!string.IsNullOrEmpty(elem.Value))
                    {
                        result.Append(string.Format("{0}{1}={2}", "&", elem.Key, elem.Value));
                    }
                }
            }

            return(result.ToString());
        }
Example #22
0
        public int insert_base_alterrecord(JObject json, DataTable dt)
        {
            FormsIdentity identity  = HttpContext.Current.User.Identity as FormsIdentity;
            string        userName  = identity.Name;
            JObject       json_user = Extension.Get_UserInfo(userName);
            string        sql       = @"insert into base_alterrecord(id,
                                tabid,tabkind,alterman,
                                reason,contentes,alterdate) 
                                values(base_alterrecord_id.nextval,
                                '{0}','{1}','{2}',
                                '{3}','{4}',sysdate)";

            sql = String.Format(sql,
                                json.Value <string>("ID"), (int)Base_YearKindEnum.Rela_Country, json_user.GetValue("ID"),
                                json.Value <string>("REASON"), getChange(dt, json));
            int i = DBMgrBase.ExecuteNonQuery(sql);

            return(i);
        }
Example #23
0
        public static async Task <Car> GetAnItem(uint ID)
        {
            HttpWebRequest rq = null;

            try
            {
                if (HelperFunction.IsInternetAvailable)
                {
                    rq = (HttpWebRequest)HttpWebRequest.Create(_getItemUrl);

                    JObject item = new JObject();
                    item["ID"] = ID.ToString();

                    var data = Encoding.ASCII.GetBytes(item.ToString());
                    rq.Method        = "POST";
                    rq.ContentType   = "application/json";
                    rq.ContentLength = data.Length;

                    using (var stream = rq.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                        stream.Flush();
                    }
                    using (HttpWebResponse rs = (HttpWebResponse)rq.GetResponse())
                    {
                        if (rs.StatusCode != HttpStatusCode.OK)
                        {
                            throw new WebException("Failed to get the item!", WebExceptionStatus.ReceiveFailure);
                        }
                        else
                        {
                            String response = String.Empty;
                            using (StreamReader sr = new StreamReader(rs.GetResponseStream()))
                            {
                                response = await sr.ReadToEndAsync();

                                sr.Close();
                            }
                            Car     c     = null;
                            JObject _item = JObject.Parse(response);
                            var     id    = (String)item.GetValue("ID");
                            if (!string.IsNullOrEmpty(id))
                            {
                                try
                                {
                                    c       = new Car(Convert.ToUInt32(id));
                                    c.Name  = (String)_item.GetValue("Name");
                                    c.Make  = (String)_item.GetValue("Make");
                                    c.Model = (String)_item.GetValue("Model");
                                    c.Color = (String)_item.GetValue("Color");
                                    c.Year  = (UInt32)_item.GetValue("Year");
                                    c.Price = (Double)_item.GetValue("Price");
                                    c.Sold  = (Boolean)_item.GetValue("Sold");
                                }
                                catch { return(null); }
                            }
                            return(c);
                        }
                    }
                }
                throw new WebException("There is no internet connection!", WebExceptionStatus.ConnectFailure);
            }
            catch (Exception ex) { Library.WriteLog(ex); return(null); }
            finally { rq.Abort(); }
        }
Example #24
0
        public int update_relaCountry(JObject json, string stopman)
        {
            FormsIdentity identity  = HttpContext.Current.User.Identity as FormsIdentity;
            string        userName  = identity.Name;
            JObject       json_user = Extension.Get_UserInfo(userName);
            string        sql       = @"update rela_country set declcountry='{0}',inspcountry='{1}',createman='{2}',stopman='{3}',createdate=sysdate,
                                 startdate =to_date('{4}','yyyy-mm-dd hh24:mi:ss'),enddate=to_date('{5}','yyyy-mm-dd hh24:mi:ss'),enabled='{6}',remark='{7}'
                                 where id='{8}'";

            sql = string.Format(sql, json.Value <string>("DECLCOUNTRY"), json.Value <string>("INSPCOUNTRY"), json_user.GetValue("ID"), stopman,
                                json.Value <string>("STARTDATE") == "" ? DateTime.MinValue.ToShortDateString() : json.Value <string>("STARTDATE"),
                                json.Value <string>("ENDDATE") == "" ? DateTime.MaxValue.ToShortDateString() : json.Value <string>("ENDDATE"),
                                json.Value <string>("ENABLED"), json.Value <string>("REMARK"), json.Value <string>("ID"));
            int i = DBMgrBase.ExecuteNonQuery(sql);

            return(i);
        }
Example #25
0
        public void GetApiData()
        {
            foreach (string country in Settings.Countries)
            {
                int count = 0;
                while (true)
                {
                    try
                    {
                        //{"code":0,"message":"Success","data":{"rowset":[],"totalPages":1,"totalRows":68,"offset":2,"limit":100}}
                        count++;
                        Logger.print("Get Page: " + count.ToString());
                        string data = GetData(count, country);
                        if (data.Contains("API Key Wrong"))
                        {
                            Logger.print("Invalid Token!!!");
                            break;
                        }

                        if (data == "ERROR")
                        {
                            Logger.print("Network ERROR!!!");
                            break;
                        }

                        JObject jObject = JObject.Parse(data);
                        string  json    = JObject.Parse(jObject.GetValue("data").ToString()).GetValue("rowset").ToString();
                        if (json.Equals("[]"))
                        {
                            Logger.print("Success!");
                            break;
                        }

                        //Debug.WriteLine(json);
                        JArray jObjArr = JArray.Parse(json);
                        jObjArr.ToList().ForEach(x =>
                        {
                            try
                            {
                                Debug.WriteLine(x);
                                var jObj = JObject.Parse(x["offer"].ToString());
                                if (jObj["status"].ToString().ToLower().Equals("active"))
                                {
                                    var offerInfo = new OfferInfo
                                    {
                                        Id         = $"{jObj["id"]}",
                                        Name       = $"{jObj["name"]}",
                                        Tracking   = $"{jObj["tracking_link"]}",
                                        PreviewUrl = $"{jObj["preview_url"]}",
                                        Payout     = double.Parse($"{jObj["payout"]}"),
                                    };

                                    offerInfo.Country  = JObject.Parse(x["offer_geo"].ToString()).GetValue("target")[0]["country_code"].ToString();
                                    offerInfo.Platform = JObject.Parse(x["offer_platform"].ToString()).GetValue("target")[0]["system"].ToString();

                                    if (Utils.IsCountryAllowed(country, new List <string> {
                                        offerInfo.Country
                                    }) && Utils.IsPassedSetting(Settings, offerInfo))
                                    {
                                        if (Settings.GetName.Count <= 0 || Utils.IsExitsFromList(Settings.GetName, offerInfo.Name) || Utils.IsExitsFromList(Settings.GetName, offerInfo.PreviewUrl))
                                        {
                                            Utils.WriteOfferInfo(offerInfo, Settings.SavePath);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine($"Parser ERROR:" + ex.Message);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("CC" + ex.Message);
                    }
                }
            }
        }
Example #26
0
        public static string oauth_consumer_secret = Keys.OAuthConsumerSecret; // "insert here...";

        public static List <List <string> > GetTweets()
        {
            var result = new List <List <string> > {
            };

            const string query = "tes";
            var          url   = "https://api.twitter.com/1.1/search/tweets.json";
            const string count = "100";
            const string lang  = "id";

            // oauth implementation details
            var oauth_version          = "1.0";
            var oauth_signature_method = "HMAC-SHA1";

            var oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            var timeSpan    = DateTime.UtcNow
                              - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

            // create oauth signature
            var baseFormat = "count={7}&lang={8}&oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                             "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";

            var baseString = string.Format(baseFormat,
                                           oauth_consumer_key,
                                           oauth_nonce,
                                           oauth_signature_method,
                                           oauth_timestamp,
                                           oauth_token,
                                           oauth_version,
                                           Uri.EscapeDataString(query),
                                           Uri.EscapeDataString(count),
                                           Uri.EscapeDataString(lang)
                                           );

            baseString = string.Concat("GET&", Uri.EscapeDataString(url), "&", Uri.EscapeDataString(baseString));

            var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                             "&", Uri.EscapeDataString(oauth_token_secret));

            string oauth_signature;

            using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(
                    hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }

            // create the request header
            var headerFormat = "OAuth oauth_consumer_key=\"{3}\", oauth_nonce=\"{0}\", " +
                               "oauth_signature=\"{5}\", oauth_signature_method=\"{1}\", " +
                               "oauth_timestamp=\"{2}\", oauth_token=\"{4}\", " +
                               "oauth_version=\"{6}\"";

            var authHeader = string.Format(headerFormat,
                                           Uri.EscapeDataString(oauth_nonce),
                                           Uri.EscapeDataString(oauth_signature_method),
                                           Uri.EscapeDataString(oauth_timestamp),
                                           Uri.EscapeDataString(oauth_consumer_key),
                                           Uri.EscapeDataString(oauth_token),
                                           Uri.EscapeDataString(oauth_signature),
                                           Uri.EscapeDataString(oauth_version)
                                           );

            ServicePointManager.Expect100Continue = false;

            // make the request
            url += "?q=" + Uri.EscapeDataString(query) + "&lang=" + Uri.EscapeDataString(lang) + "&count=" + Uri.EscapeDataString(count);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Headers.Add("Authorization", authHeader);
            request.Method      = "GET";
            request.ContentType = "application/x-www-form-urlencoded";

            var response = (HttpWebResponse)request.GetResponse();
            var reader   = new StreamReader(response.GetResponseStream());
            var objText  = reader.ReadToEnd();

            JObject jsonDat = JObject.Parse(objText);

            for (int i = 0; i < jsonDat.GetValue("statuses").Count(); i++)
            {
                var data = (JObject)jsonDat.GetValue("statuses")[i];

                result.Add(new List <string>
                {
                    data.GetValue("text").ToString(),
                    data.GetValue("created_at").ToString(),
                });
            }

            return(result);
        }
 public ResourceReply(JObject response)
 {
     this.response = response;
     this.success  = response.ContainsKey("success") && response.GetValue("success").Value <bool>();
     this.cause    = response.ContainsKey("cause") ? response.GetValue("cause").Value <string>() : null;
 }
Example #28
0
        public String request(String method, String resource_uri, String data = "{}")
        {
            String api_version = conekta.Api.version.Replace(".", "");

            if (int.Parse(api_version) < 110)
            {
                ConektaException ex = new ConektaException("This package just support api version 1.1 or higher");
                ex.details = new JArray(0);
                ex._object = "error";
                ex._type   = "api_version_unsupported";

                throw ex;
            }

            try {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var            uname = Environment.OSVersion;
                HttpWebRequest http  = (HttpWebRequest)WebRequest.Create(conekta.Api.baseUri + resource_uri);
                http.Accept    = "application/vnd.conekta-v" + conekta.Api.version + "+json";
                http.UserAgent = "Conekta/v1 DotNetBindings10/Conekta::" + conekta.Api.version;
                http.Method    = method;

                var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(conekta.Api.apiKey);
                var userAgent      = (@"{
				  ""bindings_version"":"""                 + conekta.Api.version + @""",
				  ""lang"":"".net"",
				  ""lang_version"":"""                 + typeof(string).Assembly.ImageRuntimeVersion + @""",
				  ""publisher"":""conekta"",
				  ""uname"":"""                 + uname + @"""
				}"                );

                http.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes) + ":");
                http.Headers.Add("Accept-Language", conekta.Api.locale);
                http.Headers.Add("X-Conekta-Client-User-Agent", userAgent);

                if (method == "POST" || method == "PUT")
                {
                    var dataBytes = Encoding.UTF8.GetBytes(data);

                    http.ContentLength = dataBytes.Length;
                    http.ContentType   = "application/json";

                    Stream dataStream = http.GetRequestStream();
                    dataStream.Write(dataBytes, 0, dataBytes.Length);
                }

                WebResponse response = http.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                //System.Console.WriteLine(responseString);

                return(responseString);
            } catch (WebException webExcp) {
                WebExceptionStatus status = webExcp.Status;

                HttpWebResponse httpResponse = (HttpWebResponse)webExcp.Response;

                var encoding = ASCIIEncoding.UTF8;
                using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream(), encoding))
                {
                    string responseText = reader.ReadToEnd();

                    //System.Console.WriteLine(responseText);

                    JObject obj = JsonConvert.DeserializeObject <JObject>(responseText, new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });

                    ConektaException ex = new ConektaException(obj.GetValue("type").ToString());
                    ex.details = (JArray)obj["details"];
                    ex._object = obj.GetValue("object").ToString();
                    ex._type   = obj.GetValue("type").ToString();

                    throw ex;
                }
            } catch (Exception e) {
                System.Console.WriteLine(e.ToString());
                return("");
            }
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    props = MetadataHelper.GetProperties("Edm.GeographyPoint", 1, out entityTypeShortName);

            if (null == props || !props.Any())
            {
                return(passed);
            }

            string propName     = props[0].PropertyName;
            string srid         = props[0].SRID;
            var    entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url  = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj    = JObject.Parse(resp.ResponsePayload);
                JArray  jArr    = jObj.GetValue(Constants.Value) as JArray;
                var     entity  = jArr.First as JObject;
                var     propVal = entity[propName]["coordinates"] as JArray;
                var     pt      = new Point(Convert.ToDouble(propVal[0]), Convert.ToDouble(propVal[1]));
                var     pts     = new Point[4]
                {
                    pt + new Point(1.0, 0.0),
                    pt + new Point(-1.0, 0.0),
                    pt + new Point(0.0, 1.0),
                    pt + new Point(0.0, -1.0)
                };
                url  = string.Format("{0}?$filter=geo.intersects({1}, geography'POLYGON(({2}, {3}, {4}, {5}, {6}))')", url, propName, pts[0], pts[1], pts[2], pts[3], pts[0]);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JObject.Parse(resp.ResponsePayload);
                    jArr = jObj.GetValue(Constants.Value) as JArray;
                    foreach (JObject et in jArr)
                    {
                        passed = this.IsIntersects(propName, new Polygon(pts), et);
                    }
                }
                else
                {
                    passed = false;
                }
            }

            return(passed);
        }
 /// <summary>
 ///     Convert JSON Data
 /// </summary>
 /// <param name="jsondata">JSON Object</param>
 /// <returns>List of Adverse Drug Events</returns>
 /// <remarks></remarks>
 public static List<AdverseDrugEvent> CnvJsonDataToList(JObject jsondata)
 {
     return jsondata.GetValue("results").
                     Select(obj => new AdverseDrugEvent
                                   {
                                       CompanyNumb = Utilities.GetJTokenString(obj, "companynumb"),
                                       SafetyReportId = Utilities.GetJTokenString(obj, "safetyreportid"),
                                       FulfillExpediteCriteria = Utilities.GetJTokenString(obj, "fulfillexpeditecriteria"),
                                       ReceiveDateFormat = Utilities.GetJTokenString(obj, "receivedateformat"),
                                       ReceiptDateFormat = Utilities.GetJTokenString(obj, "receiptdateformat"),
                                       PrimarySource = obj["primarysource"],
                                       ReceiveDate = Utilities.GetJTokenString(obj, "receivedate"),
                                       OccurCountry = Utilities.GetJTokenString(obj, "occurcountry"),
                                       Serious = Utilities.GetJTokenString(obj, "serious"),
                                       SeriousnessCongenitalAnomali = Utilities.GetJTokenString(obj, "seriousnesscongenitalanomali"),
                                       SeriousnessDeath = Utilities.GetJTokenString(obj, "seriousnessdeath"),
                                       SeriousnessDisabling = Utilities.GetJTokenString(obj, "seriousnessdisabling"),
                                       SeriousnessHospitalization = Utilities.GetJTokenString(obj, "seriousnesshospitalization"),
                                       SeriousnessLifeThreatening = Utilities.GetJTokenString(obj, "seriousnesslifethreatening"),
                                       SeriousnessOther = Utilities.GetJTokenString(obj, "seriousnessother"),
                                       SafetyReportVersion = Utilities.GetJTokenString(obj, "safetyreportversion"),
                                       Patient = PatientData.ConvertJsonDate(((JObject) Utilities.GetJTokenObject(obj, "patient")))
                                   }).
                     ToList();
 }
Example #31
0
        public string Header()
        {
            string result = "<li><a href=\"/Home/Index\"><i class=\"icon iconfont\">&#xe62e;</i>&nbsp;&nbsp;首页</a></li>";

            if (string.IsNullOrEmpty(HttpContext.User.Identity.Name))
            {
            }
            else
            {
                JObject json_user = Extension.Get_UserInfo(HttpContext.User.Identity.Name);
                string  sql       = @"select MODULEID,NAME,PARENTID,URL,SORTINDEX,IsLeaf,ICON from sysmodule t 
                where t.parentid='91a0657f-1939-4528-80aa-91b202a593ab' and t.MODULEID IN (select MODULEID FROM sys_moduleuser where userid='{0}')
                order by sortindex";
                sql = string.Format(sql, json_user.GetValue("ID"));
                DataTable dt1 = DBMgr.GetDataTable(sql);
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    string icon = string.Empty;
                    if (!string.IsNullOrEmpty(dt1.Rows[i]["ICON"] + ""))
                    {
                        icon = "<i class=\"icon iconfont\">&#x" + dt1.Rows[i]["ICON"] + ";</i>&nbsp;&nbsp;";
                    }
                    result += "<li><a>" + icon + dt1.Rows[i]["NAME"] + "</a>";
                    sql     = @"select MODULEID,NAME,PARENTID,URL,SORTINDEX,IsLeaf,ICON from sysmodule t where t.parentid='{0}'
                    and t.MODULEID IN (select MODULEID FROM sys_moduleuser where userid='{1}') order by sortindex";
                    sql     = string.Format(sql, dt1.Rows[i]["MODULEID"], json_user.GetValue("ID"));
                    DataTable dt2 = DBMgr.GetDataTable(sql);
                    if (dt2.Rows.Count > 0)
                    {
                        result += "<ul>";
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            icon = string.Empty;
                            if (!string.IsNullOrEmpty(dt2.Rows[j]["ICON"] + ""))
                            {
                                icon = "<i class=\"icon iconfont\">&#x" + dt2.Rows[j]["ICON"] + ";</i>&nbsp;&nbsp;";
                            }
                            if (string.IsNullOrEmpty(dt2.Rows[j]["URL"] + ""))
                            {
                                result += "<li><a>" + icon + dt2.Rows[j]["NAME"] + "</a>";
                            }
                            else
                            {
                                //result += "<li><a href=\"" + icon + dt2.Rows[j]["URL"] + "\">" + dt2.Rows[j]["NAME"] + "</a>";
                                //result += "<li><a href=\"" + dt2.Rows[j]["URL"] + "\">" + icon + dt2.Rows[j]["NAME"] + "</a>";

                                if (dt2.Rows[j]["URL"].ToString().IndexOf("?") > 0)
                                {
                                    result += "<li><a href=\""
                                              + dt2.Rows[j]["URL"].ToString().Substring(0, dt2.Rows[j]["URL"].ToString().IndexOf("?") + 1)
                                              + DecodeBase.Encrypt(dt2.Rows[j]["URL"].ToString().Substring(dt2.Rows[j]["URL"].ToString().IndexOf("?") + 1))
                                              + "\">" + icon + dt2.Rows[j]["NAME"] + "</a>";
                                }
                                else
                                {
                                    result += "<li><a href=\"" + dt2.Rows[j]["URL"] + "\">" + icon + dt2.Rows[j]["NAME"] + "</a>";
                                }
                            }
                            sql = @"select MODULEID,NAME,PARENTID,URL,SORTINDEX,IsLeaf,ICON from sysmodule t where t.parentid='{0}' 
                            and t.MODULEID IN (select MODULEID FROM sys_moduleuser where userid='{1}') order by sortindex";
                            sql = string.Format(sql, dt2.Rows[j]["MODULEID"], json_user.GetValue("ID"));
                            DataTable dt3 = DBMgr.GetDataTable(sql);
                            if (dt3.Rows.Count > 0)
                            {
                                result += "<ul>";
                                for (int k = 0; k < dt3.Rows.Count; k++)
                                {
                                    icon = string.Empty;
                                    if (!string.IsNullOrEmpty(dt3.Rows[k]["ICON"] + ""))
                                    {
                                        icon = "<i class=\"icon iconfont\">&#x" + dt3.Rows[k]["ICON"] + ";</i>&nbsp;&nbsp;";
                                    }
                                    if (string.IsNullOrEmpty(dt3.Rows[k]["URL"] + ""))
                                    {
                                        result += "<li><a>" + icon + dt3.Rows[k]["NAME"] + "</a></li>";
                                    }
                                    else
                                    {
                                        //result += "<li><a href=\"" + dt3.Rows[k]["URL"] + "\">" + icon + dt3.Rows[k]["NAME"] + "</a></li>";
                                        if (dt3.Rows[k]["URL"].ToString().IndexOf("?") > 0)
                                        {
                                            result += "<li><a href=\""
                                                      + dt3.Rows[k]["URL"].ToString().Substring(0, dt3.Rows[k]["URL"].ToString().IndexOf("?") + 1)
                                                      + DecodeBase.Encrypt(dt3.Rows[k]["URL"].ToString().Substring(dt3.Rows[k]["URL"].ToString().IndexOf("?") + 1))
                                                      + "\">" + icon + dt3.Rows[k]["NAME"] + "</a>";
                                        }
                                        else
                                        {
                                            result += "<li><a href=\"" + dt3.Rows[k]["URL"] + "\">" + icon + dt3.Rows[k]["NAME"] + "</a>";
                                        }
                                    }
                                }
                                result += "</ul></li>";
                            }
                            else
                            {
                                result += "</li>";
                            }
                        }
                        result += "</ul></li>";
                    }
                    else
                    {
                        result += "</li>";
                    }
                }
            }
            return(result);
        }
Example #32
0
        public static T GetState <T>(this JObject?state, Type type, string key, Func <T> defaultValue)
        {
            var item = state?.GetValue(key, StringComparison.OrdinalIgnoreCase);

            return(item != null ? (T)item.ToObject(type, CreateSerializer()) ! : defaultValue());
        }
Example #33
0
 public DivisionAnimatedNode(int tag, JObject config, NativeAnimatedNodesManager manager)
     : base(tag, config)
 {
     _manager    = manager;
     _inputNodes = config.GetValue("input", StringComparison.Ordinal).ToObject <int[]>();
 }
 internal static string GetAdaptiveInputId(JObject input) => input?.GetValue(AdaptiveProperties.Id)?.ToString();
            /// <summary>
            ///     Converts JSON Data to List
            /// </summary>
            /// <param name="jsondata">JSON Object Data</param>
            /// <returns>List of Recall Data</returns>
            /// <remarks></remarks>
            public static List<ResultRecall> CnvJsonDataToList(JObject jsondata)
            {
                var result = new List<ResultRecall>();

                foreach (var obj in jsondata.GetValue("results"))
                {
                    var tmp = new ResultRecall();

                    tmp.City = (obj["city"]).ToString();
                    tmp.Classification = (obj["classification"]).ToString();
                    tmp.Code_info = (obj["code_info"]).ToString();
                    tmp.Country = (obj["country"]).ToString();
                    tmp.Distribution_Pattern = (obj["distribution_pattern"]).ToString();
                    tmp.Event_Id = (obj["event_id"]).ToString();
                    tmp.Initial_Firm_Notification = (obj["initial_firm_notification"]).ToString();
                    //tmp.openfda = zz("city")
                    tmp.Product_Description = (obj["product_description"]).ToString();
                    tmp.Product_Quantity = (obj["product_quantity"]).ToString();
                    tmp.Product_Type = (obj["product_type"]).ToString();
                    tmp.Reason_For_Recall = (obj["reason_for_recall"]).ToString();
                    tmp.Recall_Initiation_Date = (obj["recall_initiation_date"]).ToString();
                    tmp.Recall_Number = (obj["recall_number"]).ToString();
                    tmp.Recalling_Firm = (obj["recalling_firm"]).ToString();
                    tmp.Report_Date = (obj["report_date"]).ToString();
                    tmp.State = (obj["state"]).ToString();
                    tmp.Status = (obj["status"]).ToString();
                    tmp.Voluntary_Mandated = (obj["voluntary_mandated"]).ToString();

                    result.Add(tmp);
                }

                return result;
            }