get data (single value) from ksoap to andorid through webservice - ksoap

final String SOAP_ACTION = "http://tempuri.org/get_data2";
final String OPERATION_NAME = "get_data2";
final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
final String SOAP_ADDRESS = "****";
final String req_no, req_date, bolnumber, container_no, current_loc, truck_no;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsString = (SoapObject)envelope.getResponse();
Log.d("-----------------------", resultsString.getProperty("emp_name").toString());
tv.setText(resultsString.getPropertyCount());
}
catch (Exception exception)
{
exception.printStackTrace();
tv.setText(exception.toString());
}

Related

input :Specified cast is not valid

I tried to execute my application Rest api. Using a breakpoint, I found a problm in this line:
expenses.AmountTTC = Convert.ToDecimal(ttc.Text);
The error is "Specified cast is not valid".
AmountTTC has the type decimal? in the model , same for my service(i have two projects, one for the services and anthor for my mobile application).
private void Button_Clicked(object sender, EventArgs e)
{
ajoutD.Clicked += async delegate
{
try
{
LoginViews expenses = new LoginViews();
expenses.Name = nameLib.Text;
expenses.StartDate = dataDe.Date;
expenses.EndDate = dateAu.Date;
datenow.Date = DateTime.Now;
expenses.Description = description.Text;
expenses.CurrencyId = Convert.ToInt32(devises.Id);
expenses.AmountTTC = Convert.ToDecimal(ttc.Text);
remb.Text = expenses.AmountReimbursed.ToString();
expenses.Remboursable = Convert.ToBoolean(isremboursable);
expenses.Provider = marchand.Text;
HttpClient httpClient = new HttpClient();
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(expenses);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await httpClient.PostAsync(url, content);
AuthResponse responseData = JsonConvert.DeserializeObject<AuthResponse>(response?.Content?.ReadAsStringAsync()?.Result);
if (responseData.data.Success)
{
await DisplayAlert("heey", "connexion done", "ok");
}
else
{
await DisplayAlert("wake up !", responseData.data.ErrorMessage, "attention");
}
}catch(Exception eee)
{
string msg = eee.ToString();
}
};
}

How to solve this circular dependency problem?

