Driver becomes null in TearDown method of base class - c#

In my TearDown() method located in my Base class, my driver is becoming null before I try to quit it. This has a result of me getting a NullReferenceException.
When I initially enter the TearDown() method the driver has a value but as I try to move it to different locations, it's value gets lost. So quiting the driver at Position 3 or further brings the NullReferenceException.
In my code below I will show the various points that I close my driver. I have narrowed it down to 1 line where the driver looses it's value (Position 3). I want to maintain the driver until I take a screenshot if a test fails and at that point close the driver.
Why does my driver loose it's value once it reaches position 3?
Code:
[TearDown]
public async Task TearDown()
{
//driver.Value.Quit(); //Position 1 driver has a value at this point and not null
if (testrail == "True")
{
// arrange
RestRequest restRequest = new RestRequest($"index.php?/api/v2/get_runs/7&limit=1", Method.Get);
string authInfo = Base64StringConverter.GetBase64String("email:password");
restRequest.AddHeader("Authorization", "Basic " + authInfo);
restRequest.AddHeader("Content-Type", "application/json");
//driver.Value.Quit(); //Position 2: driver has a value at this point and not null
// act
RestResponse<GetRun> response = await restClient.ExecuteAsync<GetRun>(restRequest);
//driver.Value.Quit(); //Position 3: driver has lost it's value at this point and is null
HttpStatusCode statusCode = response.StatusCode;
// assert
var data = JsonConvert.DeserializeObject<List<GetRun>>(response.Content);
var a = data[0];
var run = a.Id;
Console.WriteLine(response.Content);
var testCase = TestContext.CurrentContext.Test.Properties.Get("Category").ToString().Replace("C", "");
Console.WriteLine(testCase);
var result = TestContext.CurrentContext.Result.Outcome.Status;
var testRailStatus = result switch
{
TestStatus.Failed => ResultStatus.Failed,
TestStatus.Passed => ResultStatus.Passed,
_ => ResultStatus.Retest
};
Console.WriteLine(testRailStatus.ToString());
string status = testRailStatus.ToString();
int status_id;
if (status == "Passed")
{
status_id = 1;
}
else
{
status_id = 5;
TakeScreenshot();
}
Console.WriteLine(status_id);
RestRequest addResult = new RestRequest($"index.php?/api/v2/add_result_for_case/{run}/{testCase}", Method.Post);
addResult.AddHeader("Authorization", "Basic " + authInfo);
addResult.AddHeader("Content-Type", "application/json");
//Add body with type class
addResult.RequestFormat = DataFormat.Json;
addResult.AddJsonBody(new { status_id = status_id });
var newResponse = await restClient.ExecuteAsync(addResult);
}
driver.Value.Quit();
}
public void TakeScreenshot()
{
Screenshot screenshot = (driver.Value as ITakesScreenshot).GetScreenshot();
string filepath = "C:\\Selenium\\";
string timestamp = DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss");
screenshot.SaveAsFile(filepath + timestamp + "_Screenshot.png", ScreenshotImageFormat.Png);
}

Related

if else conditions not checking properly in c#?

