예제 #1
0
        public void upload_activity_json(ref StringBuilder jsonData, SQLiteConnection dbConnection, int fileId, string activityName, string activityNotes, Batch activityBatch)
        {
            System.Text.ASCIIEncoding aSCIIEncoding = new System.Text.ASCIIEncoding();

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://ridewithgps.com/trips.json");

            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method      = "POST";
            httpWebRequest.ServicePoint.Expect100Continue = false;

            byte[] jsonBytes = aSCIIEncoding.GetBytes(jsonData.ToString());
            httpWebRequest.ContentLength = jsonBytes.Length;

            System.IO.Stream requestStream = httpWebRequest.GetRequestStream();
            requestStream.Write(jsonBytes, 0, jsonBytes.Length);
            requestStream.Close();

            try{
                HttpWebResponse  httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                System.IO.Stream responseStream  = httpWebResponse.GetResponseStream();
                if (responseStream != null)
                {
                    System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream);
                    string text = streamReader.ReadToEnd();

                    Match KeywordMatch = Regex.Match(text, "\"id\":([^,]*),", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    if (KeywordMatch.Success)
                    {
                        ((MainForm)Application.OpenForms[0]).setUpdateRideMsg("ridewithgps", "Ride Uploaded Successfully");
                        ((MainForm)Application.OpenForms[0]).setUpdateRideId("ridewithgps", KeywordMatch.Groups[1].Value);
                        ((MainForm)Application.OpenForms[0]).setNewActivityLink("ridewithgps", KeywordMatch.Groups[1].Value, string.Format("http://ridewithgps.com/trips/{0}", KeywordMatch.Groups[1].Value));
                        ((MainForm)Application.OpenForms[0]).setUpdateRideImg("ridewithgps", Image.FromFile("success-icon.png"));

                        if (activityBatch != null)
                        {
                            activityBatch.setUploadStatus("rwgps", "success", string.Format("http://ridewithgps.com/trips/{0}", KeywordMatch.Groups[1].Value));
                            activityBatch.setUploadProgressStatus("RideWithGps: Uploaded Succesfully");
                        }

                        SQLiteCommand cmd = new SQLiteCommand(dbConnection);
                        string        sql = "update File set fileActivityName = ?, fileActivityNotes = ?, fileUploadRWGPS = ? where idFile = ?";
                        cmd.CommandText = sql;
                        cmd.Parameters.Add(new SQLiteParameter());
                        cmd.Parameters.Add(new SQLiteParameter());
                        cmd.Parameters.Add(new SQLiteParameter());
                        cmd.Parameters.Add(new SQLiteParameter());
                        // add values to parameters
                        cmd.Parameters[0].Value = activityName;
                        cmd.Parameters[1].Value = activityNotes;
                        cmd.Parameters[2].Value = string.Format("http://ridewithgps.com/trips/{0}", KeywordMatch.Groups[1].Value);
                        cmd.Parameters[3].Value = fileId;

                        /*string sql = string.Format("update File set fileActivityName = \"{2}\", fileActivityNotes = \"{3}\", fileUploadRWGPS = \"{0}\" where idFile = {1}",
                         *                 string.Format("http://ridewithgps.com/trips/{0}",KeywordMatch.Groups[1].Value),
                         *                 fileId,
                         *                 activityName,
                         *                 activityNotes
                         *                );
                         * cmd.CommandText = sql;
                         */
                        cmd.ExecuteNonQuery();
                    }
                    else
                    {
                        ((MainForm)Application.OpenForms[0]).setUpdateRideMsg("ridewithgps", "Ride ID not found, activity may not have been accepted.");
                        ((MainForm)Application.OpenForms[0]).setUpdateRideImg("ridewithgps", Image.FromFile("failure-icon.png"));
                        if (activityBatch != null)
                        {
                            activityBatch.setUploadStatus("rwgps", "error");
                            activityBatch.setUploadProgressStatus("RideWithGps: Error uploading ride");
                        }
                    }
                }
            }
            catch (Exception ex) {
                ((MainForm)Application.OpenForms[0]).setUpdateRideMsg("ridewithgps", "Exception raised while processing upload request. " + ex.ToString());
                ((MainForm)Application.OpenForms[0]).setUpdateRideImg("ridewithgps", Image.FromFile("failure-icon.png"));
                if (activityBatch != null)
                {
                    activityBatch.setUploadStatus("rwgps", "exception");
                    activityBatch.setUploadProgressStatus("RideWithGps: Exception" + ex.Message);
                }
            }
        }