I have two interfaces for components that each requires functionality from the other one. One that generates Oauth tokens, and another one that gets secrets from a secret provider (Azure Key Vault).
The problem is that the Token Provider needs to obtain a secret value (a password) to make its HTTP call, and the Secret Provider class needs to get a Token in order to call Azure. Chicken and Egg problem.
From the other questions I've read, one suggestion is to create a third class/interface on which the original 2 depend, but I'm not sure how that would work here.
Any help and suggestions would be appreciated. Code for all relevant classes/interfaces is shown below.
public interface ISecretProvider
{
string GetSecret(string secretName);
}
public interface ITokenProvider
{
string GetKeyVaultToken();
}
public class OktaTokenProvider : ITokenProvider
{
ISecretProvider _secretProvider;
public string GetKeyVaultToken()
{
var tokenUrl = ConfigurationManager.AppSettings["KeyVault.Token.Url"];
var clientId = ConfigurationManager.AppSettings["KeyVault.Token.ClientId"];
var clientSecret = _secretProvider.GetSecret("ClientSecret");
var scope = ConfigurationManager.AppSettings["KeyVault.Scope"];
var token = GetToken(tokenUrl, clientId, clientSecret, scope);
return token;
}
private string GetToken(string tokenUrl, string clientId, string clientSecret, string scope)
{
var clientCredentials = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"))}";
string responseFromServer = string.Empty;
bool success = false;
int retryCount = 0;
while (!success)
{
try
{
var tokenWebRequest = (HttpWebRequest)WebRequest.Create(tokenUrl);
tokenWebRequest.Method = "POST";
tokenWebRequest.Headers.Add($"Authorization:{clientCredentials}");
tokenWebRequest.Headers.Add("Cache-control:no-cache");
tokenWebRequest.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(tokenWebRequest.GetRequestStream()))
{
streamWriter.Write($"grant_type=client_credentials&scope={scope}");
streamWriter.Flush();
streamWriter.Close();
}
using (WebResponse response = tokenWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
success = true;
}
catch (Exception)
{
if (retryCount > 3)
{
throw;
}
else
{
retryCount++;
}
}
}
JToken token = JObject.Parse(responseFromServer);
var accessToken = $"Bearer {token.SelectToken("access_token").ToString()}";
return accessToken;
}
}
public class KeyVaultSecretProvider : ISecretProvider
{
ITokenProvider _tokenProvider;
public KeyVaultSecretProvider(ITokenProvider tokenProvider)
{
_tokenProvider = tokenProvider;
}
public string GetSecret(string secretName)
{
var KeyVaultUrl = ConfigurationManager.AppSettings[Constants.KEYVAULT_ENDPOINT];
var subscriptionKey = ConfigurationManager.AppSettings[Constants.KEYVAULT_SUBSCRIPTION_KEY];
string responseFromServer = "";
var requestedSecretUrl = $"{KeyVaultUrl}{secretName}";
var secretWebRequest = (HttpWebRequest)WebRequest.Create(requestedSecretUrl);
var accessToken = _tokenProvider.GetKeyVaultToken();
secretWebRequest.Method = "GET";
secretWebRequest.Headers.Add("authorization:" + accessToken);
secretWebRequest.Headers.Add("cache-control:no-cache");
secretWebRequest.Headers.Add("Ocp-Apim-Subscription-Key:" + subscriptionKey);
using (WebResponse response = secretWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
JToken secret = JObject.Parse(responseFromServer);
var secretValue = secret.SelectToken("Secret").ToString();
return secretValue;
}
}
Have a single class implement both interfaces. The two responsibilities are inter-dependent, so put them together in one class. There is nothing wrong with this.

How to add screenshot into RallyDev using RAlly API

how to upload the screenshots into rally dev using the rally rest api. I am able to log defects. I need to log screenshots
Here is an example using Rally REST Api Tookit for Java that creates a defect and then creates an attachment on the defect:
public class CreateDefectAddAttachment{
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String projectRef = "/project/12352608219";
String applicationName = "RestExample_createDefectAttachScreenshot";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
//Read User
QueryRequest userRequest = new QueryRequest("User");
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "user#company.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
try {
for (int i=0; i<1; i++) {
//Create a defect
JsonObject newDefect = new JsonObject();
newDefect.addProperty("Name", "bug1234");
newDefect.addProperty("Project", projectRef);
CreateRequest createRequest = new CreateRequest("defect", newDefect);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read defect
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading Defect %s...", ref));
String imageFilePath = "C:/";
String imageFileName = "pic.png";
String fullImageFile = imageFilePath + imageFileName;
String imageBase64String;
long attachmentSize;
// Open file
RandomAccessFile myImageFileHandle = new RandomAccessFile(fullImageFile, "r");
try {
long longLength = myImageFileHandle.length();
long maxLength = 5000000;
if (longLength >= maxLength) throw new IOException("File size >= 5 MB Upper limit for Rally.");
int fileLength = (int) longLength;
// Read file and return data
byte[] fileBytes = new byte[fileLength];
myImageFileHandle.readFully(fileBytes);
imageBase64String = Base64.encodeBase64String(fileBytes);
attachmentSize = fileLength;
// First create AttachmentContent from image string
JsonObject myAttachmentContent = new JsonObject();
myAttachmentContent.addProperty("Content", imageBase64String);
CreateRequest attachmentContentCreateRequest = new CreateRequest("AttachmentContent", myAttachmentContent);
CreateResponse attachmentContentResponse = restApi.create(attachmentContentCreateRequest);
String myAttachmentContentRef = attachmentContentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment Content created: " + myAttachmentContentRef);
//Create the Attachment
JsonObject myAttachment = new JsonObject();
myAttachment.addProperty("Artifact", ref);
myAttachment.addProperty("Content", myAttachmentContentRef);
myAttachment.addProperty("Name", "AttachmentFromREST.png");
myAttachment.addProperty("Description", "Attachment From REST");
myAttachment.addProperty("ContentType","image/png");
myAttachment.addProperty("Size", attachmentSize);
myAttachment.addProperty("User", userRef);
CreateRequest attachmentCreateRequest = new CreateRequest("Attachment", myAttachment);
CreateResponse attachmentResponse = restApi.create(attachmentCreateRequest);
String myAttachmentRef = attachmentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment created: " + myAttachmentRef);
if (attachmentResponse.wasSuccessful()) {
System.out.println("Successfully created Attachment");
} else {
String[] attachmentContentErrors;
attachmentContentErrors = attachmentResponse.getErrors();
System.out.println("Error occurred creating Attachment: ");
for (int j=0; j<attachmentContentErrors.length;j++) {
System.out.println(attachmentContentErrors[j]);
}
}
}catch (Exception e) {
System.out.println("Exception occurred while attempting to create Content and/or Attachment: ");
e.printStackTrace();
}
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating a defect: ");
for (int j=0; i<createErrors.length;j++) {
System.out.println(createErrors[j]);
}
}
}
} finally {
//Release all resources
restApi.close();
}
}
}

Stream PDF Byte array from WebAPI to browser