I am coming to a problem where I am checking if some of the elements key values are valid in order to proceed with the QR code scanning. For example: If my Active attribute is true, and completed is false and the schedule time is current time +- 30 minutes of start window then proceed with the scanning. If not, let me show them an error. I tried implementing the checking part with a simple if - but only checking the active, and completed key values. Can anyone check and help me solve this issue. thanks for the help.
here is my code:
public void ScanQrCode()
{
BarcodeScanner.Scan(async (barCodeType, barCodeValue) =>
{
BarcodeScanner.Stop();
var results = JsonConvert.DeserializeObject<dynamic>(barCodeValue);
var gettingTheName = (string) results.Evaluation.Value;
TextHeader.text = gettingTheName;
var qrCodeString = $"***************.firebaseio.com/Evaluations/.json?orderBy=\"$key\"&startAt=\"{gettingTheName}\"&limitToFirst=1";
Debug.Log(barCodeValue);
var qrCodeObj = JsonConvert.DeserializeObject<dynamic>(qrCodeString);
try
{
bool parseSuccessful = DateTime.TryParse("ScheduleStartTime", out var scheduledStartTime);
if (results.Contains("Active").Equals(true) &&
results.Contains("Completed").Equals(false) &&
DateTime.Now < scheduledStartTime.AddMinutes(30) &&
DateTime.Now > scheduledStartTime.AddMinutes(-30)) {
var matchingLink = new WebClient().DownloadString(qrCodeString);
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(matchingLink);
var candidateId = obj.First.First["CandiateID"].ToString();
string page = $"https://***********.firebaseio.com/Candidates/.json?orderBy=\"$key\"&startAt=\"{candidateId}\"&limitToFirst=1";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// Reading the string.
Dictionary<string, Candidates> evaluationDictionary = new Dictionary<string, Candidates>();
string result = await content.ReadAsStringAsync();
evaluationDictionary = JsonConvert.DeserializeObject<Dictionary<string, Candidates>>(result);
Debug.Log(evaluationDictionary);
foreach (Candidates candidates in evaluationDictionary.Values)
{
string evaluationMessage = candidates.FirstName + " " + candidates.LastName;
candidateMessage = GetComponent<Text>();
candidateMessage.text = evaluationMessage;
}
// Getting a reference to the text component.
candidateMessage = GetComponent<Text>();
candidateMessage.text = matchingLink.ToString();
candidateMessage.text = matchingLink.Trim(new char[] {'"'});
}
}
else
{
EditorUtility.DisplayDialog("Incorrect credentials", "Please scan a valid QR code", "OK");
}
}
catch (Exception e)
{
Console.WriteLine(e);
SceneManager.LoadScene("Verify");
throw;
}
});
}
}
JSON:
{
"Active": true,
"Completed": false,
"ScheduleStartTime": "2019-12-16T20:10:57.649418-08:00"
}
Yeah. I was kind of stuck on that part too. I tried doing it by adding
&& qrCodeString.Contains("ScheduleStartTime").Equals(I GOT STUCK IN
HERE)
I'd accomplish this portion by parsing the date string to a DateTime object, then comparing the current time with your new DateTime shifted in both directions.
I might do something like this:
try {
bool parseSuccessful = DateTime.TryParse( ScheduledStartTimeFromJSON, out var scheduledStartTime );
if ( qrCodeString.Contains( "Active" ).Equals( true ) &&
qrCodeString.Contains( "CompletedMessage" ).Equals( false ) &&
DateTime.Now < scheduledStartTime.AddMinutes(30) &&
DateTime.Now > scheduledStartTime.AddMinutes( -30 ) ) {
var matchingLink = new WebClient().DownloadString( qrCodeString );
...
}
}
You should also check to make sure the date was parsed successfully before comparing it to anything.
According to your JSON example:
First i think you should check for Completed value insted of CompletedMessage.
Secound with this code qrCodeString.Contains("Active").Equals(true) you are just checking if Active is contained in the string. I think you should be looking for the value of it.
In my vision the right way to do the check you need is to first deserialize the JSON like this
var qrCodeObj = JsonConvert.DeserializeObject<dynamic>(qrCodeString);
And then check for the respectives values
if (qrCodeObj["Active"] == true && qrCodeObj["Completed"] == false)
{
var matchingLink = new WebClient().DownloadString(qrCodeString);
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject (matchingLink);
var candidateId = obj.First.First["CandiateID"].ToString();
string page = $"https://*********.firebaseio.com/Candidates/.json?orderBy=\"$key\"&startAt=\"{candidateId}\"&limitToFirst=1";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// Reading the string.
Dictionary<string, Candidates> evaluationDictionary = new Dictionary<string, Candidates>();
string result = await content.ReadAsStringAsync();
evaluationDictionary = JsonConvert.DeserializeObject<Dictionary<string, Candidates>>(result);
Debug.Log(evaluationDictionary);
foreach (Candidates candidates in evaluationDictionary.Values)
{
string evaluationMessage = candidates.FirstName + " " + candidates.LastName;
candidateMessage = GetComponent<Text>();
candidateMessage.text = evaluationMessage;
}
// Getting a reference to the text component.
candidateMessage = GetComponent<Text>();
candidateMessage.text = matchingLink.ToString();
candidateMessage.text = matchingLink.Trim(new char[] {'"'});
}
}
else
{
EditorUtility.DisplayDialog("Incorrect Credentials ",
"Please scan a valid QR code. " , "OK");
}