예제 #2
0
        public void UploadFile(string file, string activity_name, SQLiteConnection dbConnection, int fileId, string activityName, string activityNotes, Batch activityBatch)
        {
            int    wId = 0;
            string url = "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/";
            string file_content_type = "application/octet-stream";
            string file_param_name   = "data";
            string file_extension    = Path.GetExtension(file);

            url += file_extension;
            bool bSetName = false;

            NameValueCollection nvc = new NameValueCollection();

            nvc.Add("responseContentType", "text/html");

            Debug.Write(string.Format("Uploading {0} to {1}", file, url));
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method      = "POST";
            wr.KeepAlive   = true;
            wr.ServicePoint.Expect100Continue = false;
            wr.CookieContainer = this.GetCookieContainer();

            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = wr.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem      = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header         = string.Format(headerTemplate, file_param_name, file, file_content_type);

            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            //byte[] filedata = System.Text.Encoding.ASCII.GetBytes(file);
            //rs.Write(filedata, 0, filedata.Length);
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None);

            byte[] buffer    = new byte[4096];
            int    bytesRead = 0;

            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            ((MainForm)Application.OpenForms[0]).setUpdateRideMsg("garmin", "Uploading, waiting for response");

            if (activityBatch != null)
            {
                activityBatch.setUploadProgressStatus("Garmin: Uploading activity, waiting for response");
            }

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;

            try {
                wresp = wr.GetResponse();
                Stream       stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                string       json    = reader2.ReadToEnd();
                //Debug.Write(string.Format("File uploaded, server response is: {0}", json));

                garminImportResult gOut = new JavaScriptSerializer().Deserialize <garminImportResult>(json);

                if (gOut.detailedImportResult.successes.Length > 0)
                {
                    garminImportResultRecord sRec = gOut.detailedImportResult.successes[0];
                    ((MainForm)Application.OpenForms[0]).setUpdateRideMsg("garmin", "Ride Uploaded Successfully");
                    ((MainForm)Application.OpenForms[0]).setUpdateRideId("garmin", sRec.internalId);
                    ((MainForm)Application.OpenForms[0]).setNewActivityLink("garmin", sRec.internalId, string.Format("http://connect.garmin.com/activity/{0}", sRec.internalId));
                    ((MainForm)Application.OpenForms[0]).setUpdateRideImg("garmin", Image.FromFile("success-icon.png"));
                    if (activityBatch != null)
                    {
                        activityBatch.setUploadProgressStatus("Garmin: Uploaded Successfully");
                    }

                    wId = Convert.ToInt32(sRec.internalId);

                    SQLiteCommand cmd = new SQLiteCommand(dbConnection);

                    string sql = "update File set FileActivityName = ?, fileActivityNotes = ?, fileUploadGarmin = ? where idFile = ?";
                    cmd.CommandText = sql;
                    cmd.Parameters.Add(new SQLiteParameter());
                    cmd.Parameters.Add(new SQLiteParameter());
                    cmd.Parameters.Add(new SQLiteParameter());
                    cmd.Parameters.Add(new SQLiteParameter());
                    // add the parameter values
                    cmd.Parameters[0].Value = activityName;
                    cmd.Parameters[1].Value = activityNotes;
                    cmd.Parameters[2].Value = string.Format("http://connect.garmin.com/activity/{0}", sRec.internalId);
                    cmd.Parameters[3].Value = fileId;

                    /*string sql = string.Format("update File set fileActivityName = \"{2}\", fileActivityNotes = \"{3}\", fileUploadGarmin = \"{0}\" where idFile = {1}",
                     *                         string.Format("http://connect.garmin.com/activity/{0}",sRec.internalId),
                     *                         fileId,
                     *                         activityName,
                     *                         activityNotes
                     *                        );
                     * cmd.CommandText = sql;
                     */
                    cmd.ExecuteNonQuery();

                    bSetName = true;

                    if (activityBatch != null)
                    {
                        activityBatch.setUploadStatus("garmin", "success", string.Format("http://connect.garmin.com/activity/{0}", sRec.internalId));
                    }
                }
                else if (gOut.detailedImportResult.failures.Length > 0)
                {
                    garminImportResultRecord fRec = gOut.detailedImportResult.failures[0];

                    ((MainForm)Application.OpenForms[0]).setUpdateRideMsg("garmin", "Activity data wasn`t accepted. Code=" + fRec.messages[0].code + ", Msg=" + fRec.messages[0].content);
                    ((MainForm)Application.OpenForms[0]).setUpdateRideImg("garmin", Image.FromFile("failure-icon.png"));
                    if (activityBatch != null)
                    {
                        activityBatch.setUploadStatus("garmin", "not accepted", "Garmin: Activity data wasn`t accepted. Code=" + fRec.messages[0].code + ", Msg=" + fRec.messages[0].content);
                    }
                }
            } catch (Exception ex) {
                Debug.Write("Error uploading file", ex.ToString());
                ((MainForm)Application.OpenForms[0]).setUpdateRideMsg("garmin", "Exception raised while processing upload request. " + ex.ToString());
                ((MainForm)Application.OpenForms[0]).setUpdateRideImg("garmin", Image.FromFile("failure-icon.png"));
                if (activityBatch != null)
                {
                    activityBatch.setUploadStatus("garmin", "exception", "Garmin: Exception raised while processing upload request. " + ex.ToString());
                }
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            } finally {
                wr = null;
            }

            // Set the workout name if the activity was successfully created above
            if (bSetName)
            {
                // Build the Http Request, with specified headers - including preserving the cookies (this.GetCookieContainer)
                string wUrl    = string.Format("http://connect.garmin.com/proxy/activity-service-1.2/json/name/{0}", wId);
                string wParams = "value=" + HttpUtility.UrlEncode(activity_name);

                System.Text.ASCIIEncoding aSCIIEncoding = new System.Text.ASCIIEncoding();
                byte[]         wBytes         = aSCIIEncoding.GetBytes(wParams);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(wUrl);
                httpWebRequest.Proxy           = null;
                httpWebRequest.Credentials     = CredentialCache.DefaultCredentials;
                httpWebRequest.Method          = "POST";
                httpWebRequest.ContentType     = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength   = (long)wBytes.Length;
                httpWebRequest.CookieContainer = this.GetCookieContainer();
                System.IO.Stream requestStream = httpWebRequest.GetRequestStream();
                requestStream.Write(wBytes, 0, wBytes.Length);
                requestStream.Close();

                // Get the response to the web request, and read all of the data received
                // TODO: parse the response to check for errors - just ignore for now as it's not critical if this step fails as the activity
                // will still have been saved at this point so activity name could be changed manually if necessary
                using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {
                    System.IO.Stream responseStream = httpWebResponse.GetResponseStream();
                    if (responseStream != null)
                    {
                        System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream);
                        string text = streamReader.ReadToEnd();
                        this.LastOutput = text;
                    }
                }
            }
        }