public void Post(int id, [FromBody] DataIntermed value) { try { db.EditValuesFromIndex(id, value.acct, value.pin, value.bal, value.fName, value.lName, value.profileImg); } catch (ArgumentException e) { // Catch exception thrown and throw an HTTP exception across the network, to the client var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(String.Format("{0}", e.Message)), // ReasonPhrase cannot contain any newline characters for some reason, so remove them ReasonPhrase = e.Message.Replace('\n', ' ').Replace('\r', ' ') }; throw new HttpResponseException(response); } catch (CommunicationException e) { // Catch exception thrown and throw an HTTP exception across the network, to the client // Indicate to the client that the request's contents is too large to process var response = new HttpResponseMessage(HttpStatusCode.RequestEntityTooLarge) { Content = new StringContent(String.Format("{0}", e.Message)), // ReasonPhrase cannot contain any newline characters for some reason, so remove them ReasonPhrase = e.Message.Replace('\n', ' ').Replace('\r', ' ') }; throw new HttpResponseException(response); } }
private void GoButton_Click(object sender, RoutedEventArgs e) { int index = 0; //Get index to search for try { index = Int32.Parse(IndexBox.Text); //Fetch values at index RestRequest req = new RestRequest(String.Concat("api/getvalues/", index.ToString())); IRestResponse resp = client.Get(req); //Deserialize JSON returned by the response to our request DataIntermed result = JsonConvert.DeserializeObject <DataIntermed>(resp.Content); //Set values using DataIntermed object. FNameBox.Text = result.fname; LNameBox.Text = result.lname; AcctNoBox.Text = result.acct.ToString(); PinBox.Text = result.pin.ToString("D4"); BalanceBox.Text = result.bal.ToString(); } catch (FormatException e1) { IndexBox.Text = ""; } }
/*Getting a specific user at an entry*/ public HttpResponseMessage GetValuesForEntry(int index, out uint acctNo, out uint pin, out double bal, out string fName, out string lName, out byte[] image) { acctNo = 0; pin = 0; bal = 0; fName = ""; lName = ""; image = null; //Initialising values DataIntermed data; HttpRequestMessage Request = new HttpRequestMessage(); try { channel.GetValuesForEntry(index, out acctNo, out pin, out bal, out fName, out lName, out image); //Calling the function in data tier data = new DataIntermed(bal, acctNo, pin, fName, lName, index, image); //making a dataintermed obj var json = new JavaScriptSerializer().Serialize(data); //serializing the dataintermed obj so it can be inside the httpresponsemessage logger.LogFunc("Inside the GetValuesForEntry inside the DataModel Class and have found " + data.fName + " " + data.lName); //Logging success return(Request.CreateErrorResponse(HttpStatusCode.OK, json)); //Returning successmessage and data } catch (FaultException <ExceptionDetail> e) //If it fails { logger.LogFunc("Inside Get Values For Entry: " + "Message: " + e.Message + " StackTrace: " + e.StackTrace); //Logging that it failed HttpResponseMessage hrm = Request.CreateResponse(HttpStatusCode.NotFound); //Status code for caller hrm.Content = new StringContent("Value was not found at that index"); //Error message for user return(hrm); } }
/*Searching for a user by their last name*/ public HttpResponseMessage SearchByLastName(string searchTerm, out uint acctNo, out uint pin, out double bal, out string fName, out string lName, out int index, out byte[] image) { acctNo = 0; pin = 0; bal = 0.0; fName = ""; lName = ""; image = null; index = 0; //Intializing values DataIntermed data; HttpRequestMessage Request = new HttpRequestMessage(); try { channel.SearchByLName(searchTerm, out acctNo, out pin, out bal, out fName, out lName, out index, out image); //Call function in datatier data = new DataIntermed(bal, acctNo, pin, fName, lName, index, image); //Create obj var json = new JavaScriptSerializer().Serialize(data); //Converting js return(Request.CreateErrorResponse(HttpStatusCode.OK, json)); //Send it back with success code } catch (FaultException <ExceptionDetail> e) { logger.LogFunc("Inside Search By Last Name: " + "Message: " + e.Message + " StackTrace: " + e.StackTrace); //log error HttpResponseMessage hrm = Request.CreateResponse(HttpStatusCode.NotFound); //tell caller hrm.Content = new StringContent("Couldn't find someone with that last name"); //error message for user return(hrm); } }
/** * Retrieves the user's details based on the specified last name. Is case sensitive */ public DataIntermed GetValuesFromLName(string query) { logNumber++; Log(String.Format("OPERATION: Get a user from specified last name: {0}", query)); DataIntermed result = new DataIntermed(); // Iterate through each of the entries in the database, until a matching user is encountered. Return that user's details for (int i = 0; i < foob.GetNumEntries(); i++) { foob.GetValuesForEntry(i, out result.acct, out result.pin, out result.bal, out result.fName, out result.lName, out result.profileImg); if (result.lName.Equals(query)) { result.index = i; return(result); } } // If no matching user is encountered, then just return error values result.index = -1; result.acct = 0; result.pin = 0; result.bal = -1; result.fName = "NOT_FOUND"; result.lName = "NOT_FOUND"; result.profileImg = null; return(result); }
public HttpResponseMessage Get(int index) { DataIntermed data = new DataIntermed(); HttpResponseMessage hrm = dataObj.GetValuesForEntry(index, out data.acctNo, out data.pin, out data.bal, out data.fName, out data.lName, out data.image); return(hrm); }
// Make a request to the server to find a user based on their index in the database private async Task <DataIntermed> GetValuesFromIndex(int index) { RestRequest req = new RestRequest(String.Format("/api/getall/{0}", index)); IRestResponse res = await client.ExecuteGetAsync(req); DataIntermed result = JsonConvert.DeserializeObject <DataIntermed>(res.Content); return(result); }
public HttpResponseMessage Post(SearchData searchTerm) { DataModel data = new DataModel(); DataIntermed person = new DataIntermed(); HttpResponseMessage hrm = data.SearchByLastName(searchTerm.searchStr, out person.acctNo, out person.pin, out person.bal, out person.fName, out person.lName, out person.index, out person.image); return(hrm); }
/** * Retrieves the user's details based on the specified index in the database */ public DataIntermed GetValuesFromIndex(int index) { logNumber++; Log(String.Format("OPERATION: Get a user from specified index: {0}", index)); DataIntermed result = new DataIntermed(); result.index = index; foob.GetValuesForEntry(index, out result.acct, out result.pin, out result.bal, out result.fName, out result.lName, out result.profileImg); return(result); }
/*Asynchronously searches for a user at that index*/ private async Task SearchIndexAsync(object sender, RoutedEventArgs e, int index) { //Onclick get the index await Task.Run(() => //Async { //Setting up the api method RestRequest request = new RestRequest("api/getvalues/" + index.ToString()); IRestResponse resp = client.Get(request); //Uses Get over POST //JSON deserialiser to deserialize our object to the class we want //Async this.Dispatcher.Invoke(() => { if (resp.IsSuccessful) //If the httpresponse was successful { TransitionModel transModel = JsonConvert.DeserializeObject <TransitionModel>(resp.Content); //Contains a message and the dataintermed obj DataIntermed dataIntermed = JsonConvert.DeserializeObject <DataIntermed>(transModel.message); //Getting the dataintermed obj //Setting the values in the gui FNameBox.Text = dataIntermed.fName; LNameBox.Text = dataIntermed.lName; BalanceBox.Text = dataIntermed.bal.ToString("C"); AcctNoBox.Text = dataIntermed.acctNo.ToString(); PinBox.Text = dataIntermed.pin.ToString("D4"); /* Sourced from to figure out how to change byte array to bitmap * https://stackoverflow.com/questions/21555394/how-to-create-bitmap-from-byte-array * */ Bitmap bmp; using (var ms = new MemoryStream(dataIntermed.image)) { bmp = new Bitmap(ms); } Photo.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } else //if the httpresponse isn't successful { string errmsg = resp.Content; MessageBox.Show(errmsg); AfterError(); //dispaly in everyfield that the user input is wrong } //Go back from searching visual ChangeUIElements(false); ProgressBar.Visibility = Visibility.Hidden; SearchBox.Visibility = Visibility.Visible; }); }); }
/*Asynchronously searching for someone with that last name*/ private async Task SearchNameAsync(object sender, RoutedEventArgs e) { SearchData mySearch = new APIClasses.SearchData(); mySearch.searchStr = SearchBox.Text.ToUpper(); ProgressBar.Visibility = Visibility.Visible; ChangeUIElements(true); await Task.Run(() => { RestRequest request = new RestRequest("api/search"); request.AddJsonBody(mySearch); //Do the request IRestResponse resp = client.Post(request); this.Dispatcher.Invoke(() => { if (resp.IsSuccessful) //IF that name exists in the database { TransitionModel transModel = JsonConvert.DeserializeObject <TransitionModel>(resp.Content); DataIntermed dataIntermed = JsonConvert.DeserializeObject <DataIntermed>(transModel.message); /*Updating the users fields*/ FNameBox.Text = dataIntermed.fName; LNameBox.Text = dataIntermed.lName; BalanceBox.Text = dataIntermed.bal.ToString("C"); //"C" so its in money form AcctNoBox.Text = dataIntermed.acctNo.ToString(); PinBox.Text = dataIntermed.pin.ToString("D4"); IndexBox.Text = dataIntermed.index.ToString(); Bitmap bmp; using (var ms = new MemoryStream(dataIntermed.image)) { bmp = new Bitmap(ms); } //Converting byte array to bitmap -> see below for reference Photo.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ChangeUIElements(false); ProgressBar.Visibility = Visibility.Hidden; } else //If the response isn't successful { string errmsg = resp.Content; MessageBox.Show(errmsg); AfterError(); } //Return ui back to normal ChangeUIElements(false); ProgressBar.Visibility = Visibility.Hidden; SearchBox.Visibility = Visibility.Visible; }); }); }
// Make a request to the server to find a user based on last name private async Task <DataIntermed> GetValuesFromLName(string query) { SearchData searchQuery = new SearchData(); searchQuery.searchStr = query; RestRequest req = new RestRequest("api/search"); req.AddJsonBody(searchQuery); IRestResponse res = await client.ExecutePostAsync(req); DataIntermed result = JsonConvert.DeserializeObject <DataIntermed>(res.Content); return(result); }
// Click handler for search button private async void Button_Click(object sender, RoutedEventArgs e) { DataIntermed result = new DataIntermed(); int index; bool searchIsIndex = Int32.TryParse(QueryTextBox.Text, out index); if (!string.IsNullOrWhiteSpace(QueryTextBox.Text)) { if (searchIsIndex) { LockUI(); result = await GetValuesFromIndex(index); UnlockUI(); StatusLabel.Text = "STATUS: Ready to edit"; StatusLabel.Background = new SolidColorBrush(Colors.AliceBlue); } else { LockUI(); string query = QueryTextBox.Text; result = await GetValuesFromLName(query); UnlockUI(); StatusLabel.Text = "STATUS: Ready to edit"; StatusLabel.Background = new SolidColorBrush(Colors.AliceBlue); } } if (result != null) { this.temp = result; IndexTextBox.Text = result.index.ToString(); FNameTextBox.Text = result.fName; LNameTextBox.Text = result.lName; BalanceTextBox.Text = result.bal.ToString(); AcctNoTextBox.Text = result.acct.ToString(); PinTextBox.Text = result.pin.ToString("D4"); if (result.profileImg != null) { ProfileImage.Source = ByteArrayToImageSource(result.profileImg); } else { ProfileImage.Source = null; } } }
// GET api/<controller>/5 // Gets account values at import index. public DataIntermed Get(int id) { DataModel data = new DataModel(); uint acct, pin; string fName, lName; int bal; data.GetValuesForEntry(id, out acct, out pin, out fName, out lName, out bal); DataIntermed output = new DataIntermed(); output.acct = acct; output.pin = pin; output.fname = fName; output.lname = lName; output.bal = bal; return(output); }
public DataIntermed Post(SearchData value) { DataModel data = new DataModel(); uint acct, pin; string fName, lName; int bal; lName = value.searchStr; data.SearchByLastName(lName, out fName, out acct, out pin, out bal); DataIntermed output = new DataIntermed(); output.acct = acct; output.pin = pin; output.fname = fName; output.lname = lName; output.bal = bal; return(output); }
private DataIntermed temp; // this field holds data for the currently displayed user public MainWindow() { InitializeComponent(); temp = new DataIntermed(); string endpoint = "https://localhost:44385/"; client = new RestClient(endpoint); RestRequest req = new RestRequest("api/values"); IRestResponse res = client.Get(req); Console.WriteLine(res.StatusCode + "blah"); if (res.StatusCode == HttpStatusCode.ServiceUnavailable || res.StatusCode == 0) { StatusLabel.Text = "ERROR: Server connection cannot be established. This application requires a connection to the server in order to function properly"; } else { NumRecordsTextBox.Content = res.Content; } }
public void OnSearchComplete(IAsyncResult asyncResult) { SearchRequest sOp; //Retrieve async task from import AsyncResult asyncObj = (AsyncResult)asyncResult; //Check if the task has already been ended, before attempting to end if (asyncObj.EndInvokeCalled == false) { //Retrieve delegate sOp = (SearchRequest)asyncObj.AsyncDelegate; //End task, retrieve out variables DataIntermed result = sOp.EndInvoke(asyncObj); //Throws an InvalidOperationException without using dispatcher. this.Dispatcher.Invoke(() => { FNameBox.Text = result.fname; LNameBox.Text = result.lname; AcctNoBox.Text = result.acct.ToString(); PinBox.Text = result.pin.ToString("D4"); BalanceBox.Text = result.bal.ToString(); //Wake up GUI SearchBox.IsReadOnly = false; IndexBox.IsReadOnly = false; GoButton.IsEnabled = true; SearchButton.IsEnabled = true; }); } //Clean up. asyncObj.AsyncWaitHandle.Close(); }
public DataIntermed GetEntry(int id) { DataIntermed data = db.GetValuesFromIndex(id); return(data); }
public DataIntermed Post(SearchData searchQuery) { DataIntermed data = db.GetValuesFromLName(searchQuery.searchStr); return(data); }