API is mixing up data from different devices

I have an API that has devices firing data to it at the same time or within a few milliseconds. What I am finding is that the data is getting mixed up. The data is sent every five minutes (on the clock 05, 10, 15 etc.) I have an execution filter that traps the URL data coming in so I always have a real source, then it goes to the endpoint and then onto processing. For example, there will a be random five minute period missing. When I debug step by step with the missing URL from the execution filter it works fine. By that I mean I take the URL and debug, then it inserts.
In summary, I have device id 1 and device id 2.I will get missing intervals even though, I can see the data has hit the execution filter.
I am assuming that the API is not handling these as separate transactions, but somehow mixing them up together, hence the data missing and the serial numbers appearing in the wrong place, such that data from id 1 is appearing in id 2 vice versa etc.
API End Point:
public class SomeController : ApiController
{
[HttpGet]
[ExecutionFilter]
public async Task<HttpResponseMessage> Get([FromUri] FixedDataModel fdm)
{
var reply = new HttpResponseMessage();
string url = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString.ToString());
if (url.Contains("timestamp"))
{
reply = TimeSyncValidation.TimeSync;
return reply;
}
else if (!url.Contains("timestamp"))
{
reply = await Task.Run(() => DeviceClass.DeviceApiAsync(fdm, url));
}
return reply;
}
}
Processing class:
namespace API.Services
{
public class DeviceClass
{
private static string serialNumber;
private static byte chk;
private static string channelName, channelReadingNumber, channelValue, queryString, readingDate;
private static int colonPosition, chanCountFrom, equalsPosition;
private static bool checkSumCorrect;
public static HttpResponseMessage DeviceApiAsync(FixedDataModel fdm, string urlQqueryString)
{
Guid guid = Guid.NewGuid();
//ExecutionTrackerHandler.Guid = guid;
//Remove question mark
var q = urlQqueryString;
queryString = q.Substring(0);
var items = HttpUtility.ParseQueryString(queryString);
serialNumber = items["se"];
//Store raw uri for fault finding
var rawUri = new List<RawUriModel>
{
new RawUriModel
{
UniqueId = guid,
RawUri = q,
TimeStamp = DateTime.Now
}
};
//Checksum validation
chk = Convert.ToByte(fdm.chk);
checkSumCorrect = CheckSumValidator.XorCheckSum(queryString, chk);
if (!checkSumCorrect)
{
return ValidationResponseMessage.ResponseHeaders("Checksum");
}
//Create list of items that exist in URL
var urldata = new UrlDataList
{
UrlData = queryString.Split('&').ToList(),
};
var data = new List<UriDataModel>();
//Split the URL string into its parts
foreach (var item in urldata.UrlData)
{
colonPosition = item.IndexOf(":");
chanCountFrom = colonPosition + 1;
equalsPosition = item.LastIndexOf("=");
if (colonPosition == -1)
{
channelName = item.Substring(0, equalsPosition);
channelReadingNumber = "";
channelValue = item.Substring(item.LastIndexOf("=") + 1);
}
else
{
channelName = item.Substring(0, colonPosition);
channelReadingNumber = item.Substring(chanCountFrom, equalsPosition - chanCountFrom);
channelValue = item.Substring(item.LastIndexOf("=") + 1);
if (channelName == "atime" || channelName == "adate")
{
readingDate = DateValidator.CreateDate(channelValue);
}
};
bool nullFlag = false;
if (channelValue == null)
nullFlag = true;
bool missingFlag = false;
if (channelValue == "x") {
missingFlag = true;
channelValue = "0";
}
//Add data to model ready for DB insert.
data.Add(new UriDataModel
{
uid = guid,
SerialNumber = serialNumber,
ChannelName = channelName,
ChannelReadingNumber = channelReadingNumber,
ChannelValue = channelValue.Replace(",", "."),
ReadingDate = readingDate,
TimeStamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
Processed = false,
NullFlag = nullFlag,
MissingFlag = missingFlag
});
};
//Validate dates
var allDates = (from x in data where x.ChannelName.Contains("atime") || x.ChannelName.Contains("adate") select x.ChannelValue).ToList();
bool dateValidation = DateValidator.IsValid(allDates);
if (!dateValidation)
{
return ValidationResponseMessage.ResponseHeaders("Date");
};
//Validate values
var channels = Enum.GetNames(typeof(Channels)).ToList();
List<string> allChannelValues = data.Where(d => channels.Contains(d.ChannelName)).Select(d => d.ChannelValue).ToList();
bool valueValidation = ValueValidator.IsValid(allChannelValues);
if (!valueValidation)
{
return ValidationResponseMessage.ResponseHeaders("Values");
};
//Insert live data
var insertData = DataInsert<UriDataModel>.InsertData(data, "Staging.UriData");
if (!insertData)
{
return ValidationResponseMessage.ResponseHeaders("Sql");
}
var content = "\r\nSUCCESS\r\n";
var reply = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
{
Content = new StringContent(content)
};
return reply;
}
}
}
TIA
You are using global variables and static method to process your data.
Change your method to non-static.
Each DeviceClass worker must update only its own isolated data then push that off back to controller.

