Exemple #1
0
                /// <summary>
                /// Adds an email address to a user account. If _User is null adds to current user.
                /// </summary>
                /// <param name="_Config"></param>
                /// <param name="_Email"></param>
                /// <param name="_User"></param>
                public static void Add(Config _Config, string _Email, User _User = null)
                {
                    try
                    {
                        string URI = _Config.APIUrl;

                        if (_User == null)
                        {
                            URI += "user/emails/";
                        }
                        else
                        {
                            URI += "users/" + _User.id.ToString() + "/emails/";
                        }

                        URI += "?email=" + HttpUtility.UrlEncode(_Email);

                        HttpResponse <string> R = Unirest.post(URI)
                                                  .header("accept", "application/json")
                                                  .header("PRIVATE-TOKEN", _Config.APIKey)
                                                  .asString();

                        if (R.Code < 200 || R.Code >= 300)
                        {
                            throw new GitLabServerErrorException(R.Body, R.Code);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
Exemple #2
0
        private void Submit_Click(object sender, EventArgs e)
        {
            if (student_name.Text != null)
            {
                try
                {
                    string s_name = student_name.Text;

                    //Train Album
                    byte[] image = ImageToBinary(@"C:\Users\user\Desktop\crop.png");
                    // These code snippets use an open-source library. http://unirest.io/net
                    // These code snippets use an open-source library. http://unirest.io/net
                    HttpResponse <string> response = Unirest.post("https://lambda-face-recognition.p.mashape.com/album_train")
                                                     .header("X-Mashape-Key", "43mMyTAnRnmshjV8yYJtfcKGeXH9p1Qz0GMjsnFp2mnbrDrpdb")
                                                     .field("album", "school_security")
                                                     .field("albumkey", "e912e986606952880210d58450f745cf00befd54d20bf6e6914ddd0fd8b24ff0")
                                                     .field("entryid", s_name)
                                                     .field("files", File.ReadAllBytes(filePath))
                                                     //.field("urls", "http://www.lambdal.com/tiger.jpg")
                                                     .asJson <string>();
                    MessageBox.Show(response.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
Exemple #3
0
                public static Snippet Create(Config _Config, Project _Project, string _Title, string _FileName, string _Code, VisibilityLevel _VisibilityLevel)
                {
                    Snippet RetVal;

                    try
                    {
                        string URI = _Config.APIUrl + "projects/" + _Project.id.ToString() + "/snippets/"
                                     + "?title=" + HttpUtility.UrlEncode(_Title)
                                     + "&file_name=" + HttpUtility.UrlEncode(_FileName)
                                     + "&code=" + HttpUtility.UrlEncode(_Code)
                                     + "&visibility_level=" + Convert.ToInt64(_VisibilityLevel).ToString();

                        HttpResponse <string> R = Unirest.post(URI)
                                                  .header("accept", "application/json")
                                                  .header("PRIVATE-TOKEN", _Config.APIKey)
                                                  .asString();

                        if (R.Code < 200 || R.Code >= 300)
                        {
                            throw new GitLabServerErrorException(R.Body, R.Code);
                        }
                        else
                        {
                            RetVal = JsonConvert.DeserializeObject <Snippet>(R.Body.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    return(RetVal);
                }
Exemple #4
0
        //메시지 전송
        public HttpResponse <string> sendMsg()
        {
            string msg = "강민성 고객님 \r\n ETOMARS에서 알려드립니다. \r\n 수입통관에 해당하는 물품을 구매시 \r\n 관세법 시행령 제289조 에 의거하여 \r\n 아래와 같은 추가 정보를 요청 드립니다. \r\n";

            msg += "- 주민등록번호 / 개인통관고유번호 \r\n 개인통관고유번호 발급 \r\n https://unipass.customs.go.kr/csp/persIndex.do \r\n \r\n ";
            msg += "ETOMARS \r\n https://www.etomars.com \r\n 공식 대행 등록 업체 \r\n ETOMARS \r\n https://www.etomars.com \r\n 070 7661 1030";
            //알림톡 수신자
            string phone = "01020281393";

            //알림톡 발신자 -- sendnumber_save 를 통헤 등록/인증 된 번호만 사용 가능
            string callback = "01020281393";

            HttpResponse <string> request = Unirest.post("http://api.apistore.co.kr/kko/1/msg/etomars")
                                            .header("x-waple-authorization", "ODI1Ni0xNTI1MzMwOTM1NTIxLTg2YTk0NGZiLTk4NDMtNDJiYS1hOTQ0LWZiOTg0M2IyYmEwNg==")
                                            .header("Content - Type", "application/x-www-form-urlencoded;charset=UTF-8")
                                            .field("phone", phone)       //수신자 전화번호
                                            .field("callback", callback) //발신자 전화번호
                                            .field("msg", msg)
                                            .field("template_code", "test01")
                                            .field("failed_type", "N") // LMS / SMS / N
                                            .field("FAILED_SUBJECT", "LMS일경우 실패시 제목")
                                            .field("FAILED_MSG", "SMS/LMS 전송시 내용")

                                            .field("username", "강민성")
                                            .field("company", "etomars")

                                            .asJson <string>();

            return(request);
        }
            /// <summary>
            /// Creates a new project group. Available only for users who can create groups.
            /// </summary>
            /// <param name="_Config"></param>
            /// <param name="_Name"></param>
            /// <param name="_Path"></param>
            /// <param name="_Description"></param>
            /// <returns></returns>
            public static Group Create(Config _Config, string _Name, string _Path = null, string _Description = null)
            {
                if (_Path == null)
                {
                    _Path = _Name.Trim().Replace(" ", "-").ToLowerInvariant();
                }

                string URI = _Config.APIUrl + "groups?name=" + HttpUtility.UrlEncode(_Name)
                             + "&path=" + HttpUtility.UrlEncode(_Path);

                if (_Description != null)
                {
                    URI += "&description=" + HttpUtility.UrlEncode(_Description);
                }

                HttpResponse <string> R = Unirest.post(URI)
                                          .header("accept", "application/json")
                                          .header("PRIVATE-TOKEN", _Config.APIKey)
                                          .asString();

                if (R.Code < 200 || R.Code >= 300)
                {
                    throw new GitLabServerErrorException(R.Body, R.Code);
                }

                Group RetVal = JsonConvert.DeserializeObject <Group>(R.Body);

                return(RetVal);
            }
        public void WhenICallTheAPIWithPostParametersForUserCreation()
        {
            HttpResponse <string> jsonResponseCreateUser = Unirest.post(GivenIHaveTheAPIUrlToCreateAUser()).header("Content-Type", "application/json").body(jsonRead.JSonConvertCreate()).asJson <string>();

            response       = jsonResponseCreateUser.Body.ToString();
            responseStatus = jsonResponseCreateUser.Code.ToString();
        }
        private void summarize()
        {
            HttpResponse <String> response = Unirest.post("https://textanalysis-text-summarization.p.mashape.com/text-summarizer-text")
                                             .header("X-Mashape-Authorization", key)
                                             //.header("Content-Type", "application/x-www-form-urlencoded")
                                             .header("Accept", "application/json")
                                             .field("sentnum", SoCau)
                                             .field("text", content)
                                             .asJson <String>();
            JObject json = JObject.Parse(response.Body);

            worker.ReportProgress(20);
            double percent = 0;

            result = "";
            for (int i = 0; i < SoCau; i++)
            {
                string contain_string = (string)json.SelectToken("sentences[" + i.ToString() + "]");
                if (contain_string.IndexOf(sub_string, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    result = result + (string)json.SelectToken("sentences[" + i.ToString() + "]") + " ";
                }
                percent += 50 / SoCau;
                worker.ReportProgress((int)Math.Ceiling(percent));
            }
            if (percent < 100)
            {
                worker.ReportProgress(100);
            }
        }
Exemple #8
0
                /// <summary>
                /// Adds a new webhook to a project
                /// </summary>
                /// <param name="_Config"></param>
                /// <param name="_Webhook"></param>
                /// <param name="_Project"></param>
                public static void Add(Config _Config, Webhook _Webhook, Project _Project)
                {
                    try
                    {
                        string URI = _Config.APIUrl + "/projects/" + _Project.id.ToString() + "/hooks";

                        URI += "?url=" + HttpUtility.UrlEncode(_Webhook.url)
                               + "&push_events=" + Convert.ToInt32(_Webhook.push_events).ToString()
                               + "&issues_events=" + Convert.ToInt32(_Webhook.issues_events).ToString()
                               + "&merge_requests_events=" + Convert.ToInt32(_Webhook.merge_requests_events).ToString()
                               + "&tag_push_events=" + Convert.ToInt32(_Webhook.tag_push_events).ToString()
                               + "&note_events=" + Convert.ToInt32(_Webhook.note_events).ToString()
                               + "&enable_ssl_verification=" + Convert.ToInt32(_Webhook.enable_ssl_verification).ToString();

                        HttpResponse <string> R = Unirest.post(URI)
                                                  .header("accept", "application/json")
                                                  .header("PRIVATE-TOKEN", _Config.APIKey)
                                                  .asString();

                        if (R.Code < 200 || R.Code >= 300)
                        {
                            throw new GitLabServerErrorException(R.Body, R.Code);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
    public void recordPlayerHS()
    {
        //to do foolprof
        var highscore = new HighscoreEntry()
        {
            name  = inputField.text,
            score = PlayerPrefs.GetFloat("HighScore"),
        };
        var json = JsonConvert.SerializeObject(highscore);

        var response = Unirest.post("http://localhost/highscores")
                       .body(json)
                       .asJson <string>();

        if (response.Code != 200)
        {
            Debug.Log("Something went wrong (responce error)");
            somethingWentWrong.enabled = true;
            recordMyHS.gameObject.SetActive(false);
            return;
        }

        recorded.enabled = true;
        back.gameObject.SetActive(true);
        recordMyHS.gameObject.SetActive(false);

        //else
        //{
        //    somethingWentWrong.enabled = true;
        //    recordMyHS.gameObject.SetActive(false);
        //}
    }
Exemple #10
0
        /// <summary>
        /// cancelDids is a method that allows you to cancel one or multiple DIDs.
        /// </summary>
        /// <param name="didIds">Required parameter: Array of identifier of the dids to cancel from order</param>
        /// <return>Returns the dynamic response from the API call</return>
        public async Task <dynamic> CreateCancelDidsAsync(
            List <object> didIds)
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);

            queryBuilder.Append("/services/rest/ordering/cancel");


            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.post(queryUrl)
                                  //append request with appropriate headers and parameters
                                  .header("User-Agent", "APIMATIC 2.0")
                                  .header("Accept", "application/json")
                                  .header("Content-type", "application/json; charset=utf-8")
                                  .basicAuth(basicAuthUserName, basicAuthPassword)
                                  .body(APIHelper.JsonSerialize(didIds));

            //invoke request and get response
            HttpResponse <String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
            {
                throw new APIException(@"HTTP Response Not OK", response.Code);
            }

            return(APIHelper.JsonDeserialize <dynamic>(response.Body));
        }
        private void Recognize(string filename)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                byte[] data = File.ReadAllBytes(filename);

                Stream stream = new MemoryStream(data);

                HttpResponse <string> response = Unirest.post("https://lambda-face-recognition.p.mashape.com/recognize")
                                                 .header("X-Mashape-Authorization", mashapeAuthKey)
                                                 .field("album", album)
                                                 .field("albumkey", albumKey)
                                                 .field("files", data)
                                                 .asJson <string>();

                JavaScriptSerializer jss = new JavaScriptSerializer();
                var output = jss.Deserialize <dynamic>(response.Body);

                string entryID = output["photos"][0]["tags"][0]["uids"][0]["prediction"];

                FaceData _facedata = FaceDAO.GetFaceInfoByEntryID(Convert.ToInt32(entryID));

                tboutName.Text  = _facedata.name;
                tboutEmail.Text = _facedata.emailID;

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Face not recognize.");
                Cursor = Cursors.Default;
            }
        }
        public static void TrainAlbum(string name, string emailID, byte[] data)
        {
            try
            {
                //byte[] data1 = File.ReadAllBytes(ConfigurationSettings.AppSettings["SaveImageLocation"]);

                string entryID = FaceDAO.GetEntryIDByName(name).ToString();

                HttpResponse <string> response = Unirest.post("https://lambda-face-recognition.p.mashape.com/album_train")
                                                 .header("X-Mashape-Authorization", mashapeAuthKey)
                                                 .field("album", album)
                                                 .field("albumkey", albumKey)
                                                 .field("entryid", entryID)
                                                 .field("files", data)
                                                 .asString();

                JavaScriptSerializer jss = new JavaScriptSerializer();
                var output = jss.Deserialize <dynamic>(response.Body);

                FaceData _facedata = new FaceData();
                _facedata.name     = name;
                _facedata.emailID  = emailID;
                _facedata.album    = album;
                _facedata.albumkey = albumKey;

                FaceDAO.InsertUserData(_facedata);

                MessageBox.Show("Image capture and trained.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void CreateAlbum(string albumname)
        {
            Cursor.Current = Cursors.WaitCursor;

            mashapeAuthKey = ConfigurationSettings.AppSettings["MashapeAuthKey"];

            HttpResponse <string> response = Unirest.post("https://lambda-face-recognition.p.mashape.com/album")
                                             .header("X-Mashape-Authorization", mashapeAuthKey)
                                             .field("album", albumname)
                                             .asString();

            JavaScriptSerializer jss = new JavaScriptSerializer();
            var output = jss.Deserialize <dynamic>(response.Body);

            foreach (var item in output)
            {
                if (item.Key == "albumkey")
                {
                    albumKey = item.Value;
                }
            }

            Cursor.Current = Cursors.Default;

            if (string.IsNullOrEmpty(albumKey))
            {
                MessageBox.Show("Album is already exist, please try using different name.");
            }
            else
            {
                MessageBox.Show("Albumkey :" + albumKey + " Please store the album name and key to config file");
            }
        }
        /// <summary>
        /// makes post call and returns JObject using Unirest
        /// </summary>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static JObject Post(string url, string token, JObject body)
        {
            JObject jBody = new JObject();

            jBody["data"] = data;
            string bodyStr = jBody.ToString();

            try {
                HttpResponse <string> jsonReponse = Unirest.post(url)
                                                    .header("accept", "application/json")
                                                    .header("Authorization", "Bearer " + token)
                                                    .header("Content-Type", "application/json")
                                                    .header("Host", "api.getbase.com")
                                                    .header("accept-encoding", "application/json")
                                                    .header("content-length", "832")
                                                    .header("Connection", "keep-alive")
                                                    .header("cache-control", "no-cache")
                                                    .body(bodyStr)
                                                    .asString();
                return(JObject.Parse(jsonReponse.Body));
            } catch (Exception ex) {
                Console.WriteLine(ex);
                return(null);
            }
        }
Exemple #15
0
        /// <summary>
        /// Insert one or more objects
        /// </summary>
        /// <return>Returns the CustomersModel response from the API call</return>
        public async Task <CustomersModel> PostInsertCustomersAsync()
        {
            //the base uri for api requests
            string baseUri = Configuration.BaseUri;

            //prepare query string for API call
            StringBuilder queryBuilder = new StringBuilder(baseUri);

            queryBuilder.Append("/Customers");


            //validate and preprocess url
            string queryUrl = APIHelper.CleanUrl(queryBuilder);

            //prepare and invoke the API call request to fetch the response
            HttpRequest request = Unirest.post(queryUrl)
                                  //append request with appropriate headers and parameters
                                  .header("User-Agent", "APIMATIC 2.0")
                                  .header("Accept", "application/json");

            //invoke request and get response
            HttpResponse <String> response = await request.asStringAsync();

            //Error handling using HTTP status codes
            if ((response.Code < 200) || (response.Code > 206)) //[200,206] = HTTP OK
            {
                throw new APIException(@"HTTP Response Not OK", response.Code);
            }

            return(APIHelper.JsonDeserialize <CustomersModel>(response.Body));
        }
 public void Unirest_Should_Return_Correct_URL()
 {
     Unirest.get("http://localhost").URL.OriginalString.Should().Be("http://localhost");
     Unirest.post("http://localhost").URL.OriginalString.Should().Be("http://localhost");
     Unirest.delete("http://localhost").URL.OriginalString.Should().Be("http://localhost");
     Unirest.patch("http://localhost").URL.OriginalString.Should().Be("http://localhost");
     Unirest.put("http://localhost").URL.OriginalString.Should().Be("http://localhost");
 }
 public void Unirest_Should_Return_Correct_Verb()
 {
     Unirest.get("http://localhost").HttpMethod.Should().Be(HttpMethod.Get);
     Unirest.post("http://localhost").HttpMethod.Should().Be(HttpMethod.Post);
     Unirest.delete("http://localhost").HttpMethod.Should().Be(HttpMethod.Delete);
     Unirest.patch("http://localhost").HttpMethod.Should().Be(new HttpMethod("PATCH"));
     Unirest.put("http://localhost").HttpMethod.Should().Be(HttpMethod.Put);
 }
 public static void Unirest_Should_Return_Correct_URL()
 {
     Assert.Equal("http://localhost", Unirest.get("http://localhost").URL.OriginalString);
     Assert.Equal("http://localhost", Unirest.post("http://localhost").URL.OriginalString);
     Assert.Equal("http://localhost", Unirest.delete("http://localhost").URL.OriginalString);
     Assert.Equal("http://localhost", Unirest.patch("http://localhost").URL.OriginalString);
     Assert.Equal("http://localhost", Unirest.put("http://localhost").URL.OriginalString);
 }
 public static void Unirest_Should_Return_Correct_Verb()
 {
     Assert.Equal(HttpMethod.Get, Unirest.get("http://localhost").HttpMethod);
     Assert.Equal(HttpMethod.Post, Unirest.post("http://localhost").HttpMethod);
     Assert.Equal(HttpMethod.Delete, Unirest.delete("http://localhost").HttpMethod);
     Assert.Equal(new HttpMethod("PATCH"), Unirest.patch("http://localhost").HttpMethod);
     Assert.Equal(HttpMethod.Put, Unirest.put("http://localhost").HttpMethod);
 }
Exemple #20
0
        public static Report GetReportFromProvider(Guid userId)
        {
            HttpResponse <Report> jsonResponse = Unirest.post("http://thirdparyservice.org/v1/report")
                                                 .header("accept", "application/json")
                                                 .field("userId", userId)
                                                 .asJson <Report>();

            return(jsonResponse.Body);
        }
Exemple #21
0
        //발신번호 리스트
        public HttpResponse <string> sendnumber_list()
        {
            HttpResponse <string> request = Unirest.post("http://api.apistore.co.kr/kko/1/sendnumber/list/etomars")
                                            .header("x-waple-authorization", "ODI1Ni0xNTI1MzMwOTM1NTIxLTg2YTk0NGZiLTk4NDMtNDJiYS1hOTQ0LWZiOTg0M2IyYmEwNg==")
                                            .header("Content - Type", "application/x-www-form-urlencoded;charset=UTF-8")
                                            .asJson <string>();

            return(request);
        }
Exemple #22
0
        private LambdaCreateAlbumResponse CreateAlbum()
        {
            string responseJson = Unirest.post(BaseUrl + "album")
                                  .header("X-Mashape-Key", ApiKeys.GetCurrentKey())
                                  .header("Accept", "application/json")
                                  .field("album", Guid.NewGuid())
                                  .asString().Body;

            return(JsonConvert.DeserializeObject <LambdaCreateAlbumResponse>(responseJson));
        }
Exemple #23
0
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCountryOfOrigin.Text))
            {
                MessageBox.Show("All fields must be filled in");
                txtCountryOfOrigin.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(txtName.Text))
            {
                MessageBox.Show("All fields must be filled in");
                txtName.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(txtDescription.Text))
            {
                MessageBox.Show("All fields must be filled in");
                txtDescription.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(txtPictureURL.Text))
            {
                MessageBox.Show("All fields must be filled in");
                txtPictureURL.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(txtPrice.Text))
            {
                MessageBox.Show("All fields must be filled in");
                txtPrice.Focus();
                return;
            }

            var product = new Product()
            {
                CountryOfOrigin = txtCountryOfOrigin.Text,
                Name            = txtName.Text,
                Description     = txtDescription.Text,
                PictureURL      = txtPictureURL.Text,
                Price           = float.Parse(txtPrice.Text),
                SellerID        = 1
            };

            var json = JsonConvert.SerializeObject(product);

            HttpResponse <string> jsonResponse = Unirest.post("http://localhost/products")
                                                 .body(json)
                                                 .asJson <String>();

            MessageBox.Show(jsonResponse.Body);

            this.Close();
        }
Exemple #24
0
        private List <LambdaRecognizeResponse> RecognizePhotos(string albumId)
        {
            List <LambdaRecognizeResponse> result = new List <LambdaRecognizeResponse>();

            foreach (var entry in DataSet.SourceImages)
            {
                MemoryStream imageStream = new MemoryStream();
                DataSet.GetImage(entry.Key).Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] data = imageStream.ToArray();

                var watch = Stopwatch.StartNew();

                string responseJson = Unirest.post(BaseUrl + "recognize")
                                      .header("X-Mashape-Key", ApiKeys.GetCurrentKey())
                                      .header("Accept", "application/json")
                                      .field("album", AlbumName)
                                      .field("albumkey", albumId)
                                      .field("files", data)
                                      .asString().Body;

                watch.Stop();
                TimingResults.Add(new TimingModel("RecognizePhotos", entry.Key, watch.ElapsedMilliseconds));

                LambdaRecognizeResponse response = JsonConvert.DeserializeObject <LambdaRecognizeResponse>(responseJson);

                if (response.status != "success")
                {
                    Console.WriteLine("API failed at image {0}.", entry.Key);
                }
                else
                {
                    result.Add(response);
                    try
                    {
                        if (response.photos[0].tags[0].uids == null)
                        {
                            Console.WriteLine("Image {0} not recognized.", entry.Key);
                        }
                        else
                        {
                            string prediction = response.photos[0].tags[0].uids[0].prediction;
                            double confidence = response.photos[0].tags[0].uids[0].confidence;
                            Console.WriteLine("Image {0} recognized as {1} with {2} confidence.", entry.Key, prediction, confidence);
                        }
                    } catch (Exception e)
                    {
                        Console.WriteLine("Encountered some weird exception");
                    }
                }
            }

            return(result);
        }
        private AnimetricsDetectResponse DetectFace(MemoryStream stream)
        {
            string responseJson = Unirest.post(BaseUrl + "detect")
                                  .header("Accept", "application/json")
                                  .field("api_key", ApiKeys.GetCurrentKey())
                                  .field("selector", "FULL")
                                  .field("image", stream.ToArray())
                                  .asString().Body;
            AnimetricsDetectResponse response = JsonConvert.DeserializeObject <AnimetricsDetectResponse>(responseJson);

            return(response);
        }
Exemple #26
0
                public static Issue Add(Config _Config, Project _Project, Issue _Issue)
                {
                    string labels = null;
                    bool   first  = true;

                    if (_Issue.labels != null)
                    {
                        labels = "";

                        foreach (string l in _Issue.labels)
                        {
                            if (!first)
                            {
                                labels += ",";
                            }

                            labels += l;
                            first   = false;
                        }
                    }

                    string URI = _Config.APIUrl + "projects/" + _Project.id.ToString() + "/issues?"
                                 + "title=" + HttpUtility.UrlEncode(_Issue.title)
                                 + "&description=" + HttpUtility.UrlEncode(_Issue.description);

                    if (_Issue.assignee != null)
                    {
                        URI += "&assignee_id=" + _Issue.assignee.id;
                    }
                    if (_Issue.milestone != null)
                    {
                        URI += "&milestone_id=" + _Issue.milestone.id;
                    }
                    if (_Issue.labels != null)
                    {
                        URI += "&labels=" + HttpUtility.UrlEncode(labels);
                    }

                    HttpResponse <string> R = Unirest.post(URI)
                                              .header("accept", "application/json")
                                              .header("PRIVATE-TOKEN", _Config.APIKey)
                                              .asString();

                    if (R.Code < 200 || R.Code >= 300)
                    {
                        throw new GitLabServerErrorException(R.Body, R.Code);
                    }
                    else
                    {
                        return(JsonConvert.DeserializeObject <Issue>(R.Body));
                    }
                }
Exemple #27
0
        async void Order()
        {
            foreach (var item in products)
            {
                var json = JsonConvert.SerializeObject(new { UserID = 1, ProductID = item.ID });

                HttpResponse <String> jsonResponse = await Unirest.post("http://localhost/orders")
                                                     .body(json)
                                                     .asJsonAsync <String>();

                MessageBox.Show(jsonResponse.Body);
            }
            ShoppingCart.ClearCart();
        }
            /// <summary>
            /// Adds a user to the list of group members.
            /// </summary>
            /// <param name="_Config"></param>
            /// <param name="_Group"></param>
            /// <param name="_User"></param>
            /// <param name="_AccessLevel"></param>
            public static void AddMember(Config _Config, Group _Group, User _User, Member.AccessLevel _AccessLevel)
            {
                string URI = _Config.APIUrl + "groups/" + _Group.id.ToString() + "/members/?user_id=" + _User.id + "&access_level=" + Convert.ToInt64(_AccessLevel);

                HttpResponse <string> R = Unirest.post(URI)
                                          .header("accept", "application/json")
                                          .header("PRIVATE-TOKEN", _Config.APIKey)
                                          .asString();

                if (R.Code < 200 || R.Code >= 300)
                {
                    throw new GitLabServerErrorException(R.Body, R.Code);
                }
            }
            /// <summary>
            /// Transfer a project to the Group namespace. Available only for admin
            /// </summary>
            /// <param name="_Config"></param>
            /// <param name="_Group">Group to transfer project to</param>
            /// <param name="_Project">Project to be transferred</param>
            public static void TransferProject(Config _Config, Group _Group, Project _Project)
            {
                string URI = _Config.APIUrl + "groups/" + _Group.id.ToString() + "/projects/" + _Project.id;

                HttpResponse <string> R = Unirest.post(URI)
                                          .header("accept", "application/json")
                                          .header("PRIVATE-TOKEN", _Config.APIKey)
                                          .asString();

                if (R.Code < 200 || R.Code >= 300)
                {
                    throw new GitLabServerErrorException(R.Body, R.Code);
                }
            }
Exemple #30
0
        /// <summary>
        /// Gets a token for the specified subscription.
        /// </summary>
        /// <returns>The encoded JWT token prefixed with the string "Bearer ".</returns>
        /// <remarks>
        /// This method uses a cache to limit the number of request to the token service.
        /// A fresh token can be re-used during its lifetime of 10 minutes. After a successful
        /// request to the token service, this method caches the access token. Subsequent
        /// invocations of the method return the cached token for the next 5 minutes. After
        /// 5 minutes, a new token is fetched from the token service and the cache is updated.
        /// </remarks>
        public string GetAccessToken()
        {
            if (string.IsNullOrWhiteSpace(this.SubscriptionKey))
            {
                return(string.Empty);
            }

            // Re-use the cached token if there is one.
            if ((DateTime.Now - _storedTokenTime) < TokenCacheDuration)
            {
                return(_storedTokenValue);
            }

            try
            {
                HttpResponse <string> response = Unirest.post(ServiceUrl)
                                                 .header(OcpApimSubscriptionKeyHeader, this.SubscriptionKey)
                                                 .asString();

                if (response.Code != 200)
                {
                    throw new Exception($"Error getting AzureAithToken - code: {response.Code} - message: {response.Body}");
                }

                string token = response.Body;
                _storedTokenTime  = DateTime.Now;
                _storedTokenValue = "Bearer " + token;
                return(_storedTokenValue);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //using (var client = new HttpClient())
            //using (var request = new HttpRequestMessage())
            //{
            //    request.Method = HttpMethod.Post;
            //    request.RequestUri = ServiceUrl;
            //    request.Content = new StringContent(string.Empty);
            //    request.Headers.TryAddWithoutValidation(OcpApimSubscriptionKeyHeader, this.SubscriptionKey);
            //    client.Timeout = TimeSpan.FromSeconds(150);
            //    var response = await client.SendAsync(request);
            //    this.RequestStatusCode = response.StatusCode;
            //    response.EnsureSuccessStatusCode();
            //    var token = await response.Content.ReadAsStringAsync();
            //    _storedTokenTime = DateTime.Now;
            //    _storedTokenValue = "Bearer " + token;
            //    return _storedTokenValue;
            //}
        }