public ActionResult Logout(string jsonp = "") { APIResponse api = new APIResponse(); Security.ClearCredentials(); api.Success = true; if (!string.IsNullOrEmpty(jsonp)) { return new JsonpResponse(jsonp, api); } else { return Json(api, JsonRequestBehavior.DenyGet); } }
public async Task <APIResponse> Refresh() { var user = await GetUserFromDb(); var audience = GetCurrentAudience(); if (audience == null) { return(APIResponse.BadRequest(APIErrorCode.Unauthorized)); } return(APIResponse.Success( new RefreshView() { Token = JWT.CreateAuthToken( appConfig: AppConfig, user: user, audience: audience.Value, area: JwtArea.Authorized ), } )); }
public async Task <IActionResult> PutCurrency([FromRoute] int id, [FromBody] CurrencyMaster obj) { obj.CurrencyId = id; if (!ModelState.IsValid) { return(Ok(ModelState.ResponseValidation())); } if (id != obj.CurrencyId) { return(BadRequest()); } try { obj.IsActive = true; await _ICurrency_Repository.Update(obj); } catch (Exception ex) { return(Ok(APIResponse.SetResponse(APIResponseStatus.Error, ex.Message, APIOpStatus.Error, null))); } return(Ok(APIResponse.SetResponse(APIResponseStatus.Ok, "Currency updated successfully.", APIOpStatus.Success, obj))); }
public async void TestSearchWithTeam() { String accessToken = this.RandomString(); String url = this.RandomString(); String teamId = this.RandomString(); List <String> triggerIds = new List <String> { this.RandomString() }; SearchWebhooksRequest req = new SearchWebhooksRequest(); req.Url = url; req.TriggerIds = triggerIds; req.TeamId = teamId; MockAPI <Webhooks> mock = this.MockFor <Webhooks>( HttpMethod.Post, "/api/v1/webhooks.search", m => m.WithContent(req.ToString()).Respond("application/json", "{\"webhooks\":[{\"webhookId\":\"" + this.RandomString() + "\"}]}") ); APIResponse <WebhooksResponseBody> res = await mock.Instance.Search(accessToken, url, triggerIds, null, teamId); mock.Handler.VerifyNoOutstandingExpectation(); Assert.Equal(1, res.Body.Webhooks.Count()); }
/// <summary> /// Realiza a requisição do token de acesso e demais informações do usuário autenticado através do Login Único GOV.BR /// </summary> /// <param name="responseCode">Resposta da requisição de autenticação realizada através da página de login e senha do Governo Federal.</param> /// <returns>Resultado da operação</returns> public async Task <APIResponse> RequestToken(LoginGovBrAuthenticationResponse responseCode) { // Define a URI de requisição ao token string tokenURI = string.Format("{0}?grant_type={1}&code={2}&redirect_uri={3}", _tokenURI, "authorization_code", responseCode.Code, this._request.RedirectURI); // Define os dados a serem enviados via POST Dictionary <string, string> postData = new Dictionary <string, string>(); // Instancia o helper de requisição RequestHelper request = new RequestHelper(); // Realiza a chamada com a autenticação requisitada APIResponse response = await request.DoPostWithAuthentication(tokenURI, this._request.ClientID, this._request.ClientSecret, postData); // Realiza as conversões caso a requisição tenha sido realizada com sucesso if (response.Result) { // Converte a resposta para um objeto de usuário response.Data = JsonConvert.DeserializeObject <LoginGovBrUserData>(response.Data); } return(response); }
public async Task ListCategories() { APIResponse response = await GetCategories.ExecuteStrategy(null); if (response.IsSuccess) { Categories = JsonConvert.DeserializeObject <List <CategoryModel> >(response.Response); /*int categoryIdxCounter = 0; * foreach (var c in Categories) * { * if (Product.IdCategory == c.IdCategory) * { * ProductIndexCategory = categoryIdxCounter; * } * categoryIdxCounter += 1; * }*/ } else { Exception e; } }
public ActionResult <Question> Get(string productId, int pageSize = 10, int pageNumber = 1) { var apiRep = new APIResponse(); var userid = string.Empty; if (HttpContext.User.Identity is ClaimsIdentity identity) { userid = identity.FindFirst(ClaimTypes.Name).Value; } var question = _questionService.GetWithPage(productId, pageSize, pageNumber); apiRep.Error = false; apiRep.Data = question; if (question == null) { apiRep.Error = true; apiRep.Data = null; return(Ok(apiRep)); } return(Ok(apiRep)); }
protected void Page_Load(object sender, EventArgs e) { ApiAuthResponse AuthResponseObj = new ApiAuthResponse(); try { UserProfile UserProfileObj = new UserProfile(Token: CookieProxy.Instance().GetValue("t").ToString(), Email: Request.Form["e"].ToString()); UserTemplate <IUserProfile> Profile = new AdminUserTemplate(UserProfileObj); APIResponse ResponseObj = Profile.Add(); AuthResponseObj.SetAPIResponse(ResponseObj); if (ResponseObj == APIResponse.OK) { // log the event Logger.Instance().Log(Info.Instance(), new LogInfo(Profile.FetchParticularProfile(UserProfileObj).GetEmail() + " added " + Request.Form["e"])); } } catch (Exception ex) { AuthResponseObj.SetAPIResponse(APIResponse.NOT_OK); Logger.Instance().Log(Fatal.Instance(), ex); } Response.Write(new JavaScriptSerializer().Serialize(AuthResponseObj)); }
// get employee details by id private void btnGet1Employee_Click(object sender, EventArgs e) { try { //get first employee id response = shiftPlanning.getEmployees(); int firstEmpId = int.Parse(response.Data["1"].Item["id"].Value); //log txtLog.AppendText("\r\n\r\nMethod: getEmployeeDetails"); //get employee details by id response = shiftPlanning.getEmployeeDetails(firstEmpId); txtLog.AppendText("\r\nEmployee id:" + response.Data["id"].Value + "\r\nName: " + response.Data["name"].Value + "\r\nemail:" + response.Data["email"].Value + "\r\nwage:" + response.Data["wage"].Value); } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
public Dictionary <int, List <FlywheelingNode> > getNodes() { object[] uriChunks = { "systems", "node" }; APIResponse response = this.execute(new GET(uri: String.Join("/", uriChunks))); var responseData = JObject.Parse(response.ToString()); int facility_id = (int)responseData["facility_id"]; var ret = new Dictionary <int, List <FlywheelingNode> >(); var nodeList = new List <FlywheelingNode>(); ret.Add(facility_id, nodeList); foreach (var node in responseData["FlywheelingNodes"]) { nodeList.Add(new FlywheelingNode((JObject)node)); } return(ret); }
public async Task <TResponseObject> GetAsync <TResponseObject>(string apiPath) where TResponseObject : class { TResponseObject responseObject = default; try { LastResponse = null; var response = await GetAsync(apiPath, HttpCompletionOption.ResponseContentRead); LastResponse = new APIResponse(response); var jsonString = await response.Content.ReadAsStringAsync(); if (!string.IsNullOrWhiteSpace(jsonString)) { responseObject = JsonStringToObject <TResponseObject>(jsonString); } return(responseObject); } catch (AggregateException ex) { throw ex.InnerException; } }
public APIResponse UploadFile(Stream fileContent, string fileName, Dictionary <string, string> headers) { try { if (fileContent == null || fileName == null) { throw new ZCRMException("Give valid input for file upload operation."); } this.SetURLDetails(headers); //Fire Request APIResponse response = APIRequest.GetInstance(this).UploadFile(fileContent, fileName); JObject responseData = response.ResponseJSON; JObject details = (JObject)responseData[APIConstants.DETAILS]; response.Data = this.GetZCRMAttachmentObject(details); return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public void CreateInvoice(string subject, long contactId, string productId, string pricebookId, string prodDescription, long quantity) { ZCRMRecord record; record = ZCRMRecord.GetInstance("Invoices", null); //record.SetFieldValue("Account_Name", accountName); record.SetFieldValue("Subject", subject); record.SetFieldValue("Contact_Name", contactId); //record.SetFieldValue("Billing_Country", billingCountry); //record.SetFieldValue("Billing_City", billingCity); //record.SetFieldValue("Billing_Street", billingStreet); //record.SetFieldValue("Billing_Code", billingCode); //record.SetFieldValue("Due_Date", dueDate.ToShortDateString()); record.SetFieldValue("Product_Details", CreateProductDetails(productId, pricebookId, prodDescription, quantity)); List <string> trigger = new List <string>() { "workflow", "approval", "blueprint" }; string larID = "3477061000004353013"; APIResponse response1 = record.Create(trigger, larID); ZCRMRecord record1 = (ZCRMRecord)response1.Data; }
/// <summary> /// Method Name : GetPassword /// Author : Sanket Prajapati /// Creation Date : 2 Dec 2017 /// Purpose : For password verification /// Revision : By Vivek Bhavsar on 23 Jan 2018 for code refactoring add sub methods /// </summary> public async Task <ServiceResponse> GetPassword(string passsword) { string errorMessage = string.Empty; bool isTermAgree = false; PasswordModel passwordModel = GetPasswordModel(passsword); errorMessage = loginValidateServices.ValidatePasswordModel(passwordModel); if (string.IsNullOrEmpty(errorMessage)) { APIResponse <CustomerModel> response = await CheckPasswordAsync(passwordModel); errorMessage = response.Message; if (response.STATUS) { isTermAgree = Convert.ToBoolean(response.DATA.TermsAgreed); errorMessage = string.Empty; } } return(getServiceResponse(errorMessage, isTermAgree)); }
/// <summary> /// 抢单 /// </summary> /// <param name="pRequest"></param> /// <returns></returns> private string GrabOrder(string pRequest) { var rd = new APIResponse <GrabOrderRD>(); var rdData = new GrabOrderRD(); var rp = pRequest.DeserializeJSONTo <APIRequest <GrabOrderRP> >(); if (string.IsNullOrEmpty(rp.UserID)) { throw new APIException("【UserID】不能为空"); } if (rp.Parameters == null) { throw new ArgumentException(); } rp.Parameters.Validate(); ServiceOrderManager.Instance.ApplyOrder(rp.Parameters.ServiceOrderNO, rp.UserID); rdData.Msg = "抢单中…"; rd.Data = rdData; return(rd.ToJSON()); }
public void CreateContact(string firstName, string lastName, string phone, string email, string country, string city, string street, string zip) { ZCRMRecord record; record = ZCRMRecord.GetInstance("Contacts", null); record.SetFieldValue("First_Name", firstName); record.SetFieldValue("Last_Name", lastName); record.SetFieldValue("Phone", phone); record.SetFieldValue("Email", email); record.SetFieldValue("Mailing_City", city); record.SetFieldValue("Mailing_Street", street); record.SetFieldValue("Mailing_Country", country); record.SetFieldValue("Mailing_Zip", zip); List <string> trigger = new List <string>() { "workflow", "approval", "blueprint" }; string larID = "3477061000004353013"; APIResponse response = record.Create(trigger, larID); ZCRMRecord record1 = (ZCRMRecord)response.Data; }
public ActionResult UpdateStatus(string id, string status) { var apiRep = new APIResponse(); List <Order> Orders = _orderService.Get(); if (Orders == null) { apiRep.Error = true; apiRep.Message = "Can't not find list Order"; return(BadRequest(apiRep)); } foreach (Order item in Orders) { if (item.Id == id) { item.orderinfo.status = status; apiRep.Error = false; apiRep.Data = item; _orderService.Update(item.Id, item); } } return(Ok(apiRep)); }
public APIResponse UploadLinkAsAttachment(string attachmentUrl) { try { requestMethod = APIConstants.RequestMethod.POST; urlPath = parentRecord.ModuleAPIName + "/" + parentRecord.EntityId + "/" + relatedList.ApiName; requestQueryParams.Add("attachmentUrl", attachmentUrl); APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject responseDetails = (JObject)responseData[APIConstants.DETAILS]; response.Data = GetZCRMAttachment(responseDetails); return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public PaymentRequestResult(APIResponse apiResponse) { if (apiResponse.Header.ErrorCode == 0) { ResultMessage = apiResponse.Body.CardHolderErrorMessage; ResultMerchantMessage = apiResponse.Body.MerchantErrorMessage; if (!String.IsNullOrEmpty(apiResponse.Body.Result)) { Result = (Result)Enum.Parse(typeof(Result), apiResponse.Body.Result); } Url = apiResponse.Body.Url; DynamicJavascriptUrl = apiResponse.Body.DynamicJavascriptUrl; PaymentRequestId = apiResponse.Body.PaymentRequestId; } else { Result = Result.SystemError; ResultMerchantMessage = apiResponse.Header.ErrorMessage; ResultMessage = "An error occurred"; } }
public async Task <APIResponse <T> > GetAsync <T>(string url) { var client = this.PreparedClient(); var response = await client.GetAsync(url); var responseText = await response.Content.ReadAsStringAsync(); var responseObj = new APIResponse <T>(); responseObj.IsSuccess = response.IsSuccessStatusCode; responseObj.StatusCode = (int)response.StatusCode; if (response.IsSuccessStatusCode) { responseObj.Result = JsonConvert.DeserializeObject <T>(responseText); } else { responseObj.Error = JsonConvert.DeserializeObject <APIError>(responseText); } return(responseObj); }
public ActionResult UpdateUser(string obj) { APIResponse = new APIResponse(); try { UsersDetailsModel usersDetailsModel = JsonConvert.DeserializeObject <UsersDetailsModel>(obj); HttpClient client = new HttpClient(); usersDetailsModel.Id = SessionHelper.sessionObjects.UserID; usersDetailsModel.assessmentID = SessionHelper.sessionObjects.AssessmentID; var result = client.PostAsJsonAsync(apiUrl + "/UserManagement/UpdateUser", usersDetailsModel).Result; if (result.IsSuccessStatusCode) { var Result = result.Content.ReadAsStringAsync().Result; APIResponse = JsonConvert.DeserializeObject <APIResponse>(Result); } } catch (Exception ex) { } return(Json(APIResponse, JsonRequestBehavior.AllowGet)); }
public async Task DeleteCategoria() { try { ParametersRequest parametros = new ParametersRequest(); parametros.Parametros.Add(Categoria.IdCategoria.ToString()); APIResponse response = await EliminarCategoria.EjecutarEstrategia(null, parametros); if (response.IsSuccess) { ((MessageViewModel)PopUp.BindingContext).Message = "Categoría eliminada exitosamente"; await PopupNavigation.Instance.PushAsync(PopUp); } else { ((MessageViewModel)PopUp.BindingContext).Message = "Error al eliminar la categoría"; await PopupNavigation.Instance.PushAsync(PopUp); } } catch (Exception e) { } }
protected string DoDelNewsType(string pRequest) { //请求参数反序列化 var rp = pRequest.DeserializeJSONTo <APIRequest <DelNewsTypeRP> >(); //参数校验 rp.Parameters.Validate(); //构造响应数据 var rd = new APIResponse <DelNewsTypeRD>(new DelNewsTypeRD()); try { //Get News Detail Info PrivateLNewsTypeBLL.Delete(rp.Parameters.TypeIds.Split(',')); } catch (Exception ex) { Loggers.Exception(new ExceptionLogInfo(ex)); throw new Exception(ex.Message, ex); } return(rd.ToJSON()); }
protected string DoGetNumberTypeMapping(string pRequest) { //请求参数反序列化 var rp = pRequest.DeserializeJSONTo <APIRequest <GetNumberTypeMappingRP> >(); //参数校验 rp.Parameters.Validate(); //构造响应数据 var rd = new APIResponse <GetNumberTypeMappingRD>(new GetNumberTypeMappingRD()); try { //Get News Detail Info rd.Data.TypeIds = PrivateLNumberTypeMappingBLL.GetNumberTypeMapping(rp.Parameters); } catch (Exception ex) { Loggers.Exception(new ExceptionLogInfo(ex)); throw new Exception(ex.Message, ex); } return(rd.ToJSON()); }
public ActionResult AddProduct(P dto) { var apiRep = new APIResponse(); var userId = string.Empty; if (HttpContext.User.Identity is ClaimsIdentity identity) { userId = identity.FindFirst(ClaimTypes.Name).Value; } P[] products = { dto }; var Cart = new Cart { UserId = userId, Products = products }; _cartService.Insert(Cart); apiRep.Error = false; apiRep.Data = Cart; return(Ok(apiRep)); }
protected string DoDelNewsInfo(string pRequest) { //请求参数反序列化 var rq = pRequest.DeserializeJSONTo <APIRequest <DelNewsInfoRP> >(); //参数校验 rq.Parameters.Validate(); //构造响应数据 var rp = new APIResponse <DelNewsInfoRD>(new DelNewsInfoRD()); try { //删除 PrivateLNewsBLL.DelNewsInfo(rq.Parameters.NewsIds); } catch (Exception ex) { Loggers.Exception(new ExceptionLogInfo(ex)); throw new Exception(ex.Message, ex); } return(rp.ToJSON()); }
public ActionResult GetCurrentItems() { var userId = string.Empty; if (HttpContext.User.Identity is ClaimsIdentity identity) { userId = identity.FindFirst(ClaimTypes.Name).Value; } var cart = _cartService.GetUserId(userId); var apiRep = new APIResponse(); if (cart != null) { apiRep.Data = cart.Products.Length; } else { apiRep.Data = 0; } return(Ok(apiRep)); }
/// <summary> /// Method Name : SetPutMoveDataResponse /// Author : Vivek Bhavsar /// Creation Date : 23 Jan 2018 /// Purpose : Refactoring : seperate response through switch case based on http response input /// Revision : /// </summary> /// <typeparam name="T"></typeparam> /// <param name="response"></param> /// <param name="httpResponseMessage"></param> private void SetPutMoveDataResponse <T>(APIResponse <T> response, HttpResponseMessage httpResponseMessage) { switch (httpResponseMessage.StatusCode) { case HttpStatusCode.OK: response.STATUS = true; response.Message = Resource.msgPutMoveDataOK; break; case HttpStatusCode.BadRequest: response.Message = Resource.msgBadRequest; break; case HttpStatusCode.NotFound: case HttpStatusCode.NoContent: response.Message = Resource.msgPutMoveDataNotFound; break; default: response.Message = apiHelper.GetAPIResponseStatusCodeMessage(httpResponseMessage); break; } }
protected string DoSetNewsMap(string pRequest) { //请求参数反序列化 var rp = pRequest.DeserializeJSONTo <APIRequest <SetNewsMapRP> >(); //参数校验 rp.Parameters.Validate(); //构造响应数据 var rd = new APIResponse <SetNewsMapRD>(new SetNewsMapRD()); try { //Get News Detail Info PrivateLNewsMicroMappingBLL.SetNewsMap(rp.Parameters.MicroNumberId, rp.Parameters.MicroTypeId, rp.Parameters.NewIds); } catch (Exception ex) { Loggers.Exception(new ExceptionLogInfo(ex)); throw new Exception(ex.Message, ex); } return(rd.ToJSON()); }
/// <summary> /// Refreshes a valid accessToken. It can user to keep the user logged in. /// </summary> /// <param name="accessToken">The accessToken to be refreshed</param> /// <param name="requestUser">If true the user object will be returned</param> /// <returns>True if the Refreshed proccess was succefull.</returns> public static async Task <bool> Try(string accessToken, bool requestUser) { lastResponse = null; var jsonRequest = new Payload { accessToken = accessToken, requestUser = requestUser, }; string responseString; try { responseString = await NetConnector.MakeRequest(jsonRequest, URL); } catch { return(false); } lastResponse = JsonConvert.DeserializeObject <APIResponse>(responseString); return(true); }
public async Task Invoke(HttpContext context) { try { await _next.Invoke(context); } catch (Exception ex) { _logger.LogError(0, ex, ex.Message); context.Response.StatusCode = 500; } if (!context.Response.HasStarted) { context.Response.ContentType = "application/json"; var response = new APIResponse((HttpStatusCode)context.Response.StatusCode); var json = JsonConvert.SerializeObject(response); await context.Response.WriteAsync(json); } }
IEnumerator WWWRequest (string url, byte[] data, Action<APIResponse> onResponse) { Dictionary<string, string> headers = BuildHeaders(); url = BuildURL(url); #if UNITY_DEBUG Logger.Log(string.Format("<b>Request: </b><color=blue>{0}</color>, Data lenght: {1}", url, data.Length)); #endif WWW w = new WWW(url, data, headers); yield return w; APIResponse response = new APIResponse(); if (string.IsNullOrEmpty(w.error)) { response.Status = ResponseStatus.OK; response.ResponseBinaries = w.bytes; } else { try { string strCode = Regex.Replace(w.error, @"[^0-9]+", ""); response.Status = (ResponseStatus)int.Parse(strCode); Logger.LogError(w.error); } catch { Logger.LogError("Unexpected error!"); } } onResponse(response); Destroy(gameObject); }
// get employee details by id private void btnGet1Employee_Click(object sender, EventArgs e) { try { //get first employee id response = shiftPlanning.getEmployees(); int firstEmpId = int.Parse(response.Data["0"].Item["id"].Value); //log txtLog.AppendText("\r\n\r\nMethod: getEmployeeDetails"); //get employee details by id response = shiftPlanning.getEmployeeDetails(firstEmpId); txtLog.AppendText("\r\nEmployee id:" + response.Data["id"].Value + "\r\nName: " + response.Data["name"].Value + "\r\nemail:" + response.Data["email"].Value + "\r\nwage:" + response.Data["wage"].Value); } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
//get list of employees private void btnGetEmployee_Click(object sender, EventArgs e) { try { //log txtLog.AppendText("\r\n\r\nMethod: getEmployees"); //call method response = shiftPlanning.getEmployees(); for (int i = 0; i < response.Data.Count; i++) { txtLog.AppendText("\r\n\r\nEmployee Id: " + response.Data[i.ToString()].Item["id"].Value + "\r\nName: " + response.Data[i.ToString()].Item["name"].Value + "\r\nemail:" + response.Data[i.ToString()].Item["email"].Value + "\r\nwage:" + response.Data[i.ToString()].Item["wage"].Value); } } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
//Login to Session private void btnLogin_Click(object sender, EventArgs e) { //initialize SDK shiftPlanning = new ShiftPlanning(txtAPIKey.Text); if (shiftPlanning.getLoginStatus()) { } try { //log txtLog.AppendText("\r\n\r\nMethod: doLogin"); //login to session //preparing list of request field RequestFields login_details = new RequestFields(); login_details.Add("username", txtUsername.Text); login_details.Add("password", txtPassword.Text); //calling method response = shiftPlanning.doLogin(login_details); //checking response if (response.Status.Code == "1") {//if login success //get the current session session = shiftPlanning.getSession(); //update log txtLog.AppendText("\r\nLogin " + response.Status.Text + "\r\nWelcome " + response.Data["employee"].Item["name"].Value + "\r\nBusiness Name: " + response.Data["business"].Item["name"].Value + "\r\nToken: " + response.Status.Token); btnLogout.Enabled = true; } else { //update log txtLog.AppendText("\r\n\r\nLogin " + response.Status.Text + "\r\nError: " + response.Status.Error); } } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
public APIResponseLogin(APIResponse response) { Cast(response); }
private void btnChangeWages_Click(object sender, EventArgs e) { try { //get first employee id response = shiftPlanning.getEmployees(); int firstEmpId = int.Parse(response.Data["0"].Item["id"].Value); //log txtLog.AppendText("\r\n\r\nMethod: updateEmployee"); string wage = Interaction.InputBox("Please enter the wages", "C# SDK", null, 0, 0); //preparing list of request field RequestFields employee_data = new RequestFields(); employee_data.Add("id", firstEmpId); employee_data.Add("wage", wage); response = shiftPlanning.updateEmployee(employee_data); if (response.Status.Code == "1") txtLog.AppendText("\r\nEmployee record updated."); } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
private void getShDetailById_Click(object sender, EventArgs e) { try { //get shift details string shift_id = Interaction.InputBox("Please enter shift id", "C# SDK", shiftid, 0, 0); txtLog.AppendText("\r\n\r\nMethod: getShiftDetails"); string msg; response = shiftPlanning.getShiftDetails(int.Parse(shift_id)); //checking response if (response.Status.Code == "1") {//if login success msg = "\r\nShift Id:" + response.Data["id"].Value + "\r\nShift's Schedule Name: " + response.Data["schedule_name"].Value + "\r\nfrom: " + response.Data["start_time"].Item["time"].Value + " to " + response.Data["end_time"].Item["time"].Value + "\r\nstart date: " + response.Data["start_date"].Item["day"].Value + "/" + response.Data["start_date"].Item["month"].Value + "/" + response.Data["start_date"].Item["year"].Value + "\r\nend date: " + response.Data["end_date"].Item["day"].Value + "/" + response.Data["end_date"].Item["month"].Value + "/" + response.Data["end_date"].Item["year"].Value; if (response.Data["employees"].Item != null) {//if employee assigned msg += "\r\n Employees assigned for this job:"; for (int i = 0; i < response.Data["employees"].Item.Count; i++) { msg += "\r\n " + i.ToString() + ". " + response.Data["employees"].Item[i.ToString()].Item["name"].Value; } } else msg += "\r\nNo employee assigned for this job"; txtLog.AppendText(msg); } else { //update log txtLog.AppendText("\r\nShift Details Method " + response.Status.Text + "\r\nError: " + response.Status.Error); } } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
public APIResponseRegister (APIResponse response) { Cast(response); }
private void btnShiftDetails_Click(object sender, EventArgs e) { try { txtLog.AppendText("\r\n\r\nMethod: getShifts"); RequestFields filter_fields = new RequestFields(); //create filters //filter_fields.Add("schedule", 35316); response = shiftPlanning.getShifts(filter_fields); for (int i = 0; i < response.Data.Count; i++) { string msg; msg = "\r\n\r\nShift Id: " + response.Data[i.ToString()].Item["id"].Value + "\r\nShift's Schedule Name: " + response.Data[i.ToString()].Item["schedule_name"].Value; txtLog.AppendText(msg); if (i == 1) shiftid = response.Data[i.ToString()].Item["id"].Value; } } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
private void WriteResult(APIResponse response, string pValueRoot) { if (response == null) { TextBox1.Text = "No response object."; return; } if (response.Error) { TextBox1.Text = response.Message; return; } if (response.Value == null) { TextBox1.Text = "No response value."; return; } if (response.Value.Length == 0) { TextBox1.Text = "No response value."; return; } if (pValueRoot == null) { TextBox1.Text = "No root value."; return; } if (pValueRoot.Length == 0) { TextBox1.Text = "No root value."; return; } XmlDocument xml = new XmlDocument(); StringReader reader = new StringReader(response.Value); XDocument xdoc = XDocument.Load(reader); List<string> itemLineList = new List<string>(); var items = xdoc.Descendants(pValueRoot); foreach (XElement el in items.Descendants()) { itemLineList.Add(string.Format("{0}\t\t{1}", el.Name, el.Value)); } string itemLines = string.Join("\r\n", itemLineList.ToArray()); TextBoxResult.Text = string.Format("{0}", itemLines); }
private void btnUploadFile_Click(object sender, EventArgs e) { try { txtLog.AppendText("\r\n\r\nMethod: createAdminFile"); RequestFields fields = new RequestFields(); fields.Add("filename", txtFileName.Text); response = shiftPlanning.createAdminFile(fields); txtLog.AppendText("\r\nCreate File Status: " + response.Status.Text); } catch (Exception ex) { txtLog.AppendText("\r\n\r\nException: " + ex.Message); } }
public void Cast (APIResponse response) { this.Status = response.Status; this.Message = response.Message; this.ResponseBinaries = response.ResponseBinaries; }
public ActionResult Login(string email, string password, string jsonp = "") { APIResponse api = new APIResponse(); List<string> error = new List<string>(); bool bPsw = false, bUid = false; if (!string.IsNullOrEmpty(email)) { if (Utils.Validate.EmailAddress(email)) { bUid = true; } else { error.Add("Email format is not valid"); } } else { error.Add("Email is required"); } if (!string.IsNullOrEmpty(password)) { if (Utils.Validate.PasswordFormat(password)) { bPsw = true; } else { error.Add("Password format is not valid"); } } else { error.Add("Password is required"); } if (bUid && bPsw) { if (Security.Authenticate(email, password, false)) { api.Success = true; } else { error.Add("Invalid authentication credentials. Please try again."); } } api.Errors = error; if (!string.IsNullOrEmpty(jsonp)) { return new JsonpResponse(jsonp, api); } else { return Json(api, JsonRequestBehavior.DenyGet); } }
public ActionResult WebConferenceRequest(string name, string email, string date, string time, string jsonp = "") { APIResponse api = new APIResponse(); List<string> error = new List<string>(); bool bValid = true; if (WebIT.Lib.Utils.Validate.ExpressionType(name) != Lib.Type.xPression.Numeric && name != "name") { bValid = bValid && true; } else { bValid = bValid && false; error.Add("Invalid name format"); } if (WebIT.Lib.Utils.Validate.EmailAddress(email) && email != "email") { bValid = bValid && true; } else { error.Add("Invalid email format"); } if (date != "requested date") { bValid = bValid && true; } else { bValid = bValid && false; error.Add("Invalid date format"); } if (time != "requested time") { bValid = bValid && true; } else { bValid = bValid && false; error.Add("Invalid time format"); } if (bValid) { //send email string body = "<table>" + "<tr>" + "<td>Name</td><td>" + name + "</td>" + "</tr>" + "<tr>" + "<td>Email Address</td><td>" + email + "</td>" + "</tr>" + "<tr>" + "<td>Date</td><td>" + date + "</td>" + "</tr>" + "<tr>" + "<td>Time</td><td>" + time + "</td>" + "</tr>" + "</table>"; try { Utils.Email.sendEmail(Config.ActiveConfiguration.Mail.From, Config.Email.Form.WebConferenceRequest.Recipient, Config.Email.Form.WebConferenceRequest.Subject, body, true, Config.ActiveConfiguration.Mail.Host, Config.ActiveConfiguration.Mail.Port); api.Success = true; } catch { error = new List<string>() { "An unknown error occurred. Please try again in a few minutes." }; api.Success = false; } } else { api.Success = false; } api.Errors = error; if (!string.IsNullOrEmpty(jsonp)) { return new JsonpResponse(jsonp, api); } else { return Json(api, JsonRequestBehavior.DenyGet); } }
private string perform_request() { Uri uri = new Uri(api_endpoint); string boundary = "----------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri); webrequest.CookieContainer = new CookieContainer(); webrequest.ContentType = "multipart/form-data; boundary=" + boundary; webrequest.Method = "POST"; webrequest.Timeout = 120000; //check whether it is file upload string uploadfile = ""; if (request.RequestFields.ContainsKey("filepath")) {//get the file name to upload uploadfile = request.RequestFields["filepath"].ToString(); request.RequestFields.Remove("filepath"); } //get JSON format string for 'data' parameter string data = request.GetEncoded(); //prepare header for HTTP POST StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(boundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\""); sb.Append("data"); sb.Append("\""); sb.Append("\r\n"); sb.Append("\r\n"); sb.Append(data); sb.Append("\r\n"); if (uploadfile != "") {//if createfile function, prepare 'filedata' field sb.Append("--"); sb.Append(boundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\""); sb.Append("filedata"); sb.Append("\""); sb.Append("\r\n"); sb.Append("\r\n"); } Stream requestStream = null; try { string postHeader = sb.ToString(); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); FileStream fileStream = null; long length = 0; if (uploadfile != "") {//if file upload, find the length of the file fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read); length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length; } else {//if no file upload, just get lenght of the 'data' field length = postHeaderBytes.Length; } webrequest.ContentLength = length; requestStream = webrequest.GetRequestStream(); // Write out our post header requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); if (uploadfile != "") {// if file upload, write out the file contents byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) requestStream.Write(buffer, 0, bytesRead); // Write out the trailing boundary requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); } } finally { if (requestStream != null) requestStream.Close(); } // Read the response StreamReader reader = null; HttpWebResponse webResponse = (HttpWebResponse)webrequest.GetResponse(); try { // Read the responce reader = new StreamReader(webResponse.GetResponseStream()); if (webResponse.StatusCode == HttpStatusCode.OK) { // initiate new response object response = new APIResponse(); // decode response response.DecodeResponse(reader); if (this._init == 1) {//if it is first call, get the 'token' this.setSession(); } return response.Status.Code; //TO DO: need to implement debug (to log.txt) } else { throw new Exception(this.internal_errors(2)); } } finally { if (webResponse != null) webResponse.Close(); } }
public bool httpRequst(string action) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); if (apiRequest.requireAccessToken) { request.Headers.Add("Authorization", "Bearer " + this.accessToken); } foreach (KeyValuePair<string, string> header in apiRequest.headers) { request.Headers.Add(header.Key, header.Value); } request.Accept = apiRequest.accept; request.Method = action; request.ContentType = apiRequest.contentType; request.KeepAlive = apiRequest.keepAlive; request.SendChunked = apiRequest.SendChunked; request.UserAgent = apiRequest.userAgent; if (apiRequest.binaryData.Length > 0) { request.ContentLength = apiRequest.binaryData.Length; Stream dataStream; dataStream = request.GetRequestStream(); dataStream.Write(apiRequest.binaryData, 0, apiRequest.binaryData.Length); dataStream.Close(); } else { request.ContentLength = 0; } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); apiResponse = new APIResponse(response); } catch (WebException we) { errorResponse = getWebException(we); return false; } catch (Exception ex) { errorResponse = ex.Message; return false; } return true; }