Ejemplo n.º 1
0
    protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
    {
        var uri = BuildUri(TokenEndpoint, new NameValueCollection
        {
            { "code", authorizationCode },
            { "client_id", _appId },
            { "client_secret", _appSecret },
            { "redirect_uri", returnUrl.GetLeftPart(UriPartial.Path) },
        });
        var             webRequest  = (HttpWebRequest)WebRequest.Create(uri);
        string          accessToken = null;
        HttpWebResponse response    = (HttpWebResponse)webRequest.GetResponse();
        // handle response from FB
        // this will not be a url with params like the first request to get the 'code'
        Encoding rEncoding = Encoding.GetEncoding(response.CharacterSet);

        using (StreamReader sr = new StreamReader(response.GetResponseStream(), rEncoding))
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
            var jConvert   = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(jsonObject));
            Dictionary <string, object> desirializedJsonObject = JsonConvert.DeserializeObject <Dictionary <string, object> >(jConvert.ToString());
            accessToken = desirializedJsonObject["access_token"].ToString();
        }
        return(accessToken);
    }
Ejemplo n.º 2
0
        /// <summary>
        /// 格式化Json数据
        /// </summary>
        /// <param name="jsonText"></param>
        /// <returns></returns>
        public static Dictionary <string, object> FormatJsonData(string jsonText)
        {
            System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();
            Dictionary <string, object> JsonData = (Dictionary <string, object>)s.DeserializeObject(jsonText);

            return(JsonData);
        }
Ejemplo n.º 3
0
        public static void Parse(string json, out List <Report> Reports)
        {
            Reports = new List <Report>();


            try
            {
                JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                serializer.MaxJsonLength = Int32.MaxValue;

                dynamic j = serializer.DeserializeObject(json);
                foreach (KeyValuePair <string, object> entry in j)
                {
                    foreach (KeyValuePair <string, object> item in (entry.Value as Dictionary <string, object>))
                    {
                        Reports.Add(new Report());
                        Reports.Last().Category = entry.Key;
                        Reports.Last().Grid     = item.Key;
                        Reports.Last().Likes    = (item.Value as Dictionary <string, object>).Values.ToArray()[0].ToString();
                        Reports.Last().Pictures = (item.Value as Dictionary <string, object>).Values.ToArray()[1].ToString();
                        Reports.Last().Location = (item.Value as Dictionary <string, object>).Values.ToArray()[2].ToString() + ", " + (item.Value as Dictionary <string, object>).Values.ToArray()[3].ToString();
                        Reports.Last().Rating   = double.Parse((item.Value as Dictionary <string, object>).Values.ToArray()[4].ToString());
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 4
0
        protected void RecuperarSenha(object sender, EventArgs e)
        {
            string     URL           = $"https://localhost:44323/api/ResetRequest/" + HttpUtility.UrlEncode(txtEsqSenha.Text);
            string     urlParameters = "";
            HttpClient client        = new HttpClient();

            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            JavaScriptSerializer        serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            HttpResponseMessage         response   = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
            Dictionary <string, Object> resultado  = (Dictionary <string, Object>)serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);

            if (response.IsSuccessStatusCode)
            {
                lblAvisoEsqSenha.Text = "Verifique seu Email";
            }
            else
            {
                lblAvisoEsqSenha.Text = "Email inválido";
            }
            divLog.Attributes.CssStyle.Add("display", "none");
            divCad.Attributes.CssStyle.Add("display", "none");
            divEsqSenha.Attributes.CssStyle.Add("display", "flex");
        }
Ejemplo n.º 5
0
    //从界面获取商品属性信息
    private IList <cPos.Model.ItemPropInfo> GetItemPropInfoFromView()
    {
        IList <cPos.Model.ItemPropInfo> itemPropInfos = new List <cPos.Model.ItemPropInfo>();
        var json = new System.Web.Script.Serialization.JavaScriptSerializer();

        object[] obj = (object[])json.DeserializeObject(this.hidItemProp.Value);
        for (int i = 0; i < obj.Length; i++)
        {
            var itemProp   = new cPos.Model.ItemPropInfo();
            var dictionary = (Dictionary <string, object>)obj[i];
            foreach (var item in dictionary)
            {
                if (item.Key == "PropertyDetailId")
                {
                    itemProp.PropertyDetailId = item.Value == null ? null : item.Value.ToString();
                }
                else if (item.Key == "PropertyCodeId")
                {
                    itemProp.PropertyCodeId = item.Value == null ? null : item.Value.ToString();
                }
                else if (item.Key == "PropertyCodeValue")
                {
                    itemProp.PropertyCodeValue = item.Value == null ? null : item.Value.ToString();
                }
            }
            itemPropInfos.Add(itemProp);
        }
        if (itemPropInfos.Count == 0)
        {
            return(null);
        }
        return(itemPropInfos);
    }
Ejemplo n.º 6
0
    //从界面获取商品价格信息
    private IList <cPos.Model.ItemPriceInfo> GetItemPriceInfoFromView()
    {
        IList <cPos.Model.ItemPriceInfo> itemPriceInfos = new List <cPos.Model.ItemPriceInfo>();
        var json = new System.Web.Script.Serialization.JavaScriptSerializer();

        object[] obj = (object[])json.DeserializeObject(this.hidItemPrice.Value);
        for (int i = 0; i < obj.Length; i++)
        {
            var itemPrice  = new cPos.Model.ItemPriceInfo();
            var dictionary = (Dictionary <string, object>)obj[i];
            foreach (var item in dictionary)
            {
                if (item.Key == "item_price_id")
                {
                    itemPrice.item_price_id = item.Value == null ? null : item.Value.ToString();
                }
                else if (item.Key == "item_price_type_id")
                {
                    itemPrice.item_price_type_id = item.Value == null ? null : item.Value.ToString();
                }
                else if (item.Key == "item_price")
                {
                    itemPrice.item_price = Convert.ToDecimal(item.Value ?? "0");
                }
            }
            itemPriceInfos.Add(itemPrice);
        }
        if (itemPriceInfos.Count == 0)
        {
            return(null);
        }
        return(itemPriceInfos);
    }
Ejemplo n.º 7
0
        static void LerArquivoJson(string pathJson)
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            using (StreamReader r = new StreamReader(pathJson))
            {
                string  json  = r.ReadToEnd();
                dynamic array = serializer.DeserializeObject(json);


                var conexao = new NpgsqlConnection("User ID=postgres;Password=123;Host=localhost;Port=5432;Database=Desafio;Pooling=true;");
                Console.Write("Iniciado");

                conexao.Open();

                Console.WriteLine();
                Console.WriteLine("");
                Console.WriteLine(serializer.Serialize(array));
                Console.WriteLine("");
                Console.WriteLine();

                conexao.Close();
            }
            Console.Write("Execução Finalizada!");
        }
Ejemplo n.º 8
0
    public string getToken2()
    {
        string s = "";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.connectedcommunity.org/api/v1.0/Authentication/Login");

        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method      = "POST";
        httpWebRequest.Headers.Add("HLIAMKey", HLIAMKey);
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            /* string json = "{\"username\":"+ username  +"," +
             *           "\"password\":"+ password +" , \"HLIAMKey\":"+HLIAMKey+"}";*/
            string json = "{\"username\":\"01786850\"," +
                          "\"password\":\"Password1\" , \"HLIAMKey\":\"194e4c0b-1dae-45c5-8d6e-749f12b21e8f\" }";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            s = streamReader.ReadToEnd();
        }
        var serializer2 = new JavaScriptSerializer();

        var     persons      = serializer2.Deserialize <List <HLToken> >(s);
        var     serializer   = new System.Web.Script.Serialization.JavaScriptSerializer();
        var     jsonObject12 = serializer.DeserializeObject(s);
        dynamic jsonObject   = serializer.Deserialize <dynamic>(s);

        s = jsonObject["Token"];

        return(s);
    }
Ejemplo n.º 9
0
    public string getToken()
    {
        string s = "";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.connectedcommunity.org/api/v1.0/Authentication/Login");

        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method      = "POST";
        httpWebRequest.Headers.Add("HLIAMKey", HLIAMKey);
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"username\":\"[email protected]\"," +
                          "\"password\":\"Password1\" , \"HLIAMKey\":\"2eb17c85-84d1-4888-b1b6-f5edf1a4396d\" }";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            s = streamReader.ReadToEnd();
        }
        var serializer2 = new JavaScriptSerializer();

        var     persons      = serializer2.Deserialize <List <HLToken> >(s);
        var     serializer   = new System.Web.Script.Serialization.JavaScriptSerializer();
        var     jsonObject12 = serializer.DeserializeObject(s);
        dynamic jsonObject   = serializer.Deserialize <dynamic>(s);

        s = jsonObject["Token"];

        return(s);
    }