Null Point Exception happening in the HttpClient.GetAsync methode

I'm working on a Xamarin.Forms application in which I'm downloading some data from the server and showing them on the screen. This data is downloaded every 5-10 seconds in order to keep the application updated. My code for the data download looks like this:
public async Task<List<string>> RefreshProgressPageAsync()
{
var uri = new Uri(string.Format("http://someurladdress1"));
List<string> returnValue = new List<string>();
try
{
var response = await client.GetAsync(uri);
string allResult = string.Empty;
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
string[] valuePartsArray = result.Split(',');
string id = valuePartsArray[0].Substring(valuePartsArray[0].IndexOf(':') + 1);
string name = valuePartsArray[1].Substring(valuePartsArray[1].IndexOf(':') + 1);
string value = valuePartsArray[2].Substring(valuePartsArray[2].IndexOf(':') + 1);
returnValue.Add(string.Format("{0}|{1}|{2}", id, name, value));
}
uri = new Uri(string.Format("http://someurladdress2"));
response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
string[] valuePartsArray = result.Split(',');
string id = valuePartsArray[0].Substring(valuePartsArray[0].IndexOf(':') + 1);
string name = valuePartsArray[1].Substring(valuePartsArray[1].IndexOf(':') + 1);
string value = valuePartsArray[2].Substring(valuePartsArray[2].IndexOf(':') + 1);
returnValue.Add(string.Format("{0}|{1}|{2}", id, name, value));
}
return returnValue;
}
catch (Exception ex)
{
Debug.WriteLine(#" ERROR {0}", ex.Message);
return new List<string>();
}
}
Client is the HttpClient. There are two calls for the client because I want to download two different set of data in one RefreshProgressPageAsync call.
Now my problem with this is when second await client.GetAsync(uri) happens, I get a null point exception somewhere in the GetAsynch call, which is not caught by the try-catch block. I do have a workaround by not parsing the string and instead send it as is, but my question is what could cause this NullPointException?

How to mock a OWIN Testserver with RestSharp?

