public void Should_register_converters_when_asked()
        {
            // Given
            var defaultSerializer = new JavaScriptSerializer();
            var configuration = new JsonConfiguration(Encoding.UTF8, new[] { new TestConverter() }, new[] { new TestPrimitiveConverter() }, false, false);

            // When
            var serializer = new JavaScriptSerializer(configuration, true, GlobalizationConfiguration.Default);

            var data =
                new TestData()
                {
                    ConverterData =
                        new TestConverterType()
                        {
                            Data = 42,
                        },

                    PrimitiveConverterData =
                        new TestPrimitiveConverterType()
                        {
                            Data = 1701,
                        },
                };

            const string ExpectedJSON = @"{""converterData"":{""dataValue"":42},""primitiveConverterData"":1701}";

            // Then
            serializer.Serialize(data).ShouldEqual(ExpectedJSON);

            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
        }
    public MtSmsResp sendSMSReq(MtSmsReq mtSmsReq)
    {
        StreamWriter requestWriter;
        MtSmsResp mtSmsResp=null;

        try
        {
            var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;

            if (webRequest != null)
            {
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";
                using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter.Write(mtSmsReq.ToString());
                }
            }

            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);
            String jsonResponseString = responseReader.ReadToEnd();

            JavaScriptSerializer javascriptserializer = new JavaScriptSerializer();
            mtSmsResp = javascriptserializer.Deserialize<MtSmsResp>(jsonResponseString);
        }
        catch (Exception ex)
        {
            throw new SdpException(ex);
        }
        return mtSmsResp;
    }
 public void ProcessRequest(HttpContext context)
 {
     MoSmsResp moSmsResp = null;
     string jsonString="";
     context.Response.ContentType = "application/json";
     try
     {
         byte[] PostData = context.Request.BinaryRead(context.Request.ContentLength);
         jsonString = Encoding.UTF8.GetString(PostData);
         JavaScriptSerializer json_serializer = new JavaScriptSerializer();
         MoSmsReq moSmsReq = json_serializer.Deserialize<MoSmsReq>(jsonString);
         moSmsResp = GenerateStatus(true);
         onMessage(moSmsReq);
     }
     catch (Exception)
     {
         moSmsResp = GenerateStatus(false);
     }
     finally
     {
         if (jsonString.Equals(""))
             context.Response.Write(APPLICATION_RUNING_MESSAGE);
         else
             context.Response.Write(moSmsResp.ToString());
     }
 }
        public void Should_not_register_converters_when_not_asked()
        {
            // Given
            var defaultSerializer = new JavaScriptSerializer();

            // When
            var serializer = new JavaScriptSerializer(JsonConfiguration.Default, GlobalizationConfiguration.Default);

            var data =
                new TestData()
                {
                    ConverterData =
                        new TestConverterType()
                        {
                            Data = 42,
                        },

                    PrimitiveConverterData =
                        new TestPrimitiveConverterType()
                        {
                            Data = 1701,
                        },
                };

            const string ExpectedJSON = @"{""converterData"":{""data"":42},""primitiveConverterData"":{""data"":1701}}";

            // Then
            serializer.Serialize(data).ShouldEqual(ExpectedJSON);

            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
        }
Esempio n. 5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Object user = Session["userid"];
        if (user != null)
        {
            String userid = (String)user;
            try
            {
                String filename = Server.MapPath("~/User_Data/" + userid + ".js");
                String jsonData = File.ReadAllText(filename);

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                RegData data = serializer.Deserialize<RegData>(jsonData);

                name.Text = data.name;
                Userid.Text = userid;
                userName.Text = data.userName;
                password.Text = data.password;
                userProfile.Text = data.userProfile;
                state.Text = data.state;
                politic.Text = data.politic;
                foreach (string interest in data.interests)
                {
                    interests.Text += interest+",";
                }
                String imageurl = "~/User_Images/" + userid + ".jpg";
                Image.ImageUrl = imageurl;
            }
            catch (IOException exn) {
                Response.Redirect("Error.aspx?userid=" + userid + "&errid=lookup");
            }
        }
        else {
            Response.Redirect("Login.aspx");
        }


        /*
        HttpCookie cookie = Request.Cookies.Get("Registration");
        if (cookie != null)
        {
            name.Text = cookie["name"];
            userName.Text = cookie["userName"];
            password.Text = cookie["password"];
            userProfile.Text = cookie["userProfile"];
            state.Text = cookie["state"];
            politic.Text = cookie["politic"];
            interests.Text = cookie["interests"];
        }
        else {
            name.Text = "<Undefined name>";
            userName.Text = "<Undefined user name>";
            password.Text = "<Undefined password>";
            userProfile.Text = "<Undefined user profile>";
            state.Text = "<Undefined state>";
            politic.Text = "<Undefined politic>";
            interests.Text = "<Undefined interests>";
        }
         * */
    }
Esempio n. 6
0
    private static Dictionary<string, string> ParsePayload(string[] args)
    {
        int payloadIndex=-1;
         for (var i = 0; i < args.Length; i++)
            {
                Console.WriteLine(args[i]);
                if (args[i]=="-payload")
                 {
                    payloadIndex = i;
                    break;
                 }
            }
         if (payloadIndex == -1)
        {
           Console.WriteLine("Payload is empty");
           Environment.Exit(0);
        }

         if (payloadIndex >= args.Length-1)
        {
            Console.WriteLine("No payload value");
            Environment.Exit(0);
        }

         string json = File.ReadAllText(args[payloadIndex+1]);
         var jss = new JavaScriptSerializer();
         Dictionary<string, string> values = jss.Deserialize<Dictionary<string, string>>(json);
         return values;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Admin"] == null || Session["Admin"].ToString() != "1")
            Response.Redirect("login.aspx");
        if (Request.QueryString["id"] == null)
            Response.Redirect("AboutListing.aspx");
        id = Request.QueryString["id"].ToString();

        PageHeader = Util.GetTemplate("Admin_header");
        string json = Util.GetFileContent("data");
        var serializer = new JavaScriptSerializer();
        serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
        obj = serializer.Deserialize(json, typeof(object));

        if (!IsPostBack)
        {
            bool exists = false;
            foreach (dynamic obj1 in obj["Portfolio"])
            {
                if (obj1["id"] == id)
                {
                    txtTitle.Text = obj1["title"];
                    txtDescription.Text = obj1["description"];
                    txtSiteLink.Text = obj1["sitelink"];
                    txtClient.Text = obj1["client"];
                    txtDate.Text = obj1["date"];
                    txtService.Text = obj1["service"];
                    imgImage.ImageUrl = "../" + obj1["image"];
                    exists = true;
                }
            }
            if(!exists)
                Response.Redirect("PortfolioListing.aspx");
        }
    }