Ejemplo n.º 10
0
        private bool GetUserDetails()
        {
            string     URL           = $"https://localhost:44323/api/Agente/{Program.userID}";
            string     urlParameters = "";
            HttpClient client        = new HttpClient();

            client.BaseAddress = new Uri(URL);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(Program.userToken);
            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            JavaScriptSerializer        serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            HttpResponseMessage         response   = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
            Dictionary <string, Object> resultado  = (Dictionary <string, Object>)serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);

            if (response.IsSuccessStatusCode)
            {
                if (resultado.ContainsKey("restaurant_id"))
                {
                    Program.userRID = int.Parse((string)resultado["restaurant_id"]);
                    return(true);
                }
                return(false);
            }
            else
            {
                return(false);
            }

            client.Dispose();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Get dictionary by Json
        /// Key = 属性名
        /// Value = 值
        /// </summary>
        /// <param name="sJson"></param>
        /// <returns></returns>
        public static Dictionary <string, object> GetDicByJson(string sJson)
        {
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var jsonData   = serializer.DeserializeObject(sJson) as Dictionary <string, object>;

            return(jsonData);
        }
Ejemplo n.º 12
0
        private Dictionary <string, string> GetPanelandSuffix(double x, double y)
        {
            Dictionary <string, string> dicPanelSuffix = new Dictionary <string, string>();


            string requestUri = strPanelSuffixURL;

            //Parameters to pass in to the REST call
            StringBuilder data = new StringBuilder();

            //return results as JSON
            data.AppendFormat("?f={0}", "json");
            //Input geometety (Address XY)
            data.AppendFormat("&geometry={0},{1}", x.ToString(), y.ToString());
            //Its a point
            data.AppendFormat("&geometryType={0}", "esriGeometryPoint");
            //Return in a web mercator projection, probbaly not needed
            data.AppendFormat("&inSR={0}", "102100");
            //Do point-n-poly intersection
            data.AppendFormat("&spatialRel={0}", "esriSpatialRelIntersects");
            //The attributes to return
            data.AppendFormat("&outFields={0},{1}", "FIRM_PAN", "SUFFIX");
            //Dont return the feature's geometry.  We dont need it and will slow the query
            data.AppendFormat("&returnGeometry={0}", "false");


            //Make the call and parse the results
            HttpWebRequest request = WebRequest.Create(requestUri + data) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string responseString = reader.ReadToEnd();


                System.Web.Script.Serialization.JavaScriptSerializer jss =
                    new System.Web.Script.Serialization.JavaScriptSerializer();

                IDictionary <string, object> results =
                    jss.DeserializeObject(responseString) as IDictionary <string, object>;

                if (results != null && results.ContainsKey("features"))
                {
                    IEnumerable <object> features = results["features"] as IEnumerable <object>;
                    foreach (IDictionary <string, object> feature in features)
                    {
                        IDictionary <string, object> attribute = feature["attributes"] as IDictionary <string, object>;
                        dicPanelSuffix.Add("FIRM_PAN", attribute["FIRM_PAN"].ToString());
                        dicPanelSuffix.Add("SUFFIX", attribute["SUFFIX"].ToString());
                        return(dicPanelSuffix);
                    }
                }
                return(null);
            }

            return(dicPanelSuffix);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 加载客户端状态
        /// </summary>
        /// <param name="clientState"></param>
        ///<remarks></remarks>
        protected override void LoadClientState(string clientState)
        {
            System.Web.Script.Serialization.JavaScriptSerializer js = JSONSerializerFactory.GetJavaScriptSerializer();

            object[] loadArray = (object[])js.DeserializeObject(clientState);

            if (null != loadArray)
            {
                ReceiveArray(this.items, loadArray);
            }
        }