I'm working in C#.net in a WebAPI...
I have...
WebAPI Controller...
public class GetSMBController : ApiController
{
public HttpResponseMessage GET(int AgencyID, string UserName)
{
var Pdfs = new HttpResponseMessage();
Pdfs = Utilities.Reporting.CreateStandardMapBooklet(AgencyID,UserName);
return Pdfs;
}
}
That calls a method...
public static HttpResponseMessage CreateStandardMapBooklet(int AgencyID, string userName)
{
string baseDataPath = #"\\dvfmweb4\\arcgisserver\basedata\";
string tempDataPath = #"\\dvfmweb4\arcgisserver\tempGrowerData\";
string unitTestSession = "UnitTestSession";
int ShadeType = 1;
bool isInImagery = false;
double MaxSceneSize = 1.5;
bool ScaleBar = true;
int MapSettingID = 0;
bool OverallPage = false;
bool OverallImagery = false;
bool IsRecordKeepingSheet = false;
int RecordKeepingSheetID = 0;
int TemplateID = 1480;
RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport _Pdfs = new RCIS.Mapping.MapDomain.Reports.StandardMapBookletReport(
baseDataPath,
tempDataPath,
unitTestSession,
AgencyID,
ShadeType,
isInImagery,
MaxSceneSize,
ScaleBar,
MapSettingID,
TemplateID,
OverallPage,
OverallImagery,
false,
RecordKeepingSheetID,
userName,
true);
PDF testPDF = new PDF();
byte[] test = null;
try
{
List<RCIS.Mapping.MapDomain.Layout.CreatePdfResponse> pdf = _Pdfs.CreateReports();
foreach (var item in pdf)
{
//PDFInfo info = new PDFInfo();
//info.PdfBytes = item.PdfBytes;
testPDF.Report = item.PdfBytes;
test = item.PdfBytes;
}
}
catch(Exception e)
{
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(test)
};
response.Content = new ByteArrayContent(test);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
{
FileName = String.Format(AgencyID + userName + DateTime.Now.ToString("MMMddyyyy_HHmmss"))
};
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = new TimeSpan(0, 0, 60) // Cache for 30s so IE8 can open the PDF
};
return response;
}
Sorry for some of the commented out stuff and goofy variable names...I'm just trying to see if this is a viable thing.
the test object and HttpResponse message Content ARE populated but
I'm receiving this error when I call this from a browser...
This XML file does not appear to have any style information associated with it. The document tree is shown below.
An error has occurred.
Value cannot be null. Parameter name: content
System.ArgumentNullException
at System.Net.Http.ByteArrayContent..ctor(Byte[] content) at MappingServicesWebAPI.Utilities.Reporting.CreateStandardMapBooklet(Int32 AgencyID, String userName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Utilities\Reporting.cs:line 92 at MappingServicesWebAPI.Controllers.GetSMBController.GET(Int32 AgencyID, String UserName) in d:\FarmMaps\Web\WebAPI\MappingServicesWebAPI\MappingServicesWebAPI\Controllers\MappingController.cs:line 143 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.b__c(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.b__4() at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)

How to add test case when post a test case result

The JsonObject addProperty cannot support to add another JsonObject.
The official test shown on below:
#Test
public void shouldConstructTheCorrectUrlWithExtraParam() {
JsonObject body = new JsonObject();
CreateRequest req = new CreateRequest("Defect", body);
req.addParam("foo", "Bar");
Assert.assertEquals(req.toUrl(), "/defect/create.js?foo=Bar&fetch=true");
}
What I need is ???:
public void shouldConstructTheCorrectUrlWithExtraParam() {
JsonObject body = new JsonObject();
body.add("testcase",???)
CreateRequest req = new CreateRequest("testcaseresult", body);
req.addParam("foo", "Bar");
Assert.assertEquals(req.toUrl(), "/defect/create.js?foo=Bar&fetch=true");
}
I did a mistake for adding other JsonObject, it's a ref instead a instance.
Works well code:
public void createTestCaseResult(JsonObject testCaseJsonObject) throws IOException, URISyntaxException {
log.println("createTestCaseResult...");
String testCaseRef = testCaseJsonObject.get("_ref").getAsString();
QueryRequest userRequest = new QueryRequest("user");
userRequest.setFetch(new Fetch("UserName", "Subscription", "DisplayName"));
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "lu.han#technicolor.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
close();
getRestApi();
Date now = new Date();
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
SimpleDateFormat format = new SimpleDateFormat(pattern);
JsonObject newResult = new JsonObject();
newResult.addProperty("Verdict", "Pass");
newResult.addProperty("Build", "2014.01.08.1234567");
newResult.addProperty("Tester", userRef);
newResult.addProperty("Date", format.format(now));
newResult.addProperty("CreationDate", format.format(now));
newResult.addProperty("TestCase", testCaseRef);
newResult.addProperty("Workspace", workspaceRef);
CreateRequest createRequest = new CreateRequest("testcaseresult", newResult);
CreateResponse createResponse = restApi.create(createRequest);
log.println("createTestCaseResult DONEļ¼š");
log.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
}