Esempio n. 8
0
 public void parseJson(String HtmlResult)
 {
     var serializer = new JavaScriptSerializer();
     serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
     dynamic obj = serializer.Deserialize(HtmlResult, typeof(object));
     Console.WriteLine(obj.meta);
 }
    /// <summary>
    /// This method called when the page is loaded into the browser. This method requests input stream and parses it to get message counts.
    /// </summary>
    /// <param name="sender">object, which invoked this method</param>
    /// <param name="e">EventArgs, which specifies arguments specific to this method</param>
    protected void Page_Load(object sender, EventArgs e)
    {

        System.IO.Stream stream = Request.InputStream;

        this.receivedDeliveryStatusFilePath = ConfigurationManager.AppSettings["ReceivedDeliveryStatusFilePath"];
        if (string.IsNullOrEmpty(this.receivedDeliveryStatusFilePath))
            this.receivedDeliveryStatusFilePath = "~\\DeliveryStatus.txt";

        string count = ConfigurationManager.AppSettings["NumberOfDeliveryStatusToStore"];
        if (!string.IsNullOrEmpty(count))
            this.numberOfDeliveryStatusToStore = Convert.ToInt32(count);

        if (null != stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(bytes, 0, (int)stream.Length);
            string responseData = Encoding.ASCII.GetString(bytes);

            JavaScriptSerializer serializeObject = new JavaScriptSerializer();
            DeliveryStatusNotification message = (DeliveryStatusNotification)serializeObject.Deserialize(responseData, typeof(DeliveryStatusNotification));

            if (null != message)
            {
                this.SaveMessage(message);
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        int quoteId = Convert.ToInt32(Request.Params["quote_id"]);

        Quote quote = new Quote(quoteId);

        // Remove the old items from this quote
        quote.ClearItems();

        // Get the new quote items, will be a JSON array in the POST field
        string quoteItemsString = Request.Params["quote_items"];
        if ( String.IsNullOrEmpty(Request.Params["quote_items"]) || String.IsNullOrEmpty(Request.Params["quote_id"])){
            Response.StatusCode = 500;
            Response.End();
        }
        // Deserialise the JSON into QuoteItem objects and create each one (insert into DB)
        JavaScriptSerializer jsl = new JavaScriptSerializer();
        List<QuoteItem> quoteItems =(List<QuoteItem>)jsl.Deserialize(quoteItemsString, typeof(List<QuoteItem>));
        foreach (QuoteItem item in quoteItems)
            item.Create();

        // Get the quote and update the fields from the form on the ViewQuote page.
        quote.Revision++;
        quote.DiscountPercent = Convert.ToDouble(Request.Params["discount_percent"]);
        quote.DiscountPercent24 = Convert.ToDouble(Request.Params["discount_percent_24"]);
        quote.DiscountPercent36 = Convert.ToDouble(Request.Params["discount_percent_36"]);
        quote.DiscountPercentSetup = Convert.ToDouble(Request.Params["discount_percent_setup"]);
        quote.DiscountWritein = Convert.ToDouble(Request.Params["discount_writein"]);
        quote.Title = Request.Params["title"];
        quote.LastChange = DateTime.Now;
        quote.Save();
    }
Esempio n. 11
0
 public static dynamic GEOCodeAddress(String Address)
 {
     var address = String.Format("http://maps.google.com/maps/api/geocode/json?address={0}&sensor=false", Address.Replace(" ", "+"));
     var result = new System.Net.WebClient().DownloadString(address);
     var jss = new JavaScriptSerializer();
     return jss.Deserialize<dynamic>(result);
 }
    public static void Main(string[] args)
    {
        // API Key, password and host provided as arguments
        if(args.Length != 3) {
          Console.WriteLine("Usage: ApplicantTracking <key> <password> <host>");
          Environment.Exit(1);
        }

        var API_Key = args[0];
        var API_Password = args[1];
        var host = args[2];

        var url = "https://" + host + "/remote/jobs/active.json";

        using (var wc = new WebClient()) {

        //Attach crendentials to WebClient header
        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(API_Key + ":" + API_Password));
        wc.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        var results = serializer.Deserialize<Job[]>(wc.DownloadString(url));

        foreach(var job in results) {
          //Print results
          Console.WriteLine(job.Title + " (" + job.URL + ")");
        }
          }
    }
Esempio n. 13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        String str = HttpContext.Current.Request.Url.AbsoluteUri;
        String userId = str.Substring(str.LastIndexOf("=")+1);
        try
        {
            String filename = Server.MapPath("~/User_Data/" + userId + ".js");
            String jsonData = File.ReadAllText(filename);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            RegData data = serializer.Deserialize<RegData>(jsonData);

            name.Text = data.name;
            userid.Text = userId;

            String imageurl = "~/User_Images/" + userId + ".jpg";
            userImage.ImageUrl = imageurl;


        }
        catch (IOException exn)
        {
            Response.Redirect("Error.aspx?userid=" + userId + "&errid=lookup");
        }
    }
    public void SubmitSecretQuestion(object sender, EventArgs e)
    {
        string centGetUserAttributes = Session["UserAttributes"].ToString();
        var jssGetUserAttributes = new JavaScriptSerializer();
        Dictionary<string, dynamic> centGetUserAttribrutes_Dict = jssGetUserAttributes.Deserialize<Dictionary<string, dynamic>>(centGetUserAttributes);

        string strUuid = centGetUserAttribrutes_Dict["Result"]["Uuid"];

        string strSetQuestionJSON = @"{""ID"":""" + strUuid + @""",""securityquestion"":""" + SecretQuestion.Text + @""",""questionanwser"":""" + SecretAnswer.Text + @"""}";

        Centrify_API_Interface centSetQuestion = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentSetSecurityQuestionURL, strSetQuestionJSON);
        var jssSetQuestion = new JavaScriptSerializer();
        Dictionary<string, dynamic> centSetQuestion_Dict = jssSetQuestion.Deserialize<Dictionary<string, dynamic>>(centSetQuestion.returnedResponse);

        if (centSetQuestion_Dict["success"].ToString() != "True")
        {
            FailureText.Text = centSetQuestion_Dict["success"].ToString();
            ErrorMessage.Visible = true;
        }
        else
        {
            SecretQuestion_Div.Visible = false;
            AccountOverview.Visible = true;
        }
    }
    public override void ProcessRequest(HttpContext context, Match match)
    {
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        // Environmental Setup
        PccConfig.LoadConfig("pcc.config");

        string origDocument = GetStringFromUrl(context, match, "DocumentID");

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        // Perform an HTTP GET request to retrieve properties about the viewing session from PCCIS.
        // The properties will include an identifier of the source document that will be used below
        // to locate the name of file where the markups for the current document were written.
        string uriString = PccConfig.ImagingService + "/ViewingSession/u" + HttpUtility.UrlEncode(origDocument);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriString);
        request.Method = "GET";
        request.Headers.Add("acs-api-key", PccConfig.ApiKey);

        // Send request to PCCIS and get response
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        string responseBody = null;
        using (StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
        {
            responseBody = sr.ReadToEnd();
        }

        // Deserialize the JSON response into a new DocumentProperties instance, which will provide
        // the original document name (a local file name in this case) which was specified by this application
        // during the original POST of the document.
        ViewingSessionProperties viewingSessionProperties = serializer.Deserialize<ViewingSessionProperties>(responseBody);
        int i = 1;

        //location of the saved markup xmls. This could be on webserver or network storage or database.
        DirectoryInfo di = new DirectoryInfo(PccConfig.MarkupFolder);
        FileInfo[] rgFiles = di.GetFiles("*.xml");
        string documentMarkupId = string.Empty;
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        char[] charsToTrim = { ','};

        viewingSessionProperties.origin.TryGetValue("documentMarkupId", out documentMarkupId);
        foreach (FileInfo fi in rgFiles)
        {
            if (fi.Name.Contains(documentMarkupId + "_" + viewingSessionProperties.attachmentIndex))
            {
                string fileName = fi.Name;
                fileName = fi.Name.Replace(documentMarkupId + "_" + viewingSessionProperties.attachmentIndex + "_", "").Replace(".xml", "");
                sb1.AppendFormat("{{\"ID\": \"{0}\", \"annotationName\": \"{1}\", \"annotationLabel\": \"{2}\"}},", i.ToString(), fi.Name, fileName);
                i++;
            }
        }

        sb1.ToString().TrimEnd(charsToTrim);
        sb.Append("{\"annotationFiles\":[");
        sb.Append(sb1.ToString().TrimEnd(charsToTrim));
        sb.Append("] }");
        context.Response.Write(sb.ToString());
    }
    protected override IList Update(String key, String value)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        IList<int> list = new List<int>();
        list.Add(DirectoryManager.UpdateEntry(key, js.Deserialize<Directory>(value)));

        return (IList)list;
    }
Esempio n. 17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string sURL;
        sURL = "http://192.168.1.40:9101/api/query";

        string stringData = "select data in (now -5minutes, now) limit 10 where Path = '/FH-RPi02/Meter31/Energy'";

        //stringData = "select data in ('7/1/2013', '7/2/2013') limit 10 where Path = '/RasPi1/Meter29/Energy'";
        stringData = "select data in (now -5minutes, now) limit 5 streamlimit 1 where Metadata/Location/Building='Faculty Housing'";
        HttpWebRequest req = WebRequest.Create(sURL) as HttpWebRequest;
        IWebProxy iwprxy = WebRequest.GetSystemWebProxy();
            req.Proxy = iwprxy;

        req.Method = "POST";
        req.ContentType = "";

        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(stringData);

        req.ContentLength = data.Length;

        Stream os = req.GetRequestStream();
        os.Write(data, 0, data.Length);
        os.Close();

        HttpWebResponse response = req.GetResponse() as HttpWebResponse;

        Stream objStream;
                objStream = req.GetResponse().GetResponseStream();

        StreamReader objReader = new StreamReader(objStream);

        var jss = new JavaScriptSerializer();

        string sline = objReader.ReadLine();

        //sline = objReader.ReadLine();
        var f1 = jss.Deserialize<dynamic>(sline);

        var f21 = f1[0];
        var f2 = f21["uuid"];
        var f3 = f21["Readings"];

            timeSt = new int[f3.Length];
            val = new double[f3.Length];
            timeSeries = new string[f3.Length];

            for (int i = 0; i < f3.Length; i++)
            {
                var f4 = f3[i];
                timeSt[i] = Convert.ToInt32( f4[0]/1000);
                val[i] = Convert.ToDouble( f4[1]);
            }

            timeSeries = Utilitie_S.TimeFormatterBar(timeSt);

        response.Close();
    }
        public void ThenIShouldBeAbleToSeeAllMyRatingsForMyQuery()
        {
            var responseString = _response.GetBodyAsString();
            var jss = new JavaScriptSerializer();
            var result = jss.Deserialize<List<Dictionary<string, object>>>(responseString);

            Assert.IsNotEmpty(responseString);
            Assert.AreEqual(HttpStatusCode.OK, _response.StatusCode);
        }
        public void Should_deserialize_tuple()
        {
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new[] { new TupleConverter() });

            string body = @"{""item1"":10,""item2"":11}";
            Tuple<int, int> result = serializer.Deserialize<Tuple<int, int>>(body);
            result.ToString().ShouldEqual("(10, 11)");
        }
        public void Should_deserialize_string_tuple()
        {
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new[] { new TupleConverter() });

            string body = @"{""item1"":""Hello"",""item2"":""World"",""item3"":42}";
            var result = serializer.Deserialize<Tuple<string, string, int>>(body);
            result.ToString().ShouldEqual("(Hello, World, 42)");
        }
        public void ThenIShouldReceiveTempCredentials()
        {
            var responseString = response.GetBodyAsString();
            var jss = new JavaScriptSerializer();
            var result = jss.Deserialize<Dictionary<string, object>>(responseString);

            Assert.AreEqual(36, ((string)result["TokenKey"]).Length);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Esempio n. 22
0
 public override void OnMessage(string json)
 {
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     MensagemVO item = serializer.Deserialize<MensagemVO>(json);
     //terminar
     //this.EnviarMensagem();
     
     
 }
        public void ThenIShouldBeAbleToSeeMyCreatedAccount()
        {
            var responseString = _response.GetBodyAsString();
            var jss = new JavaScriptSerializer();
            var result = jss.Deserialize<Dictionary<string, object>>(responseString);

            Assert.IsNotNull(result["AccountKey"]);
            Assert.AreEqual(HttpStatusCode.OK, _response.StatusCode);
        }
Esempio n. 24
0
    public override void OnMessage(string json)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        MensagemVO vo = (MensagemVO)serializer.Deserialize<MensagemVO>(json);

        if (vo.IdConversa.ToString() == string.Empty)
            ArmazenarSocket(vo.IdUsuario.ToString());
        else
            SalvarMensagem(vo);       
    }
Esempio n. 25
0
    public void select()
    {
        string data=HttpUtil.GetReqStrValue("data");
        JavaScriptSerializer jss = new JavaScriptSerializer();

        Dictionary<string, object> dataMap=jss.Deserialize<Dictionary<string, object>>(data);
        objList= selectReverse(dataMap, new List<Dictionary<string, object>>(),null);

        Response.Write(jss.Serialize(objList));
    }
Esempio n. 26
0
 public async Task requestProject()
 {
     HttpResponseMessage response = await this.Client.GetAsync(String.Format("/api/project/{0}", this.ProjectId));
     if (response.IsSuccessStatusCode)
     {
         string jsonText = await response.Content.ReadAsStringAsync();
         JavaScriptSerializer jsonSerialization = new JavaScriptSerializer();
         var data = jsonSerialization.Deserialize<Dictionary<string,dynamic>>(jsonText);
         Console.WriteLine("\t{0} ({1})", data["properties"]["title"], data["properties"]["id"]);
     }
 }
Esempio n. 27
0
    /*
    * On page load if query string 'code' is present, invoke get_access_token
    */
    public void Page_Load(object sender, EventArgs e)
    {
        try
        {

            // Get the api key, secre key and short code values for the application from web.config.

            api_key = ConfigurationManager.AppSettings["api_key"].ToString();
            secret_key = ConfigurationManager.AppSettings["secret_key"].ToString();
            short_code = ConfigurationManager.AppSettings["short_code"].ToString();
            auth_code = Request["code"].ToString();
            // If query string contains auth code, extract it and invoke get_access_token
            if (auth_code != "")
            {
                // OAuthentication oauth_obj = new OAuthentication();
                get_access_code(api_key, secret_key, auth_code);
                access_token = Session["access_token"].ToString();

                //Get the access token from the json response
                JavaScriptSerializer deserializer_object = new JavaScriptSerializer();
                Test myDeserializedObj = (Test)deserializer_object.Deserialize(access_token, typeof(Test));
                access_token = myDeserializedObj.access_token.ToString();

                //Display the access token in UI text box
                txtAccTokNewSubs.Text = access_token.ToString();
                txtAccTokSubsDet.Text = access_token.ToString();
                txtAcceTokCommitTrns.Text = access_token.ToString();
            }
            /*
             * get the redirect response action
             */
            if (Request["action"] == "UserConfirmed")
            {
                Response.Write("User has confirmed AOC");
            }

            if (Request["action"] == "UserCancelled")
            {

                Response.Write("User has cancelled AOC");
            }

            if (Request["action"] == "Status")
            {

                Response.Write("Status callback URL has been invoked");
            }

        }
        catch (Exception ert)
        {
            // Response.Write(ert.ToString());
        }
    }
        public void Should_deserialize_type_with_tuples()
        {
            // When
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new[] { new TupleConverter() });

            // Then
            var typeWithTuple = serializer.Deserialize<TypeWithTuple>(@"{""value"":{""item1"":10,""item2"":11}}");
            typeWithTuple.Value.Item1.ShouldEqual(10);
            typeWithTuple.Value.Item2.ShouldEqual(11);
        }
Esempio n. 29
0
    public static List<Record> grabRecords()
    {
        string recordsJson = grabRecordsJson();
        if (recordsJson.Equals("")) {
            return null;
        }

        JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
        List<Record> records = javaScriptSerializer.Deserialize<List<Record>>(grabRecordsJson());
        return records;
    }
Esempio n. 30
0
 static public void Main(string[] args)
 {
     string payloadFilePath = Environment.GetEnvironmentVariable("PAYLOAD_FILE");
     string payload = File.ReadAllText(payloadFilePath);
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     IDictionary<string,string> json = serializer.Deserialize <Dictionary<string, string>>(payload);
     foreach (string key in json.Keys)
     {
         Console.WriteLine( key + " = " + json[key] );
     }
 }
Esempio n. 31
0
        protected void clbAtualizar_Callback(object source, DevExpress.Web.CallbackEventArgs e)
        {
            //**********************************
            //* É uma chamada de inicializãção?
            //**********************************
            if (e.Parameter == string.Empty)
            {
                //**************
                //* Declarações
                //**************
                Int32 CodigoUsuario = 0;

                //***************************
                //* Edição ou novo registro?
                //***************************
                if (Request.QueryString["codigo"] == null)
                {
                    CodigoUsuario = 0;
                }
                else
                {
                    CodigoUsuario = Convert.ToInt32(Request.QueryString["codigo"]);
                }

                //******************************
                //* Popula dados no objeto JSON
                //******************************
                PopulaJSON();

                //*******************************
                //* Devolve estrutura JSON vazia
                //*******************************
                e.Result = new JavaScriptSerializer().Serialize(oJSON);
            }
            else
            {
                //*************************
                //* Deserializa requisição
                //*************************
                JavaScriptSerializer oSerializer = new JavaScriptSerializer();
                oJSON = oSerializer.Deserialize <Config_Fields>(e.Parameter);

                //******************************
                //* Realiza operação solicitada
                //******************************
                switch (oJSON.Parametros["Operacao"])
                {
                case "Salvar_Registro":

                    //*************************************
                    //* Coleta código da nova oportunidade
                    //*************************************
                    oJSON = Salvar_Registro(oJSON);

                    //*******************************
                    //* Devolve estrutura JSON vazia
                    //*******************************
                    e.Result = new JavaScriptSerializer().Serialize(oJSON);
                    break;

                case "Teste_SMTP":

                    //*************************************
                    //* Coleta código da nova oportunidade
                    //*************************************
                    oJSON = Salvar_Registro(oJSON);

                    //*************************************
                    //* Coleta código da nova oportunidade
                    //*************************************
                    oJSON = Teste_SMTP(oJSON);

                    //*******************************
                    //* Devolve estrutura JSON vazia
                    //*******************************
                    e.Result = new JavaScriptSerializer().Serialize(oJSON);
                    break;
                }
            }
        }
Esempio n. 32
0
        private JsonSettings DeserializeSettings(string rawData)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();

            return(js.Deserialize <JsonSettings>(rawData));
        }
        public async Task <IDictionary <string, object>[]> GetClients()
        {
            var clients = new List <IDictionary <string, object> >();

            try
            {
                if (!IsLoggedIn)
                {
                    await Login();
                }

                var jsonSer = new JavaScriptSerializer();

                var jsonParams = new Dictionary <string, object>();

                var currentCommand = jsonSer.Serialize(jsonParams);

                jsonParams.Clear();

                // Create the request and setup for the post.
                string strRequest     = string.Format("{0}api/s/{1}/stat/sta", Server, SiteName);
                var    httpWebRequest = (HttpWebRequest)WebRequest.Create(strRequest);
                httpWebRequest.ContentType = "application/json;charset=UTF-8";
                httpWebRequest.Method      = WebRequestMethods.Http.Post;
                httpWebRequest.ServicePoint.Expect100Continue = false;
                httpWebRequest.CookieContainer = Cookies;

                // Set the callback to handle the post of data.
                var postStream = await httpWebRequest.GetRequestStreamAsync();

                byte[] byteArray = Encoding.UTF8.GetBytes(currentCommand);

                // Write to the request stream.
                await postStream.WriteAsync(byteArray, 0, byteArray.Length);

                await postStream.FlushAsync();

                postStream.Close();


                // Now read the reponse and process the data.
                var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseText = await streamReader.ReadToEndAsync();

                    jsonParams = jsonSer.Deserialize <Dictionary <string, object> >(responseText);

                    if (!jsonParams.ContainsKey("data"))
                    {
                        throw new Exception("Error getting clients");
                    }

                    var list = (ArrayList)jsonParams["data"];

                    foreach (Dictionary <string, object> data in list)
                    {
                        clients.Add(data);
                    }
                    ;
                }
            }
            catch (Exception)
            {
                await LogOut();

                throw;
            }

            return(clients.ToArray());
        }
    /// <summary>
    /// This function invokes api SpeechToText to convert the given wav amr file and displays the result.
    /// </summary>
    private void ConvertToSpeech(string parEndPoint, string parAccessToken, string parXspeechContext, string parXArgs, string parSpeechFilePath, bool parChunked)
    {
        Stream     postStream      = null;
        FileStream audioFileStream = null;

        try
        {
            audioFileStream = new FileStream(parSpeechFilePath, FileMode.Open, FileAccess.Read);
            BinaryReader reader     = new BinaryReader(audioFileStream);
            byte[]       binaryData = reader.ReadBytes((int)audioFileStream.Length);
            reader.Close();
            audioFileStream.Close();
            if (null != binaryData)
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(string.Empty + parEndPoint);
                httpRequest.Headers.Add("Authorization", "Bearer " + parAccessToken);
                httpRequest.Headers.Add("X-SpeechContext", parXspeechContext);
                if (!string.IsNullOrEmpty(parXArgs))
                {
                    httpRequest.Headers.Add("X-Arg", parXArgs);
                }
                string contentType = this.MapContentTypeFromExtension(Path.GetExtension(parSpeechFilePath));
                httpRequest.ContentLength = binaryData.Length;
                httpRequest.ContentType   = contentType;
                httpRequest.Accept        = "application/json";
                httpRequest.Method        = "POST";
                httpRequest.KeepAlive     = true;
                httpRequest.SendChunked   = parChunked;
                postStream = httpRequest.GetRequestStream();
                postStream.Write(binaryData, 0, binaryData.Length);
                postStream.Close();

                HttpWebResponse speechResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (StreamReader streamReader = new StreamReader(speechResponse.GetResponseStream()))
                {
                    string speechRequestResponse = streamReader.ReadToEnd();

                    /*if (string.Compare(SpeechContext.SelectedValue, "TV") == 0)
                     * {
                     *  speechErrorMessage = speechRequestResponse;
                     *  streamReader.Close();
                     *  return;
                     * }*/
                    if (!string.IsNullOrEmpty(speechRequestResponse))
                    {
                        JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                        SpeechResponse       deserializedJsonObj   = (SpeechResponse)deserializeJsonObject.Deserialize(speechRequestResponse, typeof(SpeechResponse));
                        if (null != deserializedJsonObj)
                        {
                            speechResponseData   = new SpeechResponse();
                            speechResponseData   = deserializedJsonObj;
                            speechSuccessMessage = "true";
                            //speechErrorMessage = speechRequestResponse;
                        }
                        else
                        {
                            speechErrorMessage = "Empty speech to text response";
                        }
                    }
                    else
                    {
                        speechErrorMessage = "Empty speech to text response";
                    }

                    streamReader.Close();
                }
            }
            else
            {
                speechErrorMessage = "Empty speech to text response";
            }
        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }

            speechErrorMessage = errorResponse;
        }
        catch (Exception ex)
        {
            speechErrorMessage = ex.ToString();
        }
        finally
        {
            if (null != postStream)
            {
                postStream.Close();
            }
        }
    }
 public bool CredentialsCheck(string email, string password, out User loggedInUser)
 {
     string message = wc.DownloadString($"{wc.BaseAddress}GetUser?email={email}&password={password}");
     loggedInUser = serializer.Deserialize<User>(message);
     return true;
 }
Esempio n. 36
0
        private void AnalysisDailyBroadcastData(IPrimitiveMap map)
        {
            string       packetype = map["PACKETTYPE"].ToString();
            OperatorData op        = new OperatorData();

            op.OperatorType = packetype;
            op.ModuleType   = map["Cmdtag"].ToString();
            JavaScriptSerializer Serializer = new JavaScriptSerializer();

            switch (packetype)
            {
            case "AddDailyBroadcast":
            case "ModifyDailyBroadcast":
                string data = map["data"].ToString();
                switch (op.ModuleType)
                {
                case "1":        //节目切播
                    JsonstructureDeal(ref data);
                    ////因为有ValueType缘故 不能反序列化
                    string[]       dataArray = data.Split(',');
                    ChangeProgram_ pp        = new ChangeProgram_();

                    pp.Program = new DailyCmdChangeProgram();


                    foreach (var item in dataArray)
                    {
                        if (item.Contains("ItemID"))
                        {
                            pp.ItemID = item.Split(':')[1];
                        }

                        if (item.Contains("B_Daily_cmd_tag"))
                        {
                            // pp.B_Daily_cmd_tag = Convert.ToByte(item.Split(':')[1]);
                        }
                        if (item.Contains("Program"))
                        {
                            pp.Program.NetID = (short)Convert.ToInt32(item.Split(':')[2]);
                        }
                        if (item.Contains("TSID"))
                        {
                            pp.Program.TSID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("ServiceID"))
                        {
                            pp.Program.ServiceID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("PCR_PID"))
                        {
                            pp.Program.ServiceID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("Program_PID"))
                        {
                            pp.Program.Program_PID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("Priority"))
                        {
                            pp.Program.Priority = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("Volume"))
                        {
                            pp.Program.Volume = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("EndTime"))
                        {
                            DateTime dd = Convert.ToDateTime(item.Split(':')[1]);
                            pp.Program.EndTime = dd;
                        }
                        if (item.Contains("B_Address_type"))
                        {
                            pp.Program.B_Address_type = (byte)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("list_Terminal_Address"))
                        {
                            string   tmp   = item.Split(':')[1].Substring(1);
                            string   tmp2  = tmp.Substring(0, tmp.Length - 4);
                            string[] array = tmp2.Split(',');

                            pp.Program.list_Terminal_Address = new List <string>(array);
                        }
                    }



                    List <ChangeProgram_> listCP = new List <ChangeProgram_>();
                    listCP.Add(pp);

                    op.Data = listCP;
                    break;

                case "3":        //播放控制
                    JsonstructureDeal(ref data);
                    List <PlayCtrl_> listPC = Serializer.Deserialize <List <PlayCtrl_> >(data);
                    op.Data = listPC;
                    break;

                case "4":        //输出控制
                    JsonstructureDeal(ref data);
                    List <OutSwitch_> listOS = Serializer.Deserialize <List <OutSwitch_> >(data);
                    op.Data = listOS;
                    break;

                case "5":        //RDS编码数据透传
                    JsonstructureDeal(ref data);
                    List <RdsTransfer_> listRT = Serializer.Deserialize <List <RdsTransfer_> >(data);
                    op.Data = listRT;
                    break;
                }

                break;

            case "DelDailyBroadcast":
                string ItemList = map["ItemIDList"].ToString();
                op.Data = ItemList;
                break;
            }
            DataDealHelper.MyEvent(op);
        }
Esempio n. 37
0
        private void AnalysisEBMIndexData(IPrimitiveMap map)
        {
            string       packetype = map["PACKETTYPE"].ToString();
            OperatorData op        = new OperatorData();

            op.OperatorType = packetype;

            switch (packetype)
            {
            case "AddEBMIndex":
                EBMIndexTmp tmp = new EBMIndexTmp();
                tmp.BL_details_channel_indicate = map["BL_details_channel_indicate"].ToString();
                tmp.IndexItemID = map["IndexItemID"].ToString();
                tmp.S_EBM_id    = map["S_EBM_id"].ToString().Substring(0, 30);
                #region   特殊处理EBM_ID 凑到30个长度
                //if (map["S_EBM_id"].ToString().Length < 30)
                //{
                //    tmp.IndexItemID = map["S_EBM_id"].ToString() + "000000000000";
                //}
                //else
                //{
                //    tmp.S_EBM_id = map["S_EBM_id"].ToString().Substring(0, 30);
                //}
                #endregion



                tmp.S_EBM_original_network_id = (SingletonInfo.GetInstance().OriginalNetworkId + 1).ToString();
                tmp.S_EBM_start_time          = map["S_EBM_start_time"].ToString();
                tmp.S_EBM_end_time            = map["S_EBM_end_time"].ToString();
                tmp.S_EBM_type             = map["S_EBM_type"].ToString();
                tmp.S_EBM_class            = map["S_EBM_class"].ToString();
                tmp.S_EBM_level            = map["S_EBM_level"].ToString();
                tmp.List_EBM_resource_code = map["List_EBM_resource_code"].ToString();

                tmp.DesFlag = map["DesFlag"].ToString();
                tmp.S_details_channel_transport_stream_id = map["S_details_channel_transport_stream_id"].ToString();
                tmp.S_details_channel_program_number      = map["S_details_channel_program_number"].ToString();
                tmp.S_details_channel_PCR_PID             = map["S_details_channel_PCR_PID"].ToString();

                tmp.DeliverySystemDescriptor = new object();
                if (tmp.DesFlag == "true")
                {
                    string data = map["DeliverySystemDescriptor"].ToString();
                    string pp1  = data.Substring(1);
                    string dd1  = pp1.Substring(0, pp1.Length - 1);
                    if (data.Contains("B_FEC_inner"))    //有线传送系统描述符
                    {
                        tmp.DeliverySystemDescriptor = (object)JsonConvert.DeserializeObject <CableDeliverySystemDescriptortmp>(dd1);
                        tmp.descriptor_tag           = 68;
                    }
                    else
                    {
                        //地面传送系统描述符
                        tmp.DeliverySystemDescriptor = (object)JsonConvert.DeserializeObject <TerristrialDeliverySystemDescriptortmp>(dd1);
                        tmp.descriptor_tag           = 90;
                    }
                }
                tmp.List_ProgramStreamInfo = new List <ProgramStreamInfotmp>();

                if (tmp.BL_details_channel_indicate == "true")
                {
                    string data = map["List_ProgramStreamInfo"].ToString();


                    JavaScriptSerializer Serializer = new JavaScriptSerializer();

                    List <ProgramStreamInfotmp> objs = Serializer.Deserialize <List <ProgramStreamInfotmp> >(data);

                    foreach (ProgramStreamInfotmp item in objs)
                    {
                        //if (item.Descriptor2 != null)
                        //{
                        //    //dynamic a = item.Descriptor2;
                        //    //Descriptor2 niemi = new Descriptor2();
                        //    //string[] pp = ((string)a[0]["B_descriptor"]).Split(' ');
                        //    //List<byte> byteList = new List<byte>();

                        //    //foreach (var it in pp)
                        //    //{
                        //    //    if (it != "")
                        //    //    {
                        //    //        byteList.Add((byte)Convert.ToInt32(it));
                        //    //    }

                        //    //}

                        //    //niemi.B_descriptor = byteList.ToArray();


                        //    //if (a[0]["B_descriptor_tag"] != "")
                        //    //{
                        //    //    niemi.B_descriptor_tag = (byte)a[0]["B_descriptor_tag"];
                        //    //}

                        //    //item.Descriptor2 = niemi;

                        //}
                        //else
                        //{

                        //    #region  特殊处理 Descriptor2  不能为空 当BL_details_channel_indicate==true时  20180524
                        //    //  dynamic a = item.Descriptor2;
                        //    Descriptor2 niemi = new Descriptor2();
                        //    //niemi.B_descriptor = new byte[]{0,0};
                        //    //niemi.B_descriptor_tag = (byte)1;


                        //    niemi.B_descriptor = new byte[] { 0 };
                        //    niemi.B_descriptor_tag = (byte)3;
                        //    item.Descriptor2 = niemi;
                        //    #endregion
                        //}


                        //修改于20180530
                        item.Descriptor2 = null;

                        if (item.B_stream_type == "84")
                        {
                            item.B_stream_type = "03";
                        }
                    }
                    tmp.List_ProgramStreamInfo = objs;
                }
                op.Data = (object)tmp;
                DataDealHelper.MyEvent(op);
                break;

            case "AddAreaEBMIndex":
            case "DelAreaEBMIndex":
                ModifyEBMIndex Mebm = new ModifyEBMIndex();
                Mebm.IndexItemID = map["IndexItemID"].ToString();
                Mebm.Data        = map["List_EBM_resource_code"].ToString();
                op.Data          = (object)Mebm;
                DataDealHelper.MyEvent(op);
                break;

            case "DelEBMIndex":
                op.Data = map["IndexItemID"].ToString();
                DataDealHelper.MyEvent(op);
                break;
            }
        }
Esempio n. 38
0
        public void ProcessRequest(HttpContext context)
        {
            string new_hash = "";


            JavaScriptSerializer ser = new JavaScriptSerializer();
            //var pp = context.Request["vv"];
            //var pp2 = context.Request["vv2"];
            //var pp3 = context.Request["vv3"];
            //var pp4 = context.Request["vv4"];
            //var pp5 = context.Request["vv5"];
            //var pp6 = context.Request["vv6"];
            //var pp7 = context.Request["vv7"];
            //var pp8 = context.Request["vv8"];

            var    pp     = context.Request["vv"];
            string vfile1 = "";
            string vfile2 = "";
            string vfile3 = "";

            RegisteredUsers dd = ser.Deserialize <RegisteredUsers>(pp);


            if (context.Request.Files.Count > 0)
            {
                var files = new List <string>();

                foreach (string file in context.Request.Files)
                {
                    if (file == "FileUpload")
                    {
                        var postedFile = context.Request.Files[file];
                        var vfile      = postedFile.FileName.Replace("\"", string.Empty).Replace("'", string.Empty);
                        vfile = Stp(vfile);
                        string FileName   = context.Server.MapPath("~/admin/ag_docz/" + vfile);
                        string serverpath = context.Server.MapPath("~/");
                        string ssp        = Generate15UniqueDigits();

                        String xpath = doUploadPic(ssp, vfile, serverpath + "admin/tm/Picz/", postedFile);

                        xpath = xpath.Replace(serverpath + "admin/tm/", "");

                        vfile1 = xpath;
                    }

                    if (file == "FileUpload2")
                    {
                        var postedFile = context.Request.Files[file];
                        var vfile      = postedFile.FileName.Replace("\"", string.Empty).Replace("'", string.Empty);
                        vfile = Stp(vfile);
                        string FileName   = context.Server.MapPath("~/admin/ag_docz/" + vfile);
                        string serverpath = context.Server.MapPath("~/");
                        string ssp        = Generate15UniqueDigits();

                        String xpath = doUploadPic(ssp, vfile, serverpath + "admin/tm/Picz/", postedFile);

                        xpath = xpath.Replace(serverpath + "admin/tm/", "");

                        vfile2 = xpath;
                    }

                    if (file == "FileUpload3")
                    {
                        var postedFile = context.Request.Files[file];
                        var vfile      = postedFile.FileName.Replace("\"", string.Empty).Replace("'", string.Empty);
                        vfile = Stp(vfile);
                        string FileName   = context.Server.MapPath("~/admin/ag_docz/" + vfile);
                        string serverpath = context.Server.MapPath("~/");
                        string ssp        = Generate15UniqueDigits();

                        String xpath = doUploadPic(ssp, vfile, serverpath + "admin/tm/Picz/", postedFile);

                        xpath = xpath.Replace(serverpath + "admin/tm/", "");

                        vfile3 = xpath;
                    }
                }
            }

            cld.Classes.zues ff = new cld.Classes.zues();
            // Recordal_Result sp = ff.InsertRecordalB(pp, pp2, pp3, pp4, pp5, pp6,pp7,pp8);
            Recordal_Result sp = ff.InsertRecordalB(dd.vv, dd.vv2, dd.vv3, dd.vv4, dd.vv5, dd.vv6, dd.vv7, dd.vv8, vfile1, vfile2, vfile3);

            // String vip = ff.getApplicantName(pp);
            context.Response.ContentType = "application/json";
            context.Response.Write(ser.Serialize(sp));
        }
Esempio n. 39
0
        public void ProcessRequest(HttpContext context)
        {
            this.context = context;
            if (context.Request["rx_orm_addin_test"] == "rx_orm_addin_test")
            {
                response_write_json(new
                {
                    version          = rx_manager.version,
                    api_type         = "asp_net_handle",
                    i_rx_risk        = this is i_rx_risk,
                    i_rx_risk_proc   = this is i_rx_risk_proc,
                    i_rx_risk_update = this is i_rx_risk_update,
                    i_rx_risk_delete = this is i_rx_risk_delete,
                    i_rx_risk_insert = this is i_rx_risk_insert,
                    i_rx_sign        = this is i_rx_sign
                });
                return;
            }

            if (this is i_rx_sign && !sign_validate())
            {
                response_write_json(new dml_result("")
                {
                    result_code = dml_result_code.error,
                    message     = "sign 签名不正确"
                });
                return;
            }

            string rx_method = context.Request["rx_method"];

            if (rx_method == null || rx_method.Trim() == "")
            {
                response_write("该控制器继承了rx_handle,所以请按照规则或者rx_manager前端sdk进行调用!");
                return;
            }

            if (!(this is i_rx_risk))
            {
                throw new Exception("当前控制器或者handle必须继承i_rx_risk才能开启前端orm调用接口");
            }

            if (rx_manager.rx_function_md5.ContainsKey(rx_method))
            {
                if (!rx_manager.rx_function_md5[rx_method].Contains(context.Request["rx_function"]))
                {
                    response_write("检测到非法的调用,你是否调用了尝试修改rx_manager进行注入调用?");
                    return;
                }
            }


            List <MethodInfo> methods = rx_manager.method_list.Where(a => a.Name == rx_method).OrderByDescending(a => a.GetParameters().Length).ToList();

            if (methods.Count == 0)
            {
                response_write_json(new
                {
                    message = string.Format("rx_manager中不存在 {0} 这个静态方法", rx_method)
                });
            }
            JavaScriptSerializer jss = new JavaScriptSerializer();

            for (int i = 0; i < methods.Count; i++)
            {
                bool                        is_continue      = false;
                ParameterInfo[]             parameters       = methods[i].GetParameters();
                object[]                    input_parameters = new object[parameters.Length];
                Dictionary <string, object> result           = new Dictionary <string, object>();
                Dictionary <string, int>    ref_index        = new Dictionary <string, int>();
                for (int j = 0; j < parameters.Length; j++)
                {
                    if (context.Request[parameters[j].Name] == null && !parameters[j].ParameterType.IsByRef)
                    {
                        is_continue = true;
                        break;
                    }

                    if (parameters[j].ParameterType.IsByRef)
                    {
                        input_parameters[j] = Activator.CreateInstance(Type.GetType(parameters[j].ParameterType.FullName.Replace("&", "")));
                        result.Add(parameters[j].Name, null);
                        ref_index.Add(parameters[j].Name, j);
                    }
                    else if (parameters[j].ParameterType.IsAnsiClass && parameters[j].ParameterType.FullName.ToLower() == "system.string")
                    {
                        input_parameters[j] = context.Request[parameters[j].Name];
                    }
                    else if (parameters[j].ParameterType.IsEnum)
                    {
                        input_parameters[j] = Enum.Parse(parameters[j].ParameterType, context.Request[parameters[j].Name], true);
                    }
                    else if (parameters[j].ParameterType.FullName.ToLower() == "system.data.sqlclient.sqlparameter[]")
                    {
                        List <Dictionary <string, object> > dic_list = jss.Deserialize <List <Dictionary <string, object> > >(context.Request[parameters[j].Name]);
                        if (dic_list == null)
                        {
                            input_parameters[j] = null;
                            continue;
                        }
                        SqlParameter[] paras = new SqlParameter[dic_list.Count];
                        for (int k = 0; k < dic_list.Count; k++)
                        {
                            paras[k] = new SqlParameter(dic_list[k]["ParameterName"].ToString(), dic_list[k]["Value"].ToString())
                            {
                                Direction = dic_list[k]["Value"] == null ? ParameterDirection.Input : (ParameterDirection)Enum.Parse(typeof(ParameterDirection), dic_list[k]["Direction"].ToString(), true),
                                Size      = 9999999
                            };
                        }
                        input_parameters[j] = paras;
                    }
                    else if (parameters[j].ParameterType.FullName.ToLower() == "rx.rx_entity[]")
                    {
                        List <Dictionary <string, object> > dic_list = jss.Deserialize <List <Dictionary <string, object> > >(context.Request[parameters[j].Name]);
                        rx_entity[] entitys = new rx_entity[dic_list.Count];
                        for (int k = 0; k < dic_list.Count; k++)
                        {
                            entitys[k] = new rx_entity(dic_list[k]["entity_name"].ToString());
                            entitys[k].command_type        = (dml_command_type)Enum.Parse(typeof(dml_command_type), dic_list[k]["command_type"].ToString(), true);
                            entitys[k].is_use_null         = Convert.ToBoolean(dic_list[k]["is_use_null"]);
                            entitys[k].where_keys          = dic_list[k]["where_keys"] as List <string>;
                            entitys[k].select_display_keys = dic_list[k]["select_display_keys"] as string;
                            ArrayList rx_fields = (ArrayList)dic_list[k]["rx_fields"];
                            for (int l = 0; l < rx_fields.Count; l++)
                            {
                                Dictionary <string, object> rx_field = (Dictionary <string, object>)rx_fields[l];
                                entitys[k].Add(
                                    rx_field["key"].ToString(),
                                    new rx_field(
                                        rx_field["key"].ToString(),
                                        rx_field["value"],
                                        entitys[k],
                                        (date_format_type)Enum.Parse(typeof(date_format_type), rx_field["date_format_type"].ToString(), true)
                                        )
                                {
                                    compare_symbol = (compare_symbol)Enum.Parse(typeof(compare_symbol), rx_field["compare_symbol"].ToString(), true),
                                    logic_symbol   = (logic_symbol)Enum.Parse(typeof(logic_symbol), rx_field["logic_symbol"].ToString(), true),
                                    auto_remove    = Convert.ToBoolean(rx_field["auto_remove"]),
                                    build_quote    = Convert.ToBoolean(rx_field["build_quote"])
                                }
                                    );
                            }
                            entitys[k].select_display_keys = dic_list[k]["select_display_keys"] == null ? null : dic_list[k]["select_display_keys"].ToString();
                            entitys[k].where_keys          = dic_list[k]["where_keys"] == null ? null : ((ArrayList)dic_list[k]["where_keys"]).OfType <string>().ToList();
                        }

                        input_parameters[j] = entitys;
                    }
                    else if (parameters[j].ParameterType.FullName.ToLower() == "rx.rx_entity")
                    {
                        Dictionary <string, object> dic = jss.Deserialize <Dictionary <string, object> >(context.Request[parameters[j].Name]);
                        rx_entity entity = new rx_entity(dic["entity_name"].ToString());
                        if (!rx_manager.empty_entity_and_view_keys.Keys.Contains(dic["entity_name"].ToString()))
                        {
                            throw new Exception("表或者视图 " + dic["entity_name"].ToString() + " 不存在");
                        }
                        entity.command_type        = (dml_command_type)Enum.Parse(typeof(dml_command_type), dic["command_type"].ToString(), true);
                        entity.is_use_null         = Convert.ToBoolean(dic["is_use_null"]);
                        entity.where_keys          = dic["where_keys"] as List <string>;
                        entity.select_display_keys = dic["select_display_keys"] as string;
                        ArrayList rx_fields = (ArrayList)dic["rx_fields"];
                        for (int l = 0; l < rx_fields.Count; l++)
                        {
                            Dictionary <string, object> rx_field = (Dictionary <string, object>)rx_fields[l];
                            entity.Add(
                                rx_field["key"].ToString(),
                                new rx_field(
                                    rx_field["key"].ToString(),
                                    rx_field["value"],
                                    entity,
                                    (date_format_type)Enum.Parse(typeof(date_format_type), rx_field["date_format_type"].ToString(), true)
                                    )
                            {
                                compare_symbol = (compare_symbol)Enum.Parse(typeof(compare_symbol), rx_field["compare_symbol"].ToString(), true),
                                logic_symbol   = (logic_symbol)Enum.Parse(typeof(logic_symbol), rx_field["logic_symbol"].ToString(), true),
                                auto_remove    = Convert.ToBoolean(rx_field["auto_remove"]),
                                build_quote    = Convert.ToBoolean(rx_field["build_quote"])
                            }
                                );
                        }
                        entity.select_display_keys = dic["select_display_keys"] == null ? null : dic["select_display_keys"].ToString();
                        entity.where_keys          = dic["where_keys"] == null ? null : ((ArrayList)dic["where_keys"]).OfType <string>().ToList();

                        input_parameters[j] = entity;
                    }
                    else
                    {
                        if (!parameters[j].ParameterType.IsArray)
                        {
                            input_parameters[j] = jss.DeserializeObject(context.Request[parameters[j].Name]);
                        }
                        else
                        {
                            switch (parameters[j].ParameterType.FullName.ToLower())
                            {
                            case "system.string[]":
                                input_parameters[j] = Regex.Split(context.Request[parameters[j].Name], @"\[{@}\]", RegexOptions.Compiled);
                                break;

                            case "system.int32[]":
                                input_parameters[j] = Regex.Split(context.Request[parameters[j].Name], @"\[{@}\]", RegexOptions.Compiled).Select(a => a.to_int()).ToArray();
                                break;
                            }
                        }
                    }
                }

                if (is_continue)
                {
                    continue;
                }

                if (result.Count != 0)
                {
                    result.Add("rows", invoke_method(methods[i], input_parameters));
                    foreach (string key in ref_index.Keys)
                    {
                        result[key] = input_parameters[ref_index[key]];
                    }
                    response_write_json(result);
                    return;
                }
                else
                {
                    response_write_json(invoke_method(methods[i], input_parameters));
                    return;
                }
            }

            response_write_json(new
            {
                message = string.Format("rx_manager中不存在 {0} 这个静态方法,或者没有找到符合该方法参数列表的重载匹配", rx_method)
            });
        }
Esempio n. 40
0
        /// <summary>
        /// 页面加载
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (AppConfig.Mode == AppConfig.CodeMode.Production)
                {
                    #region 客户版本

                    Response.AddHeader("Access-Control-Allow-Origin", AppConfig.MoblieInterfaceDomain);
                    string time = GameRequest.GetQueryString("time");
                    string sign = GameRequest.GetQueryString("sign");
                    //签名验证
                    AjaxJsonValid ajv = Fetch.VerifySignData((AppConfig.MoblieInterfaceKey + time), sign);
                    if (ajv.code == (int)ApiCode.VertySignErrorCode)
                    {
                        Response.Write(ajv.SerializeToJson());
                        return;
                    }
                    object      obj = WHCache.Default.Get <AspNetCache>(AppConfig.WxTicket);
                    TicketCache tc  = obj as TicketCache;
                    if (tc == null)
                    {
                        try
                        {
                            string url =
                                $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={WxAuthorize.Appid}&secret={WxAuthorize.Appsecret}";
                            string result           = WxHttpService.Get(url);
                            JavaScriptSerializer js = new JavaScriptSerializer();
                            AccessToken          at = js.Deserialize <AccessToken>(result);
                            if (at.errcode > 0)
                            {
                                ajv.msg = at.errmsg;
                                Response.Write(ajv.SerializeToJson());
                                return;
                            }

                            url =
                                $"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={at.access_token}&type=jsapi";
                            result = WxHttpService.Get(url);
                            JsapiTicket jt = js.Deserialize <JsapiTicket>(result);
                            if (jt.errcode > 0)
                            {
                                ajv.msg = at.errmsg;
                                Response.Write(ajv.SerializeToJson());
                                return;
                            }

                            tc = new TicketCache();
                            tc.access_token = at.access_token;
                            tc.ticket       = jt.ticket;
                            int timeout = (at.expires_in / 60) - 3;
                            WHCache.Default.Save <AspNetCache>(AppConfig.WxTicket, tc, timeout);
                        }
                        catch (Exception)
                        {
                            Response.Write(ajv.SerializeToJson());
                            return;
                        }
                    }
                    ajv.SetValidDataValue(true);
                    ajv.SetDataItem("access_token", tc.access_token);
                    ajv.SetDataItem("ticket", tc.ticket);
                    Response.Write(ajv.SerializeToJson());

                    #endregion
                }
                else
                {
                    #region 演示版本

                    string time = GameRequest.GetQueryString("time");
                    string sign = GameRequest.GetQueryString("sign");
                    Response.Redirect("http://ry.foxuc.net/JJTicket.aspx?time=" + time + "&sign=" + sign);

                    #endregion
                }
            }
        }
Esempio n. 41
0
        public ResultInfo CoDBill()
        {
            ResultInfo result = new ResultInfo()
            {
                error = 0,
                msg   = "Them moi thanh cong"
            };

            try
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;

                var jsonserializer = new JavaScriptSerializer();
                var paser          = jsonserializer.Deserialize <CoDShowRequest>(requestContent);

                int pageSize = 50;

                int pageNumber = (paser.page ?? 1);


                DateTime paserFromDate = DateTime.Now;
                DateTime paserToDate   = DateTime.Now;

                try
                {
                    paserFromDate = DateTime.ParseExact(paser.fromDate, "dd/MM/yyyy", null);
                    paserToDate   = DateTime.ParseExact(paser.toDate, "dd/MM/yyyy", null);
                }
                catch
                {
                    paserFromDate = DateTime.Now;
                    paserToDate   = DateTime.Now;
                }

                var findCus = db.BS_Customers.Where(p => p.CustomerCode == paser.customerId).FirstOrDefault();
                if (findCus == null)
                {
                    throw new Exception("sai thông tin");
                }

                var findGroup = db.BS_CustomerGroups.Find(findCus.CustomerGroupID);

                if (findGroup == null)
                {
                    throw new Exception("sai thông tin");
                }

                var data = db.CUSTOMER_COD_DEBIT_GETDOCUMENTS(paserFromDate.ToString("yyyy-MM-dd"), paserToDate.ToString("yyyy-MM-dd"), "%" + findGroup.CustomerGroupCode + "%").ToList();

                result = new ResultWithPaging()
                {
                    error      = 0,
                    msg        = "",
                    page       = pageNumber,
                    pageSize   = pageSize,
                    toltalSize = data.Count(),
                    data       = data.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList()
                };
            }
            catch (Exception e)
            {
                result.error = 1;
                result.msg   = e.Message;
            }
            return(result);
        }
Esempio n. 42
0
        public ResultInfo GetMailers()
        {
            ResultInfo result = new ResultInfo()
            {
                error = 0,
                msg   = "Them moi thanh cong"
            };

            try
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;

                var jsonserializer = new JavaScriptSerializer();
                var paser          = jsonserializer.Deserialize <MailerShowRequest>(requestContent);

                int pageSize = 50;

                int pageNumber = (paser.page ?? 1);


                DateTime paserFromDate = DateTime.Now;
                DateTime paserToDate   = DateTime.Now;

                try
                {
                    paserFromDate = DateTime.ParseExact(paser.fromDate, "dd/MM/yyyy", null);
                    paserToDate   = DateTime.ParseExact(paser.toDate, "dd/MM/yyyy", null);
                }
                catch
                {
                    paserFromDate = DateTime.Now;
                    paserToDate   = DateTime.Now;
                }

                var findCus = db.BS_Customers.Where(p => p.CustomerCode == paser.customerId).FirstOrDefault();
                if (findCus == null)
                {
                    throw new Exception("sai thông tin");
                }

                var data = db.MAILER_GETALL(paserFromDate.ToString("yyyy-MM-dd"), paserToDate.ToString("yyyy-MM-dd"), "%" + findCus.PostOfficeID + "%", "%" + paser.search + "%").Where(p => p.SenderID.Contains(paser.customerId)).ToList();

                if (paser.status != -1)
                {
                    data = data.Where(p => p.CurrentStatusID == paser.status).ToList();
                }

                result = new ResultWithPaging()
                {
                    error      = 0,
                    msg        = "",
                    page       = pageNumber,
                    pageSize   = pageSize,
                    toltalSize = data.Count(),
                    data       = data.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList()
                };
            }
            catch (Exception e)
            {
                result.error = 1;
                result.msg   = e.Message;
            }
            return(result);
        }
Esempio n. 43
0
        public ResultInfo AddMailer()
        {
            ResultInfo result = new ResultInfo()
            {
                error = 0,
                msg   = "Them moi thanh cong"
            };

            try
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;

                var jsonserializer = new JavaScriptSerializer();
                var paser          = jsonserializer.Deserialize <MailerIdentity>(requestContent);

                var findCus = db.BS_Customers.Where(p => p.CustomerCode == paser.SenderID).FirstOrDefault();

                if (findCus == null)
                {
                    throw new Exception("Sai thông tin");
                }

                if (String.IsNullOrEmpty(findCus.Address) || String.IsNullOrEmpty(findCus.ProvinceID) || String.IsNullOrEmpty(findCus.DistrictID) || String.IsNullOrEmpty(findCus.CustomerName))
                {
                    throw new Exception("Cập nhật lại thông tin cá nhân");
                }

                MailerHandleCommon mailerHandle = new MailerHandleCommon(db);
                var code     = mailerHandle.GeneralMailerCode(findCus.PostOfficeID);
                var price    = db.CalPrice(paser.Weight, findCus.CustomerID, paser.RecieverProvinceID, paser.MailerTypeID, findCus.PostOfficeID, DateTime.Now.ToString("yyyy-MM-dd")).FirstOrDefault();
                var codPrice = 0;


                // theem
                var mailerIns = new MM_Mailers()
                {
                    MailerID            = code,
                    AcceptTime          = DateTime.Now,
                    AcceptDate          = DateTime.Now,
                    COD                 = paser.COD,
                    CreationDate        = DateTime.Now,
                    CurrentStatusID     = 0,
                    HeightSize          = paser.HeightSize,
                    Weight              = paser.Weight,
                    LengthSize          = paser.LengthSize,
                    WidthSize           = paser.WidthSize,
                    Quantity            = paser.Quantity,
                    PostOfficeAcceptID  = findCus.PostOfficeID,
                    CurrentPostOfficeID = findCus.PostOfficeID,
                    EmployeeAcceptID    = "",
                    MailerDescription   = paser.MailerDescription,
                    MailerTypeID        = paser.MailerTypeID,
                    MerchandiseValue    = paser.MerchandiseValue,
                    MerchandiseID       = paser.MerchandiseID,
                    PriceDefault        = price,
                    Price               = price,
                    PriceService        = paser.PriceService,
                    Amount              = price + codPrice,
                    PriceCoD            = codPrice,
                    Notes               = paser.Notes,
                    PaymentMethodID     = paser.PaymentMethodID,
                    RecieverAddress     = paser.RecieverAddress,
                    RecieverName        = paser.RecieverName,
                    RecieverPhone       = paser.RecieverPhone,
                    RecieverDistrictID  = paser.RecieverDistrictID,
                    RecieverWardID      = paser.RecieverWardID,
                    RecieverProvinceID  = paser.RecieverProvinceID,
                    SenderID            = findCus.CustomerCode,
                    SenderAddress       = findCus.Address,
                    SenderDistrictID    = findCus.DistrictID,
                    SenderName          = findCus.CustomerName,
                    SenderPhone         = findCus.Phone,
                    SenderProvinceID    = findCus.ProvinceID,
                    SenderWardID        = findCus.WardID,
                    PaidCoD             = 0,
                    CreateType          = 1
                };

                //
                db.MM_Mailers.Add(mailerIns);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                result.error = 1;
                result.msg   = e.Message;
            }
            return(result);
        }
Esempio n. 44
0
        /**
         * Http Get Request
         *
         * @param List<string> request of URL directories.
         * @return List<object> from JSON response.
         */
        private bool _request(List <string> url_components, ResponseType type)
        {
            List <object> result = new List <object>();
            StringBuilder url    = new StringBuilder();

            // Add Origin To The Request
            url.Append(this.ORIGIN);

            // Generate URL with UTF-8 Encoding
            foreach (string url_bit in url_components)
            {
                url.Append("/");
                url.Append(_encodeURIcomponent(url_bit));
            }

            if (type == ResponseType.Presence || type == ResponseType.Subscribe)
            {
                url.Append("?uuid=");
                url.Append(this.sessionUUID);
            }

            // Temporary fail if string too long
            if (url.Length > this.LIMIT)
            {
                result.Add(0);
                result.Add("Message Too Long.");
                // return result;
            }

            Uri requestUri = new Uri(url.ToString());

            // Force canonical path and query
            string    paq            = requestUri.PathAndQuery;
            FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
            ulong     flags          = (ulong)flagsFieldInfo.GetValue(requestUri);

            flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
            flagsFieldInfo.SetValue(requestUri, flags);

            // Create Request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            try
            {
                // Make request with the following inline Asynchronous callback
                request.BeginGetResponse(new AsyncCallback((asynchronousResult) =>
                {
                    HttpWebRequest aRequest   = (HttpWebRequest)asynchronousResult.AsyncState;
                    HttpWebResponse aResponse = (HttpWebResponse)aRequest.EndGetResponse(asynchronousResult);

                    using (StreamReader streamReader = new StreamReader(aResponse.GetResponseStream()))
                    {
                        // Deserialize the result
                        string jsonString = streamReader.ReadToEnd();
                        result            = DeserializeToListOfObject(jsonString);

                        JavaScriptSerializer jS = new JavaScriptSerializer();
                        result = (List <object>)jS.Deserialize <List <object> >(jsonString);
                        var resultOccupancy = jS.DeserializeObject(jsonString);

                        if (result.Count != 0)
                        {
                            if (result[0] is object[])
                            {
                                foreach (object message in (object[])result[0])
                                {
                                    this.ReturnMessage = message;
                                    Console.WriteLine("Time token: " + result[1].ToString());
                                }
                            }
                        }

                        switch (type)
                        {
                        case ResponseType.Publish:
                            result.Add(url_components[4]);
                            Publish = result;
                            break;

                        case ResponseType.History:
                            History = result;
                            break;

                        case ResponseType.Here_Now:
                            Dictionary <string, object> dic = (Dictionary <string, object>)resultOccupancy;
                            List <object> presented         = new List <object>();
                            presented.Add(dic);
                            Here_Now = (List <object>)presented;
                            break;

                        case ResponseType.Time:
                            Time = result;
                            break;

                        case ResponseType.Subscribe:
                            result.Add(url_components[2]);
                            Subscribe = result;
                            break;

                        case ResponseType.Presence:
                            result.Add(url_components[2]);
                            Presence = result;
                            break;

                        default:
                            break;
                        }
                    }
                }), request

                                         );
                return(true);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(false);
            }
        }
Esempio n. 45
0
        private void loadSnaps(string[] fileArr)
        {
            foreach (var snapFile in fileArr)
            {
                using (BinaryReader reader = new BinaryReader(File.OpenRead(snapFile)))
                {
                    int magicNumber = reader.ReadInt32();
                    if (magicNumber == 0x01000000)
                    {
                        Snap newSnap = new Snap();
                        newSnap.filePath = snapFile;
                        newSnap.fileName = Path.GetFileName(snapFile);

                        reader.BaseStream.Position += 256; //Unicode string with padding
                        int crc         = reader.ReadInt32();
                        int eof         = (int)reader.BaseStream.Position + reader.ReadInt32();
                        int jsonOffset  = 264 + reader.ReadInt32();
                        int titleOffset = 264 + reader.ReadInt32();
                        int descOffset  = 264 + reader.ReadInt32();
                        int imageMarker = reader.ReadInt32();
                        int bufferSize  = reader.ReadInt32();
                        int imageSize   = reader.ReadInt32();

                        switch (imageMarker)
                        {
                        case 1195724874:
                            newSnap.imageFormat = "JPEG";
                            break;

                        default:
                            newSnap.imageFormat = "Unknown";
                            break;
                        }

                        reader.BaseStream.Position = jsonOffset;
                        int jsonMarker = reader.ReadInt32();        //"JSON"
                        int jsonLength = reader.ReadInt32();
                        newSnap.rawJSON = ReadStringToNull(reader); //rest is random filler data

                        JavaScriptSerializer JSONserializer = new JavaScriptSerializer();
                        newSnap.deserializedJSON = JSONserializer.Deserialize <snapJSON>(newSnap.rawJSON);

                        newSnap.date = UnixTimeStampToDateTime(newSnap.deserializedJSON.creat);

                        reader.BaseStream.Position = titleOffset;
                        int titleMarker = reader.ReadInt32(); //"TITL"
                        int titleLength = reader.ReadInt32();
                        newSnap.title = ReadStringToNull(reader);

                        reader.BaseStream.Position = descOffset;
                        int descMarker = reader.ReadInt32(); //"DESC"
                        int descLength = reader.ReadInt32();
                        newSnap.description = ReadStringToNull(reader);

                        snapList.Add(newSnap);
                    }
                }
            }

            buildListView(snapList);
            StatusStripUpdate(string.Format("Finished loading {0} {1}", fileArr.Length, fileArr.Length == 1 ? "file" : "files"));
        }
Esempio n. 46
0
        /// <summary>
        /// Processes the API Request Object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">The URL.</param>
        /// <param name="inputaddress">inputaddress String</param>
        /// <returns>string</returns>
        public static string processAPIRequestInternal <T>(String url, String inputaddress)
        {
            String       endPoint          = String.Empty;
            String       contentTypeString = String.Empty;
            SdkException exception         = null;

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            try
            {
                String accessToken = OAuthFactory.getOAuthService().getAuthenticationToken();
                //Add xml API fragment string to complete the endpoint for xml input
                endPoint          = url + Constants.API_FRAGMENT_JSON;
                contentTypeString = "application/json;charset=utf-8";

                Uri uri = new Uri(endPoint);
                using (ExtendedWebClient client = new ExtendedWebClient())
                {
                    client.Headers.Add(HttpRequestHeader.ContentType, contentTypeString);
                    client.Headers.Add(Constants.AUTH_HEADER, accessToken);
                    client.Headers.Add(Constants.USER_AGENT, "CSharp-SDK");
                    String resp = (client.UploadString(uri, inputaddress));
                    return(resp);
                }
            }
            catch (WebException webException)
            {
                Debug.WriteLine("Got an error response from API" + webException);
                string responseText = string.Empty;
                int    statusCode   = 0;

                if (webException.Response != null)
                {
                    var responseStream = webException.Response.GetResponseStream();
                    statusCode = (int)((HttpWebResponse)webException.Response).StatusCode;

                    using (var reader = new StreamReader(responseStream))
                    {
                        responseText = reader.ReadToEnd();
                    }
                    try
                    {
                        ErrorInfo apiError;
                        apiError = serializer.Deserialize <ErrorInfo>(responseText);
                        if (apiError != null)
                        {
                            apiError.HttpStatusCode = statusCode;
                            apiError.Reason         = webException.Message;
                            apiError.Response       = responseText;
                        }
                        exception = new SdkException(apiError);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Unexpected Error: " + e);
                        exception = new SdkException(new SdkInternalError(Constants.ERROR_MSG_API_PROCESSING, e));
                    }
                }
                else
                {
                    Debug.WriteLine("Unexpected Error: " + webException);
                    exception = new SdkException(new SdkInternalError(Constants.ERROR_MSG_API_PROCESSING, webException));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Unexpected Error: " + e);
                exception = new SdkException(new SdkInternalError(Constants.ERROR_MSG_API_PROCESSING, e));
            }

            throw exception;
        }
Esempio n. 47
0
        private void AnalysisEBMConfigureData(IPrimitiveMap map)
        {
            string       packetype = map["PACKETTYPE"].ToString();
            OperatorData op        = new OperatorData();

            op.OperatorType = packetype;
            op.ModuleType   = map["Cmdtag"].ToString();
            JavaScriptSerializer Serializer = new JavaScriptSerializer();

            switch (packetype)
            {
            case "AddEBMConfigure":
            case "ModifyEBMConfigure":
                string data = map["data"].ToString();
                switch (op.ModuleType)
                {
                case "1":        //时间校准
                    JsonstructureDeal(ref data);
                    //  List<TimeService_> listTS = Serializer.Deserialize<List<TimeService_>>(data);
                    //因为有ValueType缘故 不能反序列化
                    string[]     dataArray = data.Split(',');
                    TimeService_ pp        = new TimeService_();
                    foreach (var item in dataArray)
                    {
                        if (item.Contains("ItemID"))
                        {
                            pp.ItemID = item.Split(':')[1];
                        }

                        if (item.Contains("B_Daily_cmd_tag"))
                        {
                            // pp.B_Daily_cmd_tag = Convert.ToByte(item.Split(':')[1]);
                        }
                        if (item.Contains("Configure"))
                        {
                            pp.Configure = new EBConfigureTimeService();

                            string   timestr = item.Substring(26);
                            string   time    = timestr.Substring(0, timestr.Length - 2);
                            DateTime dd      = Convert.ToDateTime(time);
                            pp.Configure.Real_time = dd;
                            // pp.Configure.Real_time = item.Split(':')[1].Split(':')[1].TrimEnd('}');
                        }

                        if (item.Contains("GetSystemTime"))
                        {
                            // pp.GetSystemTime = item.Split(':')[1] == "true" ? true : false;

                            //按照陈良需求 修改为固定取系统时间
                            pp.GetSystemTime = true;
                        }

                        if (item.Contains("SendTick"))
                        {
                            string qq = item.Split(':')[1];
                            string ww = qq.Substring(0, qq.Length - 2);

                            if (Convert.ToInt32(ww) < 60)
                            {
                                pp.SendTick = 60;
                            }
                            else
                            {
                                pp.SendTick = Convert.ToInt32(ww);
                            }
                        }
                    }
                    List <TimeService_> listTS = new List <TimeService_>();
                    listTS.Add(pp);
                    op.Data = listTS;
                    break;

                case "2":        //2区域码设置
                    JsonstructureDeal(ref data);

                    List <SetAddress_> listSA = Serializer.Deserialize <List <SetAddress_> >(data);
                    op.Data = listSA;
                    break;

                case "3":        //工作模式设置
                    JsonstructureDeal(ref data);
                    List <WorkMode_> listWM = Serializer.Deserialize <List <WorkMode_> >(data);
                    op.Data = listWM;
                    break;

                case "4":        //锁定频率设置
                    JsonstructureDeal(ref data);
                    List <MainFrequency_> listMF = Serializer.Deserialize <List <MainFrequency_> >(data);
                    op.Data = listMF;
                    break;

                case "5":        //回传方式设置
                    JsonstructureDeal(ref data);
                    //又要特殊处理

                    string         tmp1   = data.Replace("\"S_reback_address_backup\":,", "\"S_reback_address_backup\":\"null\",");
                    string         tmp2   = tmp1.Replace("\"I_reback_port_Backup\":,", "\"I_reback_port_Backup\":0,");
                    List <Reback_> listRB = Serializer.Deserialize <List <Reback_> >(tmp2);
                    op.Data = listRB;
                    break;

                case "6":        //默认音量设置
                    JsonstructureDeal(ref data);
                    List <DefaltVolume_> listDV = Serializer.Deserialize <List <DefaltVolume_> >(data);
                    op.Data = listDV;
                    break;

                case "7":        //回传周期设置
                    JsonstructureDeal(ref data);
                    List <RebackPeriod_> listRP = Serializer.Deserialize <List <RebackPeriod_> >(data);
                    op.Data = listRP;
                    break;

                case "104":        //启动内容检测指令
                    JsonstructureDeal(ref data);
                    List <ContentMoniterRetback_> listCMR = Serializer.Deserialize <List <ContentMoniterRetback_> >(data);
                    op.Data = listCMR;
                    break;

                case "105":        //启动内容监测实时监听指令
                    JsonstructureDeal(ref data);
                    if (SingletonInfo.GetInstance().IsGXProtocol)
                    {
                        List <ContentRealMoniterGX_> listCRMGX = Serializer.Deserialize <List <ContentRealMoniterGX_> >(data);
                        op.Data = listCRMGX;
                    }
                    else
                    {
                        List <ContentRealMoniter_> listCRM = Serializer.Deserialize <List <ContentRealMoniter_> >(data);
                        op.Data = listCRM;
                    }
                    break;

                case "106":        //终端工作状态查询
                    JsonstructureDeal(ref data);

                    // data.IndexOf(',')
                    List <StatusRetback_> listSR = Serializer.Deserialize <List <StatusRetback_> >(data);
                    op.Data = listSR;
                    break;

                case "240":        //终端固件升级
                    JsonstructureDeal(ref data);
                    List <SoftwareUpGrade_> listSUG = Serializer.Deserialize <List <SoftwareUpGrade_> >(data);
                    op.Data = listSUG;
                    break;

                case "8":        //RDS配置
                    JsonstructureDeal(ref data);
                    List <RdsConfig_> listRC = Serializer.Deserialize <List <RdsConfig_> >(data);
                    op.Data = listRC;
                    break;
                }

                break;

            case "DelEBMConfigure":
                string ItemList = map["ItemIDList"].ToString();
                op.Data = ItemList;
                break;
            }
            DataDealHelper.MyEvent(op);
        }
    /// <summary>
    /// This function get the access token based on the type parameter type values.
    /// If type value is 1, access token is fetch for client credential flow
    /// If type value is 2, access token is fetch for client credential flow based on the exisiting refresh token
    /// </summary>
    /// <param name="type">Type as integer</param>
    /// <param name="panelParam">Panel details</param>
    /// <returns>Return boolean</returns>
    private bool GetAccessToken(AccessType type, ref string message)
    {
        FileStream   fileStream   = null;
        Stream       postStream   = null;
        StreamWriter streamWriter = null;

        // This is client credential flow
        if (type == AccessType.ClientCredential)
        {
            try
            {
                DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();

                WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.fqdn + "/oauth/v4/token");
                accessTokenRequest.Method = "POST";
                string oauthParameters = string.Empty;
                if (type == AccessType.ClientCredential)
                {
                    oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&grant_type=client_credentials&scope=" + this.scope;
                }
                else
                {
                    oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
                }

                accessTokenRequest.ContentType = "application/x-www-form-urlencoded";

                UTF8Encoding encoding  = new UTF8Encoding();
                byte[]       postBytes = encoding.GetBytes(oauthParameters);
                accessTokenRequest.ContentLength = postBytes.Length;

                postStream = accessTokenRequest.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);

                WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
                using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
                {
                    string jsonAccessToken = accessTokenResponseStream.ReadToEnd().ToString();
                    JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();

                    AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse));

                    this.accessToken           = deserializedJsonObj.access_token;
                    this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in)).ToString();
                    this.refreshToken          = deserializedJsonObj.refresh_token;

                    DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);

                    if (deserializedJsonObj.expires_in.Equals("0"))
                    {
                        int defaultAccessTokenExpiresIn = 100; // In Yearsint yearsToAdd = 100;
                        this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongDateString() + " " + currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToLongTimeString();
                    }

                    this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();

                    fileStream   = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
                    streamWriter = new StreamWriter(fileStream);
                    streamWriter.WriteLine(this.accessToken);
                    streamWriter.WriteLine(this.accessTokenExpiryTime);
                    streamWriter.WriteLine(this.refreshToken);
                    streamWriter.WriteLine(this.refreshTokenExpiryTime);

                    // Close and clean up the StreamReader
                    accessTokenResponseStream.Close();
                    return(true);
                }
            }
            catch (WebException we)
            {
                string errorResponse = string.Empty;

                try
                {
                    using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                    {
                        errorResponse = sr2.ReadToEnd();
                        sr2.Close();
                    }
                }
                catch
                {
                    errorResponse = "Unable to get response";
                }

                message = errorResponse + Environment.NewLine + we.ToString();
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(false);
            }
            finally
            {
                if (null != postStream)
                {
                    postStream.Close();
                }

                if (null != streamWriter)
                {
                    streamWriter.Close();
                }

                if (null != fileStream)
                {
                    fileStream.Close();
                }
            }
        }
        else if (type == AccessType.RefreshToken)
        {
            try
            {
                DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();

                WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.fqdn + "/oauth/v4/token");
                accessTokenRequest.Method = "POST";

                string oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
                accessTokenRequest.ContentType = "application/x-www-form-urlencoded";

                UTF8Encoding encoding  = new UTF8Encoding();
                byte[]       postBytes = encoding.GetBytes(oauthParameters);
                accessTokenRequest.ContentLength = postBytes.Length;

                postStream = accessTokenRequest.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);

                WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
                using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
                {
                    string accessTokenJSon = accessTokenResponseStream.ReadToEnd().ToString();
                    JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();

                    AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(accessTokenJSon, typeof(AccessTokenResponse));
                    this.accessToken = deserializedJsonObj.access_token.ToString();
                    DateTime accessTokenExpiryTime = currentServerTime.AddMilliseconds(Convert.ToDouble(deserializedJsonObj.expires_in.ToString()));
                    this.refreshToken = deserializedJsonObj.refresh_token.ToString();

                    fileStream   = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
                    streamWriter = new StreamWriter(fileStream);
                    streamWriter.WriteLine(this.accessToken);
                    streamWriter.WriteLine(this.accessTokenExpiryTime);
                    streamWriter.WriteLine(this.refreshToken);

                    // Refresh token valids for 24 hours
                    DateTime refreshExpiry = currentServerTime.AddHours(24);
                    this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();
                    streamWriter.WriteLine(refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString());

                    accessTokenResponseStream.Close();
                    return(true);
                }
            }
            catch (WebException we)
            {
                string errorResponse = string.Empty;

                try
                {
                    using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                    {
                        errorResponse = sr2.ReadToEnd();
                        sr2.Close();
                    }
                }
                catch
                {
                    errorResponse = "Unable to get response";
                }

                message = errorResponse + Environment.NewLine + we.ToString();
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(false);
            }
            finally
            {
                if (null != postStream)
                {
                    postStream.Close();
                }

                if (null != streamWriter)
                {
                    streamWriter.Close();
                }

                if (null != fileStream)
                {
                    fileStream.Close();
                }
            }
        }

        return(false);
    }
Esempio n. 49
0
        public void TestFunc()
        {
            string       packetype = "AddDailyBroadcast";
            OperatorData op        = new OperatorData();

            op.OperatorType = packetype;
            op.ModuleType   = "1";
            JavaScriptSerializer Serializer = new JavaScriptSerializer();

            switch (packetype)
            {
            case "AddDailyBroadcast":
            case "ModifyDailyBroadcast":
                string data = "[{\"ItemID\":72076,\"B_Daily_cmd_tag\":1,\"Program\":{\"NetID\":1,\"TSID\":1,\"ServiceID\":1,\"PCR_PID\":1,\"Program_PID\":4013,\"Priority\":4,\"Volume\":1,\"EndTime\":\"2019/5/27 17:35:09\",\"B_Address_type\":1,\"list_Terminal_Address\":[\"634152310000\"]}}]";
                switch (op.ModuleType)
                {
                case "1":        //节目切播
                    // JsonstructureDeal(ref data);
                    ////因为有ValueType缘故 不能反序列化
                    string[]       dataArray = data.Split(',');
                    ChangeProgram_ pp        = new ChangeProgram_();

                    pp.Program = new DailyCmdChangeProgram();


                    foreach (var item in dataArray)
                    {
                        if (item.Contains("ItemID"))
                        {
                            pp.ItemID = item.Split(':')[1];
                        }

                        if (item.Contains("B_Daily_cmd_tag"))
                        {
                            // pp.B_Daily_cmd_tag = Convert.ToByte(item.Split(':')[1]);
                        }
                        if (item.Contains("Program") && !item.Contains("Program_PID"))
                        {
                            pp.Program.NetID = (short)Convert.ToInt32(item.Split(':')[2]);
                        }
                        if (item.Contains("TSID"))
                        {
                            pp.Program.TSID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("ServiceID"))
                        {
                            pp.Program.ServiceID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("PCR_PID"))
                        {
                            pp.Program.PCR_PID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("Program_PID"))
                        {
                            pp.Program.Program_PID = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("Priority"))
                        {
                            pp.Program.Priority = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("Volume"))
                        {
                            pp.Program.Volume = (short)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("EndTime"))
                        {
                            string tmp = item.Substring(10);

                            string   tmp1 = tmp.Substring(1);
                            string   tmp2 = tmp1.Substring(0, tmp1.Length - 1);
                            DateTime dd   = Convert.ToDateTime(tmp2);
                            pp.Program.EndTime = dd;
                        }
                        if (item.Contains("B_Address_type"))
                        {
                            pp.Program.B_Address_type = (byte)Convert.ToInt32(item.Split(':')[1]);
                        }

                        if (item.Contains("list_Terminal_Address"))
                        {
                            string tmp  = item.Split(':')[1].Substring(1);
                            string tmp2 = tmp.Substring(0, tmp.Length - 4);

                            string tmp3 = tmp2.Substring(1);

                            string   tmp4  = tmp3.Substring(0, tmp3.Length - 1);
                            string[] array = tmp4.Split(',');

                            int arraylength = array.Length;

                            if (SingletonInfo.GetInstance().IsGXProtocol)
                            {
                                for (int i = 0; i < arraylength; i++)
                                {
                                    array[i] = array[i] + "000000";
                                }
                            }


                            pp.Program.list_Terminal_Address = new List <string>(array);
                        }
                    }
                    List <ChangeProgram_> listCP = new List <ChangeProgram_>();
                    listCP.Add(pp);

                    op.Data = listCP;
                    break;

                case "3":        //播放控制
                    JsonstructureDeal(ref data);
                    List <PlayCtrl_> listPC = Serializer.Deserialize <List <PlayCtrl_> >(data);
                    op.Data = listPC;
                    break;

                case "4":        //输出控制
                    JsonstructureDeal(ref data);
                    List <OutSwitch_> listOS = Serializer.Deserialize <List <OutSwitch_> >(data);
                    op.Data = listOS;
                    break;

                case "5":        //RDS编码数据透传
                    JsonstructureDeal(ref data);
                    List <RdsTransfer_> listRT = Serializer.Deserialize <List <RdsTransfer_> >(data);
                    op.Data = listRT;
                    break;
                }

                break;

            case "DelDailyBroadcast":
                string ItemList = "72080";
                op.Data = ItemList;
                break;
            }
            DataDealHelper.MyEvent(op);
        }
Esempio n. 50
0
        public string Login(string back, int IsLogin = 1, int DT_id = 0)
        {
            string code = RequestTool.RequestString("code");

            if (code != "")
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("?grant_type=authorization_code");
                    sb.Append("&client_id=" + appid);
                    sb.Append("&client_secret=" + appkey);
                    sb.Append("&code=" + code);
                    string uri = reurnurl + "?backurl=" + back;
                    uri = System.Web.HttpUtility.UrlEncode(uri);
                    sb.Append("&redirect_uri=" + uri);
                    string res = API("oauth2.0/token", sb.ToString());
                    res = res + "&";
                    string access_token = RegexTool.GetRegValue(res, "access_token=(.*?)&");

                    //获取openid
                    sb = new StringBuilder();
                    sb.Append("?access_token=" + access_token);
                    res = API("oauth2.0/me", sb.ToString());
                    string openid = RegexTool.GetRegValue(res, "openid\":\"(.*?)\"}");

                    //获取用户资料
                    sb = new StringBuilder();
                    sb.Append("?access_token=" + access_token);
                    sb.Append("&oauth_consumer_key=" + appid);
                    sb.Append("&openid=" + openid);
                    res = API("user/get_user_info", sb.ToString());

                    JavaScriptSerializer jss   = new JavaScriptSerializer();
                    Model.QQ.userinfo    model = jss.Deserialize <Model.QQ.userinfo>(res);
                    string where = "bind_qq_id='" + openid + "'";
                    //if (DT_id > 0)
                    //{
                    //    where += " and DT_id =" + DT_id + "";
                    //}
                    Shop.Model.Lebi_User user        = B_Lebi_User.GetModel(where);
                    Lebi_User            CurrentUser = EX_User.CurrentUser();
                    if (CurrentUser.id > 0)//已经登录
                    {
                        if (IsLogin == 0)
                        {
                            if (user != null)
                            {
                                if (CurrentUser.id != user.id)
                                {
                                    return("已绑定其它帐号");
                                }
                            }
                        }
                        CurrentUser.bind_qq_id       = openid;
                        CurrentUser.bind_qq_nickname = model.nickname;
                        CurrentUser.bind_qq_token    = access_token;
                        if (CurrentUser.Face == "")
                        {
                            CurrentUser.Face = model.figureurl_qq_1;//头像
                        }
                        CurrentUser.DT_id = DT_id;
                        B_Lebi_User.Update(CurrentUser);
                    }
                    else
                    {
                        if (user == null)
                        {
                            Lebi_UserLevel defaultlevel = B_Lebi_UserLevel.GetModel("Grade>0 order by Grade asc");
                            if (defaultlevel == null)
                            {
                                defaultlevel = new Lebi_UserLevel();
                            }
                            if (defaultlevel.RegisterType == 0) //关闭注册
                            {
                                return("会员注册已关闭");
                            }
                            user                   = new Lebi_User();
                            user.bind_qq_id        = openid;
                            user.bind_qq_nickname  = model.nickname;
                            user.bind_qq_token     = access_token;
                            user.Face              = model.figureurl_qq_1;//头像
                            user.UserName          = "******" + openid;
                            user.NickName          = model.nickname;
                            user.Password          = EX_User.MD5(openid);
                            user.Language          = Language.CurrentLanguage().Code;
                            user.Sex               = model.gender;
                            user.UserLevel_id      = B_Lebi_UserLevel.GetList("Grade>0", "Grade asc").FirstOrDefault().id;
                            user.IsPlatformAccount = 1;
                            if (CurrentSite != null)
                            {
                                user.Site_id = CurrentSite.id;
                            }
                            user.DT_id = DT_id;
                            B_Lebi_User.Add(user);
                            user.id = B_Lebi_User.GetMaxId();
                            EX_User.LoginOK(user);
                        }
                        else
                        {
                            user.bind_qq_id       = openid;
                            user.bind_qq_nickname = model.nickname;
                            user.bind_qq_token    = access_token;
                            if (user.Face == "")
                            {
                                user.Face = model.figureurl_qq_1;//头像
                            }
                            //user.Sex = model.gender;
                            user.DT_id = DT_id;
                            B_Lebi_User.Update(user);
                            EX_User.LoginOK(user);
                        }
                    }
                    return("OK");
                }
                catch
                {
                    return("授权失败");
                }
            }
            return("授权失败");
        }
Esempio n. 51
0
        private void buttonDL_Click(object sender, EventArgs e)
        {
            js.MaxJsonLength = int.MaxValue;

            byte[] jsonData;
            string fileURL;
            string filePath;
            string fileName;
            int    count = 0;
            int    total = 0;

            Task.Factory.StartNew(() =>
            {
                groupBoxDL.Invoke(new Action(() => groupBoxDL.Enabled = false));
                using (var client = new WebClient())
                {
                    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    client.Headers.Add("user-agent", "SWUF");
                    try
                    {
                        jsonData = client.DownloadData(catalogURL);
                    }
                    catch
                    {
                        MessageBox.Show("Unable to download remote_catalog.json file");
                        return;
                    }
                }
                File.WriteAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "remote_catalog.json"), jsonData);

                if (!Directory.Exists(dataPath))
                {
                    Directory.CreateDirectory(dataPath);
                }

                string jsonText             = Encoding.UTF8.GetString(jsonData);
                RemoteCatalog remoteCatalog = (RemoteCatalog)js.Deserialize <RemoteCatalog>(jsonText);
                string[] m_InternalIds      = remoteCatalog.m_InternalIds;

                foreach (string line in m_InternalIds)
                {
                    if (line.Contains(".bundle"))
                    {
                        total++;
                    }
                }



                foreach (string line in m_InternalIds)
                {
                    if (line.Contains(".bundle"))
                    {
                        fileName = line.Replace(@"api://AssetBundle/Android/rsc/", "");
                        fileURL  = baseURL + fileName;
                        filePath = Path.Combine(dataPath, fileName);

                        using (var client = new WebClient())
                        {
                            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                            client.Headers.Add("user-agent", "AGA");
                            try
                            {
                                client.DownloadFile(fileURL, filePath);
                            }
                            catch
                            {
                                try
                                {
                                    client.DownloadFile(fileURL, filePath);
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                        }
                        count++;
                        buttonDL.Invoke(new Action(() => buttonDL.Text = count.ToString() + "/" + total.ToString()));
                    }
                }
                MessageBox.Show("Downloaded " + count.ToString() + " out of " + total.ToString() + " files");
                buttonDL.Invoke(new Action(() => buttonDL.Text        = "Download"));
                groupBoxDL.Invoke(new Action(() => groupBoxDL.Enabled = true));
            });
        }
        public async Task <bool> Login()
        {
            bool loggedIn = false;

            try
            {
                if (IsLoggedIn)
                {
                    return(loggedIn);
                }

                Cookies = new CookieContainer();

                var jsonSer = new JavaScriptSerializer();

                var jsonParams = new Dictionary <string, object>();
                jsonParams.Add("username", UserName);
                jsonParams.Add("password", SecureStringHelper.ToInsecureString(Password));


                var currentCommand = jsonSer.Serialize(jsonParams);

                jsonParams.Clear();

                // Create the request and setup for the post.
                var strRequest     = string.Format("{0}api/login", Server);
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(strRequest);

                httpWebRequest.ContentType = "application/json;charset=UTF-8";
                httpWebRequest.Accept      = "application/json";
                httpWebRequest.Method      = WebRequestMethods.Http.Post;
                httpWebRequest.ServicePoint.Expect100Continue = false;


                httpWebRequest.CookieContainer = Cookies;


                // Set the callback to handle the post of data.
                var postStream = await httpWebRequest.GetRequestStreamAsync();

                var byteArray = Encoding.UTF8.GetBytes(currentCommand);

                // Write to the request stream.
                await postStream.WriteAsync(byteArray, 0, byteArray.Length);

                await postStream.FlushAsync();

                postStream.Close();

                // Now read the reponse and process the data.
                var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    string responseText = await streamReader.ReadToEndAsync();

                    jsonParams = jsonSer.Deserialize <Dictionary <string, object> >(responseText);

                    if (!jsonParams.ContainsKey("data"))
                    {
                        loggedIn = false;
                    }
                    else
                    {
                        IsLoggedIn = true;
                        loggedIn   = true;
                    }
                }
            }
            catch (Exception ex)
            {
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Trace.WriteLine(ex);
                }
                throw;
            }

            return(loggedIn);
        }
        public static void commandRequest(string method, string key)
        {
            string documentCommandUrl = WebConfigurationManager.AppSettings["files.docservice.url.site"] + WebConfigurationManager.AppSettings["files.docservice.url.command"];

            var request = (HttpWebRequest)WebRequest.Create(documentCommandUrl);

            request.Method      = "POST";
            request.ContentType = "application/json";

            var body = new Dictionary <string, object>()
            {
                { "c", method },
                { "key", key }
            };

            if (JwtManager.Enabled)
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };

                var    payloadToken = JwtManager.Encode(payload);
                var    bodyToken    = JwtManager.Encode(body);
                string JWTheader    = WebConfigurationManager.AppSettings["files.docservice.header"].Equals("") ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
                request.Headers.Add(JWTheader, "Bearer " + payloadToken);

                body.Add("token", bodyToken);
            }

            var bytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(body));

            request.ContentLength = bytes.Length;
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            string dataResponse;

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Response is null");
                    }

                    using (var reader = new StreamReader(stream))
                    {
                        dataResponse = reader.ReadToEnd();
                    }
                }

            var jss         = new JavaScriptSerializer();
            var responseObj = jss.Deserialize <Dictionary <string, object> >(dataResponse);

            if (!responseObj["error"].ToString().Equals("0"))
            {
                throw new Exception(dataResponse);
            }
        }
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var downloadUri = (string)fileData["url"];

            string curExt      = Path.GetExtension(fileName);
            string downloadExt = Path.GetExtension(downloadUri);
            var    newFileName = fileName;

            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = _Default.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (_Default.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3");

            if (isSubmitForm)
            {
                if (newFileName.Equals(fileName))
                {
                    newFileName = _Default.GetCorrectName(fileName, userAddress);
                }
                forcesavePath = _Default.StoragePath(newFileName, userAddress);
            }
            else
            {
                forcesavePath = _Default.ForcesavePath(newFileName, userAddress, false);
                if (forcesavePath.Equals(""))
                {
                    forcesavePath = _Default.ForcesavePath(newFileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();
                DocEditor.CreateMeta(newFileName, user, "Filling Form", userAddress);
            }

            return(0);
        }
Esempio n. 55
0
 /// <summary>
 /// Deserialize a JSON string to typed object.
 /// </summary>
 /// <typeparam name="T">type of object</typeparam>
 /// <param name="json">JSON string</param>
 /// <returns>typed object</returns>
 public T Deserialize <T>(string json)
 {
     return(serializer.Deserialize <T>(json));
 }
Esempio n. 56
0
        public static T GetResult <T>(string returnText)
        {
            JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();

            return(javaScriptSerializer.Deserialize <T>(returnText));
        }
Esempio n. 57
0
    public static void ProcessContentProjects(Configuration configuration, SolutionBuilder.SolutionBuildResult buildResult, HashSet <string> contentProjectsProcessed)
    {
        var contentOutputDirectory =
            configuration.ProfileSettings.GetValueOrDefault("ContentOutputDirectory", null) as string;

        if (contentOutputDirectory == null)
        {
            return;
        }

        contentOutputDirectory = contentOutputDirectory
                                 .Replace("%configpath%", configuration.Path)
                                 .Replace("%outputpath%", configuration.OutputDirectory);

        var projectCollection = new ProjectCollection();
        var contentProjects   = buildResult.ProjectsBuilt.Where(
            (project) => project.File.EndsWith(".contentproj")
            ).ToArray();

        var builtXNBs =
            (from bi in buildResult.AllItemsBuilt
             where bi.OutputPath.EndsWith(".xnb", StringComparison.OrdinalIgnoreCase)
             select bi).Distinct().ToArray();

        var forceCopyImporters = new HashSet <string>(
            ((IEnumerable)configuration.ProfileSettings["ForceCopyXNBImporters"]).Cast <string>()
            );

        var forceCopyProcessors = new HashSet <string>(
            ((IEnumerable)configuration.ProfileSettings["ForceCopyXNBProcessors"]).Cast <string>()
            );

        Dictionary <string, Common.CompressResult> existingJournal = new Dictionary <string, CompressResult>();

        Common.CompressResult?existingJournalEntry;
        var jss = new JavaScriptSerializer();

        foreach (var builtContentProject in contentProjects)
        {
            var contentProjectPath = builtContentProject.File;

            if (contentProjectsProcessed.Contains(contentProjectPath))
            {
                continue;
            }

            var journal     = new List <Common.CompressResult>();
            var journalPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "JSIL",
                                           contentProjectPath.Replace("\\", "_").Replace(":", ""));

            Common.EnsureDirectoryExists(Path.GetDirectoryName(journalPath));
            if (File.Exists(journalPath))
            {
                var journalEntries = jss.Deserialize <Common.CompressResult[]>(File.ReadAllText(journalPath));

                if (journalEntries != null)
                {
                    existingJournal = journalEntries.ToDictionary(
                        (je) => {
                        if (je.Key != null)
                        {
                            return(je.SourceFilename + ":" + je.Key);
                        }
                        else
                        {
                            return(je.SourceFilename);
                        }
                    }
                        );
                }
            }

            contentProjectsProcessed.Add(contentProjectPath);
            Console.Error.WriteLine("// Processing content project '{0}' ...", contentProjectPath);

            var project           = projectCollection.LoadProject(contentProjectPath);
            var projectProperties = project.Properties.ToDictionary(
                (p) => p.Name
                );

            Project parentProject = null, rootProject = null;
            Dictionary <string, ProjectProperty> parentProjectProperties = null, rootProjectProperties = null;

            if (builtContentProject.Parent != null)
            {
                parentProject           = projectCollection.LoadProject(builtContentProject.Parent.File);
                parentProjectProperties = parentProject.Properties.ToDictionary(
                    (p) => p.Name
                    );
            }

            {
                var parent = builtContentProject.Parent;

                while (parent != null)
                {
                    var nextParent = parent.Parent;
                    if (nextParent != null)
                    {
                        parent = nextParent;
                        continue;
                    }

                    rootProject           = projectCollection.LoadProject(parent.File);
                    rootProjectProperties = rootProject.Properties.ToDictionary(
                        (p) => p.Name
                        );
                    break;
                }
            }

            var contentProjectDirectory = Path.GetDirectoryName(contentProjectPath);
            var localOutputDirectory    = contentOutputDirectory
                                          .Replace("%contentprojectpath%", contentProjectDirectory)
                                          .Replace("/", "\\");

            var contentManifest = new StringBuilder();
            contentManifest.AppendFormat("// {0}\r\n", JSIL.AssemblyTranslator.GetHeaderText());
            contentManifest.AppendLine();
            contentManifest.AppendLine("if (typeof (contentManifest) !== \"object\") { contentManifest = {}; };");
            contentManifest.AppendLine("contentManifest[\"" + Path.GetFileNameWithoutExtension(contentProjectPath) +
                                       "\"] = [");

            Action <string, string, Dictionary <string, object> > logOutput =
                (type, filename, properties) => {
                var fileInfo = new FileInfo(filename);

                var localPath = filename.Replace(localOutputDirectory, "");
                if (localPath.StartsWith("\\"))
                {
                    localPath = localPath.Substring(1);
                }

                Console.WriteLine(localPath);

                string propertiesObject;

                if (properties == null)
                {
                    properties = new Dictionary <string, object> {
                        { "sizeBytes", fileInfo.Length }
                    };
                }

                contentManifest.AppendFormat(
                    "  [\"{0}\", \"{1}\", {2}],{3}",
                    type, localPath.Replace("\\", "/"),
                    jss.Serialize(properties),
                    Environment.NewLine
                    );
            };

            Action <ProjectItem> copyRawFile =
                (item) => {
                var sourcePath = Path.Combine(
                    contentProjectDirectory,
                    item.EvaluatedInclude
                    );
                var outputPath = FixupOutputDirectory(
                    localOutputDirectory,
                    item.EvaluatedInclude
                    );

                Common.EnsureDirectoryExists(
                    Path.GetDirectoryName(outputPath));

                File.Copy(sourcePath, outputPath, true);
                logOutput("File", outputPath, null);
            };

            Action <ProjectItem, string, string> copyRawXnb =
                (item, xnbPath, type) => {
                if (xnbPath == null)
                {
                    throw new FileNotFoundException("Asset " + item.EvaluatedInclude + " was not built.");
                }

                var outputPath = FixupOutputDirectory(
                    localOutputDirectory,
                    item.EvaluatedInclude.Replace(
                        Path.GetExtension(item.EvaluatedInclude),
                        ".xnb")
                    );

                Common.EnsureDirectoryExists(
                    Path.GetDirectoryName(outputPath));

                File.Copy(xnbPath, outputPath, true);
                logOutput(type, outputPath, null);
            };

            foreach (var item in project.Items)
            {
                switch (item.ItemType)
                {
                case "Reference":
                case "ProjectReference":
                    continue;

                case "Compile":
                case "None":
                    break;

                default:
                    continue;
                }

                var itemOutputDirectory = FixupOutputDirectory(
                    localOutputDirectory,
                    Path.GetDirectoryName(item.EvaluatedInclude)
                    );

                var sourcePath = Path.Combine(contentProjectDirectory, item.EvaluatedInclude);
                var metadata   = item.DirectMetadata.ToDictionary((md) => md.Name);

                if (item.ItemType == "None")
                {
                    string          copyToOutputDirectory = "Always";
                    ProjectMetadata temp2;

                    if (metadata.TryGetValue("CopyToOutputDirectory", out temp2))
                    {
                        copyToOutputDirectory = temp2.EvaluatedValue;
                    }

                    switch (copyToOutputDirectory)
                    {
                    case "Always":
                    case "PreserveNewest":
                        copyRawFile(item);
                        break;

                    default:
                        break;
                    }

                    continue;
                }

                var    importerName  = metadata["Importer"].EvaluatedValue;
                var    processorName = metadata["Processor"].EvaluatedValue;
                string xnbPath       = null;

                Common.CompressResult temp;
                if (existingJournal.TryGetValue(sourcePath, out temp))
                {
                    existingJournalEntry = temp;
                }
                else
                {
                    existingJournalEntry = null;
                }

                var evaluatedXnbPath   = item.EvaluatedInclude.Replace(Path.GetExtension(item.EvaluatedInclude), ".xnb");
                var matchingBuiltPaths = (from bi in builtXNBs where
                                          bi.OutputPath.Contains(":\\") &&
                                          bi.OutputPath.EndsWith(evaluatedXnbPath)
                                          select bi.Metadata["FullPath"]).Distinct().ToArray();

                if (matchingBuiltPaths.Length == 0)
                {
                }
                else if (matchingBuiltPaths.Length > 1)
                {
                    throw new AmbiguousMatchException("Found multiple outputs for asset " + evaluatedXnbPath);
                }
                else
                {
                    xnbPath = matchingBuiltPaths[0];
                    if (!File.Exists(xnbPath))
                    {
                        throw new FileNotFoundException("Asset " + xnbPath + " not found.");
                    }
                }

                if (GetFileSettings(configuration.ProfileSettings, item.EvaluatedInclude).Contains("usexnb"))
                {
                    copyRawXnb(item, xnbPath, "XNB");
                }
                else if (
                    forceCopyProcessors.Contains(processorName) ||
                    forceCopyImporters.Contains(importerName)
                    )
                {
                    copyRawXnb(item, xnbPath, "XNB");
                }
                else
                {
                    switch (processorName)
                    {
                    case "XactProcessor":
                        Common.ConvertXactProject(
                            item.EvaluatedInclude, contentProjectDirectory, itemOutputDirectory,
                            configuration.ProfileSettings, existingJournal,
                            journal, logOutput
                            );

                        continue;

                    case "FontTextureProcessor":
                    case "FontDescriptionProcessor":
                        copyRawXnb(item, xnbPath, "SpriteFont");
                        continue;

                    case "SoundEffectProcessor":
                    case "SongProcessor":
                        journal.AddRange(CompressAudioGroup(
                                             item.EvaluatedInclude, contentProjectDirectory, itemOutputDirectory,
                                             configuration.ProfileSettings, existingJournal, logOutput
                                             ));
                        continue;

                    case "TextureProcessor":
                        if (Path.GetExtension(sourcePath).ToLower() == ".tga")
                        {
                            copyRawXnb(item, xnbPath, "Texture2D");
                            continue;
                        }

                        var result = Common.CompressImage(
                            item.EvaluatedInclude, contentProjectDirectory, itemOutputDirectory,
                            configuration.ProfileSettings, metadata, existingJournalEntry
                            );

                        if (result.HasValue)
                        {
                            journal.Add(result.Value);
                            logOutput("Image", result.Value.Filename, null);
                        }

                        continue;

                    case "EffectProcessor":
                        copyRawXnb(item, xnbPath, "XNB");
                        continue;
                    }

                    switch (importerName)
                    {
                    case "XmlImporter":
                        copyRawXnb(item, xnbPath, "XNB");
                        break;

                    default:
                        Console.Error.WriteLine(
                            "// Can't process '{0}': importer '{1}' and processor '{2}' both unsupported.",
                            item.EvaluatedInclude, importerName, processorName);
                        break;
                    }
                }
            }

            contentManifest.AppendLine("];");
            File.WriteAllText(
                Path.Combine(configuration.OutputDirectory, Path.GetFileName(contentProjectPath) + ".manifest.js"),
                contentManifest.ToString()
                );

            File.WriteAllText(
                journalPath, jss.Serialize(journal).Replace("{", "\r\n{")
                );
        }

        if (contentProjects.Length > 0)
        {
            Console.Error.WriteLine("// Done processing content.");
        }
    }
Esempio n. 58
0
        /// <summary> </summary>
        public static string getfieldmodel_dynamic(field_types field, string select_val)
        {
            string ele            = field.attr.ToString();
            var    jss            = new JavaScriptSerializer();
            var    dyn_ele        = jss.Deserialize <Dictionary <string, dynamic> >(ele);
            var    dyn_select_val = new Dictionary <string, dynamic>();

            dyn_select_val = String.IsNullOrWhiteSpace(select_val) ? dyn_select_val : jss.Deserialize <Dictionary <string, dynamic> >(select_val);


            // lets set up the attrs for the element
            SortedDictionary <string, string> attrs = new SortedDictionary <string, string>();

            dynamic value;

            if (dyn_ele.TryGetValue("attr", out value))
            {
                attrs = attrbase_dynamic(attrs, dyn_ele);
            }
            if (dyn_ele.TryGetValue("events", out value))
            {
                attrs = eventbase_dynamic(attrs, dyn_ele);
            }
            if (dyn_select_val.TryGetValue("selections", out value))
            {
                dyn_ele = selectedVal_dynamic(dyn_select_val, dyn_ele);
            }

            string _ele = String.Empty;
            string type = dyn_ele["type"];

            switch (type)
            {
            case "dropdown": {
                _ele = fieldsService.renderSelect_dynamic(dyn_ele, attrs); break;
            }

            case "textinput": {
                _ele = fieldsService.renderTextInput_dynamic(dyn_ele, attrs); break;
            }

            case "textarea": {
                _ele = fieldsService.renderTextarera_dynamic(dyn_ele, attrs); break;
            }

            case "checkbox": {
                _ele = fieldsService.renderCheckbox_dynamic(dyn_ele, attrs); break;
            }

            case "slider": {
                _ele = ""; break;        // FieldsService.renderSlider_dynamic(dyn_ele, attrs); break;
            }
            }

            if (!String.IsNullOrWhiteSpace(field.template.content))
            {
                Hashtable parambag = new Hashtable();

                parambag.Add("element_html", _ele);
                parambag = objectService.marge_params(attrs, parambag);
                if (!String.IsNullOrWhiteSpace(field.notes.content))
                {
                    parambag.Add("notes", field.notes.content);
                }
                parambag.Add("field", field);



                /* now process the content template */
                String laidout = renderService.simple_field_layout(field.template.content, field.template, parambag);
                _ele = laidout;
            }
            // Return the result.
            return(_ele);
        }
        public HttpResponseMessage SaveConnection(object postData)
        {
            try
            {
                var jsonData   = DotNetNuke.Common.Utilities.Json.Serialize(postData);
                var serializer = new JavaScriptSerializer();
                serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

                dynamic postObject = serializer.Deserialize(jsonData, typeof(object));

                var name        = postObject.name;
                var displayName = postObject.displayName;
                var id          = postObject.id;
                var connectors  =
                    GetConnections(PortalId).ForEach(x =>
                {
                    {
                        x.HasConfig(PortalSettings.PortalId);
                    }
                })
                    .Where(
                        c =>
                        c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).ToList();

                var connector = connectors.FirstOrDefault(c =>
                                                          (c.SupportsMultiple && (c.Id == id || string.IsNullOrEmpty(c.Id))) ||
                                                          !c.SupportsMultiple);

                if (connector == null && string.IsNullOrEmpty(id) && connectors.Any(x => x.SupportsMultiple))
                {
                    connector             = connectors.First();
                    connector.Id          = null;
                    connector.DisplayName = null;
                }
                if (connector != null && !string.IsNullOrEmpty(displayName) && connector.DisplayName != displayName)
                {
                    connector.DisplayName = string.IsNullOrEmpty(displayName) ? "" : displayName;
                }

                bool validated = false;
                if (connector != null)
                {
                    var    configs = GetConfigAsDictionary(postObject.configurations);
                    string customErrorMessage;
                    var    saved = connector.SaveConfig(PortalSettings.PortalId, configs, ref validated,
                                                        out customErrorMessage);

                    if (!saved)
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, new
                        {
                            Success = false,
                            Validated = validated,
                            Message = string.IsNullOrEmpty(customErrorMessage)
                                ? Localization.GetString("ErrSavingConnectorSettings.Text", Constants.SharedResources)
                                : customErrorMessage
                        }));
                    }
                }

                return(Request.CreateResponse(HttpStatusCode.OK,
                                              new
                {
                    Success = true,
                    Validated = validated,
                    connector?.Id
                }));
            }
            catch (Exception ex)
            {
                if (ex is ConnectorArgumentException)
                {
                    Logger.Warn(ex);
                }
                else
                {
                    Logger.Error(ex);
                }
                return(Request.CreateResponse(HttpStatusCode.InternalServerError,
                                              new { Success = false, Message = ex.Message }));
            }
        }
Esempio n. 60
0
        static T Deserialize <T>(string json)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());

            return(serializer.Deserialize <T>(json));
        }