Ejemplo n.º 14
0
        private Dictionary <string, double> Geocode(string strAddress)
        {
            string requestUri = strGeocoderURL;

            StringBuilder data = new StringBuilder();

            //return results as JSON
            data.AppendFormat("?f={0}", "json");
            //USA search only
            data.AppendFormat("&sourceCountry={0}", "USA");
            //Return coordinates as web mercator, need this projection for FEMA query
            data.AppendFormat("&outSR={0}", "102100");
            //text is the address text
            data.AppendFormat("&text={0}", System.Web.HttpUtility.UrlEncode(strAddress));

            //Make the call
            HttpWebRequest request = WebRequest.Create(requestUri + data) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string responseString = reader.ReadToEnd();

                // JavaScriptSerializer in System.Web.Extensions.dll
                System.Web.Script.Serialization.JavaScriptSerializer jss =
                    new System.Web.Script.Serialization.JavaScriptSerializer();

                IDictionary <string, object> results =
                    jss.DeserializeObject(responseString) as IDictionary <string, object>;

                if (results != null && results.ContainsKey("locations"))
                {
                    IEnumerable <object> candidates = results["locations"] as IEnumerable <object>;
                    foreach (IDictionary <string, object> candidate in candidates)
                    {
                        IDictionary <string, object> location = candidate["feature"] as IDictionary <string, object>;
                        IDictionary <string, object> geom     = location["geometry"] as IDictionary <string, object>;

                        Dictionary <string, double> dicCoords = new Dictionary <string, double>();

                        double x = decimal.ToDouble((decimal)geom["x"]);
                        double y = decimal.ToDouble((decimal)geom["y"]);

                        dicCoords.Add("x", x);
                        dicCoords.Add("y", y);

                        return(dicCoords);
                    }
                }
                return(null);
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Json转换为对象
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static T ToObject <T>(string obj)
 {
     try
     {
         System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
         T user = (T)jss.DeserializeObject(obj);
         return(user);
     }
     catch
     {
         return(default(T));;
     }
 }
Ejemplo n.º 16
0
    public void SetParm(string param, ReportDocument _ReportDocument)
    {
        // Desserializa dados.
        JavaScriptSerializer _Serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        // Cada collection dentro do objeto desserializado representa um parâmetro do relatório.
        foreach (object _ItemObject in (_Serializer.DeserializeObject(param) as object[]))
        {
            // Trata a collection dentro de cada item desserializado.
            ReportParameter _ReportParameter = new ReportParameter(_ItemObject as Dictionary <String, object>);
            // Atribui cada parâmetro.
            _ReportDocument.SetParameterValue(_ReportParameter.Name, _ReportParameter.Value);
        }
    }
Ejemplo n.º 17
0
    //从界面获取商品Sku信息
    private IList <cPos.Model.SkuInfo> GetItemSkuInfoFromView()
    {
        IList <cPos.Model.SkuInfo> itemSkuInfos = new List <cPos.Model.SkuInfo>();
        var json = new System.Web.Script.Serialization.JavaScriptSerializer();

        object[] obj = (object[])json.DeserializeObject(this.hidItemSku.Value);
        for (int i = 0; i < obj.Length; i++)
        {
            var itemSku    = new cPos.Model.SkuInfo();
            var dictionary = (Dictionary <string, object>)obj[i];
            foreach (var item in dictionary)
            {
                switch (item.Key)
                {
                case "sku_id": itemSku.sku_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_1_id": itemSku.prop_1_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_1_detail_id": itemSku.prop_1_detail_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_2_id": itemSku.prop_2_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_2_detail_id": itemSku.prop_2_detail_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_3_id": itemSku.prop_3_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_3_detail_id": itemSku.prop_3_detail_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_4_id": itemSku.prop_4_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_4_detail_id": itemSku.prop_4_detail_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_5_id": itemSku.prop_5_id = item.Value == null ? null : item.Value.ToString(); break;

                case "prop_5_detail_id": itemSku.prop_5_detail_id = item.Value == null ? null : item.Value.ToString(); break;

                case "barcode": itemSku.barcode = item.Value == null ? null : item.Value.ToString(); break;

                default: break;
                }
            }
            itemSkuInfos.Add(itemSku);
        }
        if (itemSkuInfos.Count == 0)
        {
            return(null);
        }
        return(itemSkuInfos);
    }
Ejemplo n.º 18
0
    private List <_param> getParam(dynamic data)
    {
        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        Dictionary <string, object> json = (Dictionary <string, object>)jss.DeserializeObject(data._param.ToString());
        List <_param> _params            = new List <_param>();

        foreach (var item in json)
        {
            _params.Add(new _param()
            {
                Kay = item.Key, Value = item.Value.ToString()
            });
        }

        return(_params);
    }
Ejemplo n.º 19
0
        public ConnectionParameter GetParameter()
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            dynamic result = serializer.DeserializeObject((String)this.descriptor.ConnectionParameter);

            this.connection = new ConnectionParameter();

            this.connection.Name     = result["DatabaseName"];
            this.connection.Host     = result["Host"];
            this.connection.Port     = result["Port"];
            this.connection.UserName = result["UserName"];
            this.connection.Password = result["Password"];

            return(this.connection);
        }