I'm using OWIN with WebAPI integration as WebApp. Future plan is to use OWIN self-hosting which is working fine but the OWIN testserver implementation is not working together with RestSharp:
Sample without RestSharp:
https://blogs.msdn.microsoft.com/webdev/2013/11/26/unit-testing-owin-applications-using-testserver/
First attempt is to use a mock class derived from RestClient class:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
var response = TestServer.HttpClient.GetAsync(request.Resource).Result;
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}
Unfortunatly I stuck with Post events, which needs html body from restResponse.
Has anybody done something similar.
BTW: I can also use OWIN unit tests with self-hosting OWIN, but this will not work on Teamcity automatic builds.
I changed the mock rest Client to work with Post/Put/Delete methods too. It is not 100% complete (missing auth, Cookies, files etc.), but in my case it is sufficient:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
HttpResponseMessage response = null;
Parameter body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
HttpContent content;
if (body != null)
{
object val = body.Value;
byte[] requestBodyBytes;
string requestBody;
if (val is byte[])
{
requestBodyBytes = (byte[]) val;
content = new ByteArrayContent(requestBodyBytes);
}
else
{
requestBody = Convert.ToString(body.Value);
content = new StringContent(requestBody);
}
}
else
content = new StringContent("");
string urladd = "";
IEnumerable<string> #params = from p in request.Parameters
where p.Type == ParameterType.GetOrPost && p.Value != null
select p.Name + "=" + p.Value;
if(!#params.IsNullOrEmpty())
urladd = "?" + String.Join("&", #params);
IEnumerable<HttpHeader> headers = from p in request.Parameters
where p.Type == ParameterType.HttpHeader
select new HttpHeader
{
Name = p.Name,
Value = Convert.ToString(p.Value)
};
foreach (HttpHeader header in headers)
{
content.Headers.Add(header.Name, header.Value);
}
content.Headers.ContentType.MediaType = "application/json";
switch (request.Method)
{
case Method.GET:
response = TestServer.HttpClient.GetAsync(request.Resource + urladd).Result;
break;
case Method.DELETE:
response = TestServer.HttpClient.DeleteAsync(request.Resource + urladd).Result;
break;
case Method.POST:
response = TestServer.HttpClient.PostAsync(request.Resource + urladd, content).Result;
break;
case Method.PUT:
response = TestServer.HttpClient.PutAsync(request.Resource + urladd, content).Result;
break;
default:
return null;
}
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}

Get request after a put or a post shows previous data instead of modified data?

The problem is that I do a GET request in the constructor(I call upon the method so every time that you enter the page the data is newly get from the database) and it gets the data from the database in a proper way. But after I modify the data and go back to page the data is still unmodified. The data changes in the database so the modify works but the GET request seems to get old data that is no longer in the database. How is this happening and how can I fix this? Thanks in advance!
public void getUserData()
{
RestClient client = new RestClient("http://localhost:8080/GigShare/webresources");
var request = new RestRequest("/user/{username}", Method.GET);
request.AddUrlSegment("username", "" + user.userName);
client.ExecuteAsync(request, response =>
{
getYourCarpools();
System.Diagnostics.Debug.WriteLine(modifyName.Text);
userget = (User) JsonConvert.DeserializeObject<User>(response.Content);
System.Diagnostics.Debug.WriteLine("GET");
System.Diagnostics.Debug.WriteLine(userget.name);
modifyName.Text = userget.Name;
modifySurname.Text = userget.surName;
modifyUsername.Text = userget.userName;
modifyTown.Text = userget.town;
modifyStreetName.Text = userget.streetName;
modifyHomenumber.Text = userget.homeNumber;
modifyProvince.Text = userget.province;
modifyEmail.Text = userget.email;
modifyCarBrand.Text = userget.car.brand;
modifyFuelType.Text = userget.car.fuelType;
modifySeats.Text = "" + userget.car.seats;
modifyavarageConsumption.Text = "" + userget.car.averageConsumption;
getCarData();
});
}
private void btnModifyCreateAccount_Click(object sender, RoutedEventArgs e)
{
User outputUser = dataFromUser();
var client = new RestClient()
{
BaseUrl = "http://localhost:8080/GigShare/webresources",
Authenticator = new HttpBasicAuthenticator("" + user.userId, user.password)
};
var request = new RestRequest("/user/id/{id}", Method.PUT);
request.AddUrlSegment("id", "" + user.userId);
request.RequestFormat = DataFormat.Json;
request.AddBody(outputUser);
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.NoContent)
{
// getUserData();
// NavigationService.Navigate(new Uri("/Views/NewlyAdded.xaml", UriKind.Relative));
System.Diagnostics.Debug.WriteLine("PUT");
}
else
{
System.Diagnostics.Debug.WriteLine("failmode");
}
});
}

Categories