Ejemplo n.º 20
0
        public static int Procedimento(int num, bool tf)
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string  json      = @"{ ""nome"" : ""Vinicius"", ""sobrenome"" : ""Apolinario"", ""email"": ""*****@*****.**"" }";
            dynamic resultado = serializer.DeserializeObject(json);

            MessageBox.Show("  ==  Resultado da leitura do arquivo JSON  == ");
            foreach (KeyValuePair <string, object> entry in resultado)
            {
                var key   = entry.Key;
                var value = entry.Value as string;
                MessageBox.Show(String.Format("{0} : {1}", key, value));
            }

            MessageBox.Show(serializer.Serialize(resultado));
            return(0);
        }
Ejemplo n.º 21
0
        private string Get_FEMA_attribute(string url, double x, double y, string strAttribute)
        {
            string requestUri = url;

            StringBuilder data = new StringBuilder();

            data.AppendFormat("?f={0}", "json");
            data.AppendFormat("&geometry={0},{1}", x.ToString(), y.ToString());
            data.AppendFormat("&geometryType={0}", "esriGeometryPoint");
            data.AppendFormat("&inSR={0}", "102100");
            data.AppendFormat("&spatialRel={0}", "esriSpatialRelIntersects");
            data.AppendFormat("&outFields={0}", strAttribute);
            data.AppendFormat("&returnGeometry={0}", "false");


            //Make the call and parse the results
            HttpWebRequest request = WebRequest.Create(requestUri + data) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string responseString = reader.ReadToEnd();


                System.Web.Script.Serialization.JavaScriptSerializer jss =
                    new System.Web.Script.Serialization.JavaScriptSerializer();

                IDictionary <string, object> results =
                    jss.DeserializeObject(responseString) as IDictionary <string, object>;

                if (results != null && results.ContainsKey("features"))
                {
                    IEnumerable <object> features = results["features"] as IEnumerable <object>;
                    foreach (IDictionary <string, object> feature in features)
                    {
                        IDictionary <string, object> attribute = feature["attributes"] as IDictionary <string, object>;
                        return(attribute[strAttribute].ToString());
                    }
                }
                return("");
            }

            return("");
        }
Ejemplo n.º 22
0
        private void read()
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            using (StreamReader r = new StreamReader(this.fileName))
            {
                string json = r.ReadToEnd();
                this.array = serializer.DeserializeObject(json);

                /*
                 *  Print do array dynamic com o valor do arquivo json
                 *  Console.WriteLine("");
                 *  Console.WriteLine(serializer.Serialize(array));
                 *  Console.WriteLine("");
                 *  Console.ReadKey();
                 */
            }
        }
Ejemplo n.º 23
0
        static void Cabecalho()
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = @"{ ""Disciplina"" : ""Linguagens Formais"", ""Professor"" : ""Jackson Gomes"", ""Alunos"": ""[Ewerton Santiago, Marcos Mourão, Rodrigo Figueiredo, Wllynilson Carneiro]"" }";

            dynamic resultado = serializer.DeserializeObject(json);

            Console.WriteLine("-> -> Processamento de linguagem natural <- <-");
            Console.WriteLine("");
            foreach (KeyValuePair <string, object> entry in resultado)
            {
                var key   = entry.Key;
                var value = entry.Value as string;
                Console.WriteLine(String.Format("{0} : {1}", key, value));
            }

            Console.WriteLine("");
            Console.WriteLine(serializer.Serialize(resultado));
            Console.WriteLine("");
            Console.ReadKey();
        }
Ejemplo n.º 24
0
    public string getToken()
    {
        string s = "";

        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.connectedcommunity.org/api/v2.0/Authentication/Login");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";
            httpWebRequest.Headers.Add("HLIAMKey", "194e4c0b-1dae-45c5-8d6e-749f12b21e8f");
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                // string json = "{\"username\":\"[email protected]\"," +
                //           "\"password\":\"1000168\" , \"HLIAMKey\": \"67EE6ECE-2247-47E3-8994-F85BCF62AB2F\"}";

                string json = "{\"username\":\"01786850\"," +
                              "\"password\":\"Password1\" , \"HLIAMKey\": \"194e4c0b-1dae-45c5-8d6e-749f12b21e8f\"}";
                streamWriter.Write(json);
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                s = streamReader.ReadToEnd();
            }
            var serializer2 = new JavaScriptSerializer();

            var     persons      = serializer2.Deserialize <List <HLToken> >(s);
            var     serializer   = new System.Web.Script.Serialization.JavaScriptSerializer();
            var     jsonObject12 = serializer.DeserializeObject(s);
            dynamic jsonObject   = serializer.Deserialize <dynamic>(s);
            s = jsonObject["Token"];
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
        return(s);
    }
Ejemplo n.º 25
0
        public string GeoRankerGetSession(string email, string apiKey)
        {
            string resultSession = "";
            var    urlPartial    = "api/login.json?email=" + email + "&apikey=" + apiKey;

            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var response = client.GetStringAsync(urlPartial).Result;
                    if (response.Length > 0)
                    {
                        JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                        dynamic result = serializer.DeserializeObject(response);

                        foreach (KeyValuePair <string, object> entry in result)
                        {
                            if (entry.Key == "session")
                            {
                                resultSession = entry.Value.ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }


            return(resultSession);
        }
Ejemplo n.º 26
0
        public static async Task <List <Words> > Search(string searchTerm)
        {
            LanguageDetector detector = new LanguageDetector();

            detector.AddAllLanguages();

            HttpClient client    = new HttpClient();
            var        loginPage = await client.GetStringAsync("https://www.altmetric.com/explorer/login");

            Match  matchObject = Regex.Match(loginPage, @"name=""authenticity_token"" value=""(?<key>.+)""");
            string token       = string.Empty;

            if (matchObject.Success)
            {
                token = matchObject.Groups["key"].Value;
            }

            Dictionary <string, string> formFields = new Dictionary <string, string>()
            {
                { "email", "*****@*****.**" },
                { "password", "bigdatachallenge" },
                { "authenticity_token", token },
                { "commit", "Sign in" }
            };

            FormUrlEncodedContent content = new FormUrlEncodedContent(formFields);
            var response = await client.PostAsync("https://www.altmetric.com/explorer/login", content);

            var searchResults =
                await client.GetStringAsync("https://www.altmetric.com/explorer/json_data/research_outputs?q=" + searchTerm +
                                            "&scope=all");

            Console.WriteLine("A");

            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

            serializer.MaxJsonLength = Int32.MaxValue;
            dynamic papersDict = serializer.DeserializeObject(searchResults);

            List <Words> newsList = new List <Words>();

            List <Task <string> > taskList  = new List <Task <string> >();
            List <int>            scoreList = new List <int>();

            if (papersDict["outputs"].Length == 0)
            {
                return(newsList);
            }

            Console.WriteLine("B");

            for (int i = 0; i < Math.Min(10, papersDict["outputs"].Length); i++)
            {
                string altId = papersDict["outputs"][i]["id"].ToString();
                int    score = papersDict["outputs"][i]["score"];
                scoreList.Add(score);
                taskList.Add(client.GetStringAsync("https://api.altmetric.com/v1/fetch/id/" + altId + "?key=ef2e9b9961415ba4b6510ec82c3e9cba"));
            }

            int counter = 0;

            while (taskList.Count > 0)
            {
                Console.WriteLine(counter);
                Task <string> firstFinishedTask = await Task.WhenAny(taskList);

                taskList.Remove(firstFinishedTask);
                string detailsText = await firstFinishedTask;

                dynamic details = serializer.DeserializeObject(detailsText);

                if (details["posts"].ContainsKey("news") && details["posts"]["news"].Length > 0)
                {
                    for (int j = 0; j < Math.Min(3, details["posts"]["news"].Length); j++)
                    {
                        if (details["posts"]["news"][j].ContainsKey("title") &&
                            details["posts"]["news"][j].ContainsKey("url"))
                        {
                            string title = details["posts"]["news"][j]["title"];

                            if (detector.Detect(title) == "en" && details["posts"]["news"][j]["url"] != null)
                            {
                                var request = new HttpRequestMessage(HttpMethod.Head, details["posts"]["news"][j]["url"]);
                                try
                                {
                                    var validityResponse = await client.SendAsync(request);

                                    if (validityResponse.IsSuccessStatusCode)
                                    {
                                        Words newsArticle = new Words(title, details["posts"]["news"][j]["url"], scoreList[counter], WordType.Article);
                                        newsList.Add(newsArticle);
                                    }
                                }
                                catch (HttpRequestException e)
                                {
                                }
                            }
                        }
                    }
                }

                if (details["posts"].ContainsKey("blogs") && details["posts"]["blogs"].Length > 0)
                {
                    string title = details["posts"]["blogs"][0]["title"];

                    if (detector.Detect(title) == "en" && details["posts"]["blogs"][0]["url"] != null)
                    {
                        var request = new HttpRequestMessage(HttpMethod.Head, details["posts"]["blogs"][0]["url"]);
                        try
                        {
                            var validityResponse = await client.SendAsync(request);

                            if (validityResponse.IsSuccessStatusCode)
                            {
                                Words blogPost = new Words(title, details["posts"]["blogs"][0]["url"], scoreList[counter], WordType.Blog);
                                newsList.Add(blogPost);
                            }
                        }
                        catch (HttpRequestException e)
                        {
                        }
                    }
                }

                if (details["posts"].ContainsKey("video") && details["posts"]["video"].Length > 0)
                {
                    string title = details["posts"]["video"][0]["title"];

                    if (detector.Detect(title) == "en" && details["posts"]["video"][0]["url"] != null)
                    {
                        var request = new HttpRequestMessage(HttpMethod.Head, details["posts"]["video"][0]["url"]);
                        try
                        {
                            var validityResponse = await client.SendAsync(request);

                            if (validityResponse.IsSuccessStatusCode)
                            {
                                Words video = new Words(title, details["posts"]["video"][0]["url"], scoreList[counter], WordType.Video);
                                newsList.Add(video);
                            }
                        }
                        catch (HttpRequestException e)
                        {
                        }
                    }
                }
                counter++;
            }

            client.Dispose();

            return(newsList);
        }
Ejemplo n.º 27
0
        private Dictionary<string, double> Geocode(string strAddress)
        {
            string requestUri = strGeocoderURL;

            StringBuilder data = new StringBuilder();
            //return results as JSON
            data.AppendFormat("?f={0}", "json");
            //USA search only
            data.AppendFormat("&sourceCountry={0}", "USA");
            //Return coordinates as web mercator, need this projection for FEMA query
            data.AppendFormat("&outSR={0}", "102100");
            //text is the address text
            data.AppendFormat("&text={0}", System.Web.HttpUtility.UrlEncode(strAddress));

            //Make the call
            HttpWebRequest request = WebRequest.Create(requestUri + data) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string responseString = reader.ReadToEnd();

                // JavaScriptSerializer in System.Web.Extensions.dll
                System.Web.Script.Serialization.JavaScriptSerializer jss =
                    new System.Web.Script.Serialization.JavaScriptSerializer();

                IDictionary<string, object> results =
                    jss.DeserializeObject(responseString) as IDictionary<string, object>;

                if (results != null && results.ContainsKey("locations"))
                {
                    IEnumerable<object> candidates = results["locations"] as IEnumerable<object>;
                    foreach (IDictionary<string, object> candidate in candidates)
                    {

                        IDictionary<string, object> location = candidate["feature"] as IDictionary<string, object>;
                        IDictionary<string, object> geom = location["geometry"] as IDictionary<string, object>;

                        Dictionary<string, double> dicCoords = new Dictionary<string, double>();

                        double x = decimal.ToDouble((decimal)geom["x"]);
                        double y = decimal.ToDouble((decimal)geom["y"]);

                        dicCoords.Add("x", x);
                        dicCoords.Add("y", y);

                        return dicCoords;
                    }
                }
                return null;
            }
        }
Ejemplo n.º 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["userID"] != null)
            {
                divConectado.Visible           = true;
                divDesconectado.Visible        = false;
                divsidenavConectado.Visible    = true;
                divsidenavDesconectado.Visible = false;
                divConectado.Attributes.CssStyle.Add("display", "flex");
                divDesconectado.Attributes.CssStyle.Add("display", "none");
                divsidenavConectado.Attributes.CssStyle.Add("display", "flex");
                divsidenavDesconectado.Attributes.CssStyle.Add("display", "none");
                string     URL           = $"https://localhost:44323/api/Agente/" + Session["userID"];
                string     urlParameters = "";
                HttpClient client        = new HttpClient();
                client.BaseAddress = new Uri(URL);

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue((string)Session["userToken"]);
                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                // List data response.
                JavaScriptSerializer        serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                HttpResponseMessage         response   = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
                Dictionary <string, Object> resultado  = (Dictionary <string, Object>)serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);

                if (response.IsSuccessStatusCode)
                {
                    if (resultado.ContainsKey("client_name"))
                    {
                        lblBemVindo.Text        = "Bem vindo(a) " + resultado["client_name"];
                        lblBemVindoSidenav.Text = "Bem vindo(a) " + resultado["client_name"];
                    }
                }
            }
            divLog.Attributes.CssStyle.Add("display", "none");
            divCad.Attributes.CssStyle.Add("display", "none");
            divEsqSenha.Attributes.CssStyle.Add("display", "none");
        }
Ejemplo n.º 29
0
        private Dictionary<string, string> GetPanelandSuffix(double x, double y)
        {
            Dictionary<string, string> dicPanelSuffix = new Dictionary<string, string>();

            string requestUri = strPanelSuffixURL;

            //Parameters to pass in to the REST call
            StringBuilder data = new StringBuilder();
            //return results as JSON
            data.AppendFormat("?f={0}", "json");
            //Input geometety (Address XY)
            data.AppendFormat("&geometry={0},{1}",x.ToString(),y.ToString());
            //Its a point
            data.AppendFormat("&geometryType={0}", "esriGeometryPoint");
            //Return in a web mercator projection, probbaly not needed
            data.AppendFormat("&inSR={0}", "102100");
            //Do point-n-poly intersection
            data.AppendFormat("&spatialRel={0}", "esriSpatialRelIntersects");
            //The attributes to return
            data.AppendFormat("&outFields={0},{1}", "FIRM_PAN","SUFFIX");
            //Dont return the feature's geometry.  We dont need it and will slow the query
            data.AppendFormat("&returnGeometry={0}", "false");

            //Make the call and parse the results
            HttpWebRequest request = WebRequest.Create(requestUri + data) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string responseString = reader.ReadToEnd();

                System.Web.Script.Serialization.JavaScriptSerializer jss =
                    new System.Web.Script.Serialization.JavaScriptSerializer();

                IDictionary<string, object> results =
                    jss.DeserializeObject(responseString) as IDictionary<string, object>;

                if (results != null && results.ContainsKey("features"))
                {
                    IEnumerable<object> features = results["features"] as IEnumerable<object>;
                     foreach (IDictionary<string, object> feature in features)
                     {
                         IDictionary<string, object> attribute = feature["attributes"] as IDictionary<string, object>;
                         dicPanelSuffix.Add("FIRM_PAN", attribute["FIRM_PAN"].ToString());
                         dicPanelSuffix.Add("SUFFIX", attribute["SUFFIX"].ToString());
                         return dicPanelSuffix;
                     }
                }
                return null;

            }

            return dicPanelSuffix;
        }
Ejemplo n.º 30
0
        //this Function gets all profile and data from the user contact list and saved in a cash system

        void GetProfileWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (GetProfileWorker.CancellationPending == true)
                {
                    e.Cancel = true;
                }
                else
                {
                    string aa            = File.ReadAllText(Settings.UserID);
                    string bb            = File.ReadAllText(Settings.SessionID);
                    string cc            = File.ReadAllText(Settings.UserID);
                    string TextID        = aa.Replace("\r\n", "");
                    string sessionIDText = bb.Replace("\r\n", "");
                    string userprofile   = bb.Replace("\r\n", "");

                    using (var client = new WebClient())
                    {
                        var values = new NameValueCollection();
                        values["user_id"]         = TextID;
                        values["user_profile_id"] = userprofile;
                        values["s"] = sessionIDText;

                        var    ChatusersListresponse       = client.UploadValues(Settings.WebsiteUrl + "/app_api.php?type=get_users_list", values);
                        var    ChatusersListresponseString = Encoding.Default.GetString(ChatusersListresponse);
                        var    dictChatusersList           = new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(ChatusersListresponseString);
                        string ApiStatus = dictChatusersList["api_status"].ToString();

                        if (ApiStatus == "200")
                        {
                            var    s            = new System.Web.Script.Serialization.JavaScriptSerializer();
                            var    gg           = dictChatusersList["users"];
                            var    Profiles     = JObject.Parse(ChatusersListresponseString).SelectToken("users").ToString();
                            Object obj          = s.DeserializeObject(Profiles);
                            JArray Profileusers = JArray.Parse(Profiles);

                            string PostProfiles = "";

                            foreach (var ProfileUser in Profileusers)
                            {
                                JObject ProfileUserdata = JObject.FromObject(ProfileUser);
                                var     Profile_User_ID = ProfileUserdata["user_id"].ToString();
                                PostProfiles += Profile_User_ID + ",";
                            }

                            //Result of all profiles and friends of the user Account splited by (,)
                            string result = PostProfiles;

                            values["user_id"]  = TextID;
                            values["usersIDs"] = result;
                            values["s"]        = sessionIDText;
                            var    ProfileListPost = client.UploadValues(Settings.WebsiteUrl + "app_api.php?type=get_multi_users", values);
                            var    ProfileListPostresponseString = Encoding.Default.GetString(ProfileListPost);
                            var    dictProfileList = new JavaScriptSerializer().Deserialize <Dictionary <string, object> >(ProfileListPostresponseString);
                            string ApiStatus2      = dictProfileList["api_status"].ToString();

                            if (ApiStatus2 == "200")
                            {
                                gg           = dictProfileList["users"];
                                Profiles     = JObject.Parse(ProfileListPostresponseString).SelectToken("users").ToString();
                                obj          = s.DeserializeObject(Profiles);
                                Profileusers = JArray.Parse(Profiles);
                                foreach (var ProfileUser in Profileusers)
                                {
                                    JObject ProfileUserdata = JObject.FromObject(ProfileUser);

                                    var Profile_User_ID = ProfileUserdata["user_id"].ToString();
                                    var path            = Settings.FolderDestination + Settings.SiteName + @"\Data\" + Profile_User_ID + @"\";
                                    var path2           = Settings.FolderDestination + Settings.SiteName + @"\Data\" + Profile_User_ID + @"\" + Profile_User_ID + ".json";
                                    if (CashSystem(path2) == "0")
                                    {
                                        DirectoryInfo di   = Directory.CreateDirectory(path);
                                        string        Json = ProfileUser.ToString();
                                        System.IO.File.WriteAllText(path2, Json);
                                    }
                                    else
                                    {
                                        string Json = ProfileUser.ToString();
                                        System.IO.File.WriteAllText(path2, Json);
                                    }
                                    var    Profile_Cover   = ProfileUserdata["cover"].ToString();
                                    string lastItemOfSplit = Profile_Cover.Split('/').Last();
                                    var    Coverpath       = Settings.FolderDestination + Settings.SiteName + @"\ImageCash\" + Profile_User_ID + @"\";
                                    var    Coverpath2      = Coverpath + lastItemOfSplit;
                                    if (CashSystem(Coverpath2) == "0")
                                    {
                                        if (!Directory.Exists(Coverpath))
                                        {
                                            DirectoryInfo di = Directory.CreateDirectory(Coverpath);
                                        }

                                        client.DownloadFile(Profile_Cover, Coverpath2);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 31
0
        protected void Login(object sender, EventArgs e)
        {
            lblEmailAvisoLogin.Text = "";
            lblSenhaAvisoLogin.Text = "";
            bool camposPreenchidos = true;

            if (String.IsNullOrWhiteSpace(txtEmailLogin.Text))
            {
                lblEmailAvisoLogin.Text = "Insira um email para efetuar o login";
                camposPreenchidos       = false;
                divLog.Attributes.CssStyle.Add("display", "flex");
                divCad.Attributes.CssStyle.Add("display", "none");
                divEsqSenha.Attributes.CssStyle.Add("display", "none");
            }
            if (String.IsNullOrWhiteSpace(txtSenhaLogin.Text))
            {
                lblSenhaAvisoLogin.Text = "Insira uma senha para efetuar o login";
                camposPreenchidos       = false;
                divLog.Attributes.CssStyle.Add("display", "flex");
                divCad.Attributes.CssStyle.Add("display", "none");
                divEsqSenha.Attributes.CssStyle.Add("display", "none");
            }
            if (camposPreenchidos)
            {
                string     URL           = $"https://localhost:44323/api/AgenteToken/{Uri.EscapeUriString(txtEmailLogin.Text)}/{Uri.EscapeUriString(txtSenhaLogin.Text)}";
                string     urlParameters = "";
                HttpClient client        = new HttpClient();
                client.BaseAddress = new Uri(URL);

                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                // List data response.
                JavaScriptSerializer        serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                HttpResponseMessage         response   = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
                Dictionary <string, Object> resultado  = (Dictionary <string, Object>)serializer.DeserializeObject(response.Content.ReadAsStringAsync().Result);

                if (response.IsSuccessStatusCode)
                {
                    Session["userID"]    = int.Parse((string)resultado["id"]);
                    Session["userToken"] = (string)resultado["token"];
                    divLog.Attributes.CssStyle.Add("display", "none");

                    divConectado.Visible           = true;
                    divDesconectado.Visible        = false;
                    divsidenavConectado.Visible    = true;
                    divsidenavDesconectado.Visible = false;
                    divConectado.Attributes.CssStyle.Add("display", "flex");
                    divDesconectado.Attributes.CssStyle.Add("display", "none");
                    divsidenavConectado.Attributes.CssStyle.Add("display", "flex");
                    divsidenavDesconectado.Attributes.CssStyle.Add("display", "none");
                    string     URL2           = $"https://localhost:44323/api/Agente/" + Session["userID"];
                    string     urlParameters2 = "";
                    HttpClient client2        = new HttpClient();
                    client2.BaseAddress = new Uri(URL2);

                    client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue((string)Session["userToken"]);
                    // Add an Accept header for JSON format.
                    client2.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    // List data response.
                    JavaScriptSerializer        serializer2 = new System.Web.Script.Serialization.JavaScriptSerializer();
                    HttpResponseMessage         response2   = client2.GetAsync(urlParameters2).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
                    Dictionary <string, Object> resultado2  = (Dictionary <string, Object>)serializer2.DeserializeObject(response2.Content.ReadAsStringAsync().Result);

                    if (response2.IsSuccessStatusCode)
                    {
                        if (resultado2.ContainsKey("client_name"))
                        {
                            lblBemVindo.Text = "Bem vindo(a) " + resultado2["client_name"];
                        }
                    }
                }
                else
                {
                    if ((string)resultado["error"] == "AUTH_ERROR")
                    {
                        lblSenhaAvisoLogin.Text = "Usuário ou senha incorreto";
                    }
                    divLog.Attributes.CssStyle.Add("display", "flex");
                    divCad.Attributes.CssStyle.Add("display", "none");
                    divEsqSenha.Attributes.CssStyle.Add("display", "none");
                }

                client.Dispose();
                //lblEmailAvisoLogin.Text = "Beleza";
            }
        }
Ejemplo n.º 32
0
        public void ProcessRequest(HttpContext context)
        {
            AFWACsession session = context.Session["AFWACSESSION"] as AFWACsession;

            context.Response.ContentType = "text/plain";

            System.Web.Script.Serialization.JavaScriptSerializer UTIL =
                new System.Web.Script.Serialization.JavaScriptSerializer();

            string JSONidsOfSelRows = (context.Request.Params["wserowids"]);
            string JSONnewval       = (context.Request.Params["newvector"]);
            string JSONoldval       = (context.Request.Params["oldvector"]);

            Array ARRmultiselOldEditStat =
                UTIL.DeserializeObject
                    (context.Request.Params["multiselOldEditStat"]) as Array;

            // will be either ADD or DEL
            string rolelinksIncrementalUpdateType = (context.Request.Params["mode"]);

            // edittype will be either EDIT or CLONE or NEWFRESH
            string edittype = (context.Request.Params["edittype"]);

            Object OBJarrofids = UTIL.DeserializeObject(JSONidsOfSelRows);
            Array  arrofids    = OBJarrofids as Array;

            // This will be used for any situation where there is only one row
            // being worked on (the most common situation).
            int IDwserow = -1;

            if (edittype != "NEWFRESH")
            {
                IDwserow = int.Parse(arrofids.GetValue(0) as string);
            }
            // arrofids.GetLength()   .GetValue(idx)   etc.


            /////////////////////////////////////
            //
            // MAKE CHANGES TO THE FIELDS OF THE VECTOR
            //

            if (JSONnewval != "--@--NOCHANGE--@--")
            {
                //
                // There was a change in the entitlements
                //

                // In this case, there is only one row that is being worked on.
                // ASSERT(arrofids.GetLength() == 1



                Object deserresult = UTIL.DeserializeObject(JSONnewval);
                System.Collections.Generic.Dictionary <string, object> THERESULT =
                    deserresult as System.Collections.Generic.Dictionary <string, object>;


                // Check to ensure nothing else in workspace has very same vector

                bool changeWasOnlyCosmetic = false;

                string targetchecksum =
                    HELPERS.ENTCHECKSUM
                    (
                        THERESULT["StandardActivity"] as string,
                        THERESULT["RoleType"] as string,
                        THERESULT["Application"] as string,
                        THERESULT["System"] as string,
                        THERESULT["Platform"] as string,
                        THERESULT["EntitlementName"] as string,
                        THERESULT["EntitlementValue"] as string,
                        "",
                        THERESULT["AuthObjValue"] as string,
                        THERESULT["FieldSecName"] as string,
                        THERESULT["FieldSecValue"] as string,
                        THERESULT["Level4SecName"] as string,
                        THERESULT["Level4SecValue"] as string);


                int existingID =
                    HELPERS.FindEntitlementByChecksum(targetchecksum);


                // The retval is -1 if nothing found with that exact vector
                if (existingID >= 0)
                {
                    // If we get here, an existing row was found with exact same checksum.
                    // If it is the same row as this one being edited, then this
                    // means that only non-significant fields were changed, e.g. commentary.

                    if ((existingID == IDwserow) && (edittype == "EDIT"))
                    {
                        changeWasOnlyCosmetic = true;
                    }
                    else
                    {
                        // Whoops, something else has the same vector.
                        // LOGIC ERROR HERE: Assumes checksum for two different vectors will never be identical.
                        context.Response.Write("An entitlement with that exact set of characteristics already exists.");
                        context.Response.StatusCode = 500;
                        return;
                    }
                }


                switch (edittype)
                {
                case "EDIT":
                    Object deserresultOLD = UTIL.DeserializeObject(JSONoldval);
                    System.Collections.Generic.Dictionary <string, object> THEOLDRESULT =
                        deserresultOLD as System.Collections.Generic.Dictionary <string, object>;

                    HELPERS.EntitlementVectorUpdate
                        (IDwserow, THERESULT, THEOLDRESULT, changeWasOnlyCosmetic,
                        session.idUser, context.Request.ServerVariables["REMOTE_ADDR"], UTIL
                        );

                    break;

                case "CLONE":
                case "NEWFRESH":
                    IDwserow = HELPERS.EntitlementCreate(THERESULT, targetchecksum);
                    context.Response.Write(IDwserow.ToString());
                    break;
                }
            }
        }
Ejemplo n.º 33
0
        private string Get_FEMA_attribute(string url, double x, double y, string strAttribute)
        {
            string requestUri = url;

            StringBuilder data = new StringBuilder();
            data.AppendFormat("?f={0}", "json");
            data.AppendFormat("&geometry={0},{1}", x.ToString(), y.ToString());
            data.AppendFormat("&geometryType={0}", "esriGeometryPoint");
            data.AppendFormat("&inSR={0}", "102100");
            data.AppendFormat("&spatialRel={0}", "esriSpatialRelIntersects");
            data.AppendFormat("&outFields={0}", strAttribute);
            data.AppendFormat("&returnGeometry={0}", "false");

            //Make the call and parse the results
            HttpWebRequest request = WebRequest.Create(requestUri + data) as HttpWebRequest;

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());

                string responseString = reader.ReadToEnd();

                System.Web.Script.Serialization.JavaScriptSerializer jss =
                    new System.Web.Script.Serialization.JavaScriptSerializer();

                IDictionary<string, object> results =
                    jss.DeserializeObject(responseString) as IDictionary<string, object>;

                if (results != null && results.ContainsKey("features"))
                {
                    IEnumerable<object> features = results["features"] as IEnumerable<object>;
                    foreach (IDictionary<string, object> feature in features)
                    {
                        IDictionary<string, object> attribute = feature["attributes"] as IDictionary<string, object>;
                        return attribute[strAttribute].ToString();
                    }
                }
                return "";

            }

            return "" ;
        }