This is function from my partner:
public ActionResult<string> ReadSmb(string server, string share, string path, string username = "", string password = "")
{
var result = new StringBuilder();
NTStatus status;
SMB1Client client = new SMB1Client(); // SMB2Client can be used as well
bool isConnected = client.Connect(server, SMBTransportType.DirectTCPTransport);
if (isConnected)
{
status = client.Login(String.Empty, username, password);
if (status == NTStatus.STATUS_SUCCESS)
{
List<string> shares = client.ListShares(out status);
ISMBFileStore fileStore = client.TreeConnect(share, out status);
object fileHandle;
FileStatus fileStatus;
if (fileStore is SMB1FileStore)
{ path = #"\\" + path; }
status = fileStore.CreateFile(out fileHandle, out fileStatus,
path,
AccessMask.GENERIC_READ | AccessMask.SYNCHRONIZE,
SMBLibrary.FileAttributes.Normal, ShareAccess.Read,
CreateDisposition.FILE_OPEN,
CreateOptions.FILE_NON_DIRECTORY_FILE | CreateOptions.FILE_SYNCHRONOUS_IO_ALERT,
null);
if (status == NTStatus.STATUS_SUCCESS)
{
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
byte[] data;
long bytesRead = 0;
while (true)
{
status = fileStore.ReadFile(out data, fileHandle, bytesRead, (int)client.MaxReadSize);
if (status != NTStatus.STATUS_SUCCESS && status != NTStatus.STATUS_END_OF_FILE)
{
throw new Exception("Failed to read from file");
}
if (status == NTStatus.STATUS_END_OF_FILE || data.Length == 0)
{
break;
}
bytesRead += data.Length;
stream.Write(data, 0, data.Length);
}
stream.Seek(0, SeekOrigin.Begin);
using (var streamreader = new StreamReader(stream, Encoding.GetEncoding(932)))
{
result.Append(streamreader.ReadToEnd());
streamreader.Close();
}
}
}
else
{
result.AppendLine($"file open : {status.ToString()}");
}
status = fileStore.CloseFile(fileHandle);
status = fileStore.Disconnect();
client.Logoff();
}
else
{
result.AppendLine($"logon : {status.ToString()}");
}
client.Disconnect();
}
else
{
result.AppendLine($"not connected : {server}");
}
return Json(result.ToString());
}
And The results he tried displayed on the screen as follows:
I have the following code:
ActionResult<string> test = TestFunction();
List<string> list = test;
for (int i = 0; i < list.Count; i++ )
{
//do something with list
}
My "ActionResult test" is return Json(result.ToString());
And now, i want to convert from ActionResult to List to loop them and do something with them.
How can I convert or do any thing to loop them?
Thanks for read my post :)
Genuinely? You wouldn't do it this way
It looks like the method from your partner is either supposed to be in a controller directly,
[HttpGet]
public ActionResult<string> ReadSmbstring server, string share, string path, string username = "", string password = ""){
...
}
or the controller method is some hollow shell/passthrough like,
[HttpGet]
public ActionResult<string> Get(...){
return ReadSmb(...);
}
It's going to be harder to work with ReadSmb the way it is, than changing it so it just returns a string, and then passthrough calling it in a controller:
public ActionResult<string> ReadSmb(string server, string share, string path, string username = "", string password = "")
{
...
return result.ToString();
}
[HttpGet]
public ActionResult<string> Get(...){
return Json(ReadSmb(...));
}
Also, I do want to point out that it's going to be hard to work with all round, because it basically prepares what looks like a block of formatted text. There's barely any point in "JSONifying" that, because all it'll do is wrap it in " and turn any " inside it into \"
Json() is intended to work with objects like:
var r = new Person {
Name = "John",
Age = 22,
Address = new Address {
Street = "Infinite Loop",
City = "Cupertino"
}
}
And it'll churn out
{
"name": "John",
"age": 22,
"address": {
"street": "Infinite Loop",
"city": "Cupertino"
}
}
If you made ReadSmb return you some sensible object then it'll be a lot easier to work with, and Json()ing the result will do something reasonable which makes it a lot easier to work with at the other end of the pipe
If ReadSmb returned you a class like:
public class SmbFile{
public string FileName {get; set;}
public string Status {get; set;}
public string B64Content { get => Convert.ToBase64String(_fileContent); }
[JsonIgnore]
public byte[] FileContent { get; set;} //note, properties should not return arrays - doing for convenience of demonstrating a point
}
Then you could inspect the Status, know if there was some bytes data, read it, parse it, whatever youre planning on doing.. and it would Json() fairly sensibly too
Related
I’m getting an error in VS trying to check the Return Code of a method that builds and post data via an API.
The line that is generating the error is:
if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)
The error is:
Operator '==' cannot be applied to operands of type 'Task<string'>' and 'string'
My goal is to pass those parameters (data1, data5, etc) to the BuildApi() method and then post that data via an API call.
When the data is successfully posted, I should get a Return Code of 200 or a Return Code of 400 if an error occurred (according to the API developer).
The BuildApi() method should return either a 200 or 400 back to the condition statement.
Is the BuildApi() method formatted correctly to return the Return Code and if so, what’s wrong with that “if” statement?
Thanks in advance for your help!
Full Code:
static class MyGlobals
{
public static XmlDocument XmlAccounts = new XmlDocument();
public static XmlNode XmlRoot;
public static string data1 { get; set; }
public static string data2 { get; set; }
public static string data3 { get; set; }
public static string data4 { get; set; }
public static string data5 { get; set; }
public static string ReturnCode { get; set; }
}
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
SqlConnection ObjConn = new SqlConnection();
string ConnectMe = #"
Data Source =SERVER;
Database =DATABASE1;
User ID =USER;
Pwd =PASS;
Connection Timeout =700
";
// Open Connection
ObjConn = new SqlConnection(ConnectMe);
ObjConn.Open();
// Call methods based on the required tool
SR_Provisioning(ObjConn);
}
static public void SR_Provisioning(SqlConnection ObjConn)
{
Get = #"
SELECT
data1,
data2,
data3,
data4,
data5
FROM
table
";
ObjAdp = new SqlDataAdapter(Get, ObjConn);
ObjAdp.Fill(OutputTable);
foreach (DataRow OutputRow in OutputTable.Rows)
{
//Initalize FQAN
string FQAN = "";
// Convert query output to variables
MyGlobals.data1 = OutputRow[0].ToString();
MyGlobals.data2 = OutputRow[1].ToString();
MyGlobals.data3 = OutputRow[2].ToString();
MyGlobals.data4 = OutputRow[3].ToString();
MyGlobals.data5 = OutputRow[4].ToString();
// Instantiate new objects
strFunctions MyStr = new strFunctions();
wshWin32API win32api = new wshWin32API();
// Convert server to FQDN for accessibility ease
string FQDN = getFQDN(MyGlobals.data1, ObjConn);
// Perform action based on Tranaction_Type
switch (MyGlobals.data5)
{
case "Add":
if (MyGlobals.data2 == "LOCAL")
{
// Create local ID first
try
{
FQAN = MyGlobals.data1 + "\\" + MyGlobals.data3;
// Check the return code to determine how to log the results
if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)
{
switch (MyGlobals.ReturnCode)
/*
Return Codes
200 (Created)
400(Expectation Failed)
*/
{
case "200":
// Do something
AllIsGood();
break;
case "400":
// Do something else
AllIsBad();
break;
}
}
}
catch (Exception err)
{
// Handle error and update transaction record
Update_Row();
}
}
}
static async Task<string> BuildApi(string data5, string data1, string FQAN, string data4)
{
try
{
UriBuilder baseUri = new UriBuilder("https://pwmfunction001.azurewebsites.net/api/VMGroupMemberModify01?code=T753ljF4jwXZXzmotCnnrBdV7Mrbqvcd3ibazRb92ZoBfJADuCpq5w==-Headers#{Metadata=true}-Body#{");
// Create the query string
string queryToAppend = "DATA5=" + data5 + ";DATA1=" + data1 + ";FQAN=" + FQAN + ";data4=" + data4 + "}";
if (baseUri.Query != null && baseUri.Query.Length > 1)
{
baseUri.Query = baseUri.Query.Substring(1) + ";" + queryToAppend;
}
else
{
// Check this
baseUri.Query = queryToAppend;
}
string httpResponseBody = "";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(client.ToString());
HttpResponseMessage response = await client.PostAsync(baseUri.ToString(), content);
if (response.IsSuccessStatusCode)
{
httpResponseBody = "200";
return httpResponseBody;
}
else
{
httpResponseBody = "400";
return httpResponseBody;
}
}
catch(HttpRequestException err)
{
throw err;
}
}
}
}
Your BuildApi function is async so you need to await it in your code:
if (await BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)
UPDATE:
If you can't run it async then you need the result:
if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4).Result == MyGlobals.ReturnCode)
However, I would try in the first instance to make your calling method async
I have the following working controller method, which returns the JSON in a simple text format.
[HttpPost]
public IActionResult DecodeBarcode(string productCodeScheme, string productCode, string serialNumber, string batch, string expirationDate, int commandStatusCode) {
string TextAreaResult = string.Empty;
try {
TextAreaResult = string.Format("{0} {1} {2}", request.getHttpInformation(), request.getHttpWarning(), request.getHttpResponseCode());
} catch (Exception exc) {
TextAreaResult = "Exception: " + exc.Message;
}
return Json(TextAreaResult);
}
The output after the above method is run looks something like
"The pack is active No warning 200"
whereas
request.getHttpInformation() is The pack is active
request.getHttpWarning() is No warning
request.getHttpResponseCode() is 200
Now, I am trying to split the response into 3 different key-value pairs so that my response will look like
{
httpInformation: "The pack is active",
httpWarning: "No Warning",
httpResponseCode: "200"
}
How do I pass the additional params in return Json(TextAreaResult) call?
If I do like the following it won't work
[HttpPost]
public IActionResult DecodeBarcode(string productCodeScheme, string productCode, string serialNumber, string batch, string expirationDate, int commandStatusCode) {
string TextAreaResult = string.Empty;
string TextAreaResultHttpInformation = string.Empty;
string TextAreaResultHttpWarning = string.Empty;
string TextAreaResultHttpResponseCode = string.Empty;
try {
TextAreaResultHttpInformation = string.Format("{0}}", request.getHttpInformation());
TextAreaResultHttpWarning = string.Format("{1}}", request.getHttpWarning());
TextAreaResultHttpResponseCode = string.Format("{2}}", request.getHttpResponseCode());
} catch (Exception exc) {
TextAreaResult = "Exception: " + exc.Message;
}
return Json(TextAreaResultHttpInformation, TextAreaResultHttpInformation, TextAreaResultHttpResponseCode);
}
How do I construct the key-value pairs and return as JSON? Perhaps, Json method is not the right choice over here, but being new to C#, I am not aware of any other c# inbuilt methods for constructing JSON
Assuming you actually want to consume the response as JSON, you could achieve this by doing
return Json(new
{
HttpInformation = TextAreaResultHttpInformation,
HttpWarning = TextAreaResultHttpWarning,
StatusCode = TextAreaResultHttpResponseCode
});
You can make wrapper class for these properties and return it.
public class BarcodeResultDto
{
[JsonProperty("httpInformation")]
public string HttpInformation { get; set; }
[JsonProperty("httpWarning")]
public string HttpWarning { get; set; }
[JsonProperty("httpResponseCode")]
public int GetHttpResponseCode { get; set; }
}
public IActionResult DecodeBarcode(string productCodeScheme, string productCode, string serialNumber,
string batch, string expirationDate, int commandStatusCode)
{
var barcodeResult = new BarcodeResultDto
{
GetHttpResponseCode = 200,
HttpInformation = "The pack is active",
HttpWarning = "No Warning"
};
// your code here
return Ok(barcodeResult);
}
Or you can change retuned value from IActionResult to JsonResult
If you want a different approach then you can use JsonSerializer in the following way :
// Creating BlogSites object
BlogSites bsObj = new BlogSites()
{
Name = "test-name",
Description = "test-description"
};
// Serializing object to json data
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonData = js.Serialize(bsObj); // {"Name":"test-name","Description":"test-description"}
You will just need to create a class and store value in its objects then serialize it. If you have a list then you can use List of that class and then serialize.
I am working on a webservice calling module,I have a document for calling webservice which is built in C#,i have called webservice in JSON only and have no idea how to make a request to such webservices,Can anybuddy help me how to make a request and getting respose fron such kind of webservice my webservice details are as below,
webservice base url : http://www.fansplay.com/wsfpbtest/FBS.svc
API name : GetContestants
Request format:
{“ APIUserName”: “admin” , “Password”: “*****”}
Response:
{
"Contestants": [
{
"Age": 19,
"Bio": "",
"City": "Agra",
"ContestantID": 11,
"CurrentWeekPoints": 0,
"FirstName": "Merlin",
"ImageURL": "http://localhost:41800/FansPlayBachelor/Player/11.jpg",
"LastName": "M",
"Occupation": "Student",
"State": "Delhi",
"Status": "A",
"TotalPoints": 0
},
{
"Age": 25,
"Bio": "",
"City": "chennai",
"ContestantID": 12,
"CurrentWeekPoints": 0,
"FirstName": "James",
"ImageURL": "http://localhost:41800/FansPlayBachelor/Player/12.jpg",
"LastName": "S",
"Occupation": "Marketing",
"State": "tamilnadu",
"Status": "A",
"TotalPoints": 0
}
],
"ResponseCode": true,
"ResponseMessage": "Success"
}
I have tried as below:
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(StartActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("Loading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost("http://www.fansplay.com/wsfpbtestV3/FBS.svc/GetContestants");
String json = "";
try{
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("APIUserName", "Rjfk#vDV43F");
jsonObject.accumulate("Password", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
String req =URLEncoder.encode(json, "utf-8");
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(req);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";}
catch(Exception e){
e.printStackTrace();
}
return null;
}
I have no idea which kind of webservice this is,So can anybody please help me as i stuck since 4 days in this.
This is a Web service which returns XML or JSON.
For XML:
You can use SoapUI to test and inspect the Web service.
You can use libraries like ksoap2-android or IceSoap to send SOAP Messages to the Web service but we will use java.net.HttpURLConnection.
For JSON:
You can use Postman to test and inspect the Web service.
The steps required to call the Web Service:
Open your AndroidManifest.xml and add permission of internet <uses-permission android:name="android.permission.INTERNET"></uses-permission>
Write code which calls the GetContestants operation on the Web service.
Write code to parse data received from the GetContestants operation.
Write code to use an AsyncTask which calls and encapsulates the above methods so that this doesn't all take place on the main UI thread.
For XML, sample code (step 2) which calls the GetContestants SOAP based operation on the Web service:
private String getContestants(String username, String password) throws Exception {
URL obj = new URL("http://www.fansplay.com/wsfpbtest/FBS.svc/SOAP");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "text/xml; charset=utf-8");
con.setRequestProperty("SOAPAction", "http://tempuri.org/IFBS/GetContestants");
String reqXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\" xmlns:fbs=\"http://schemas.datacontract.org/2004/07/FBService\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <tem:GetContestants>\n" +
" <tem:objContestant>\n" +
" <fbs:APIUserName>" + username + "</fbs:APIUserName>\n" +
" <fbs:Password>" + password +"</fbs:Password>\n" +
" </tem:objContestant>\n" +
" </tem:GetContestants>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(reqXML);
wr.flush();
wr.close();
// Read response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
Call the above method as follows: String xml = getContestants("Rjfk#vDV43F", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");
For JSON, sample code (step 2) which calls the GetContestants method on the Web service:
private String getContestants(String username, String password) throws Exception {
URL obj = new URL("http://www.fansplay.com/wsfpbtestV3/FBS.svc/GetContestants");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "text/json");
String jsonBody = String.format("{\"APIUserName\": \"%s\" , \"Password\": \"%s\"}", username, password);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(jsonBody);
wr.flush();
wr.close();
// Read response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
Call the above method as follows: String json = getContestants("Rjfk#vDV43F", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");
For XML, sample code (step 3) which parses and extracts the Contestant data:
private void parseContestants(String xml) throws ParserConfigurationException, IOException, SAXException {
// Build a Document from the XML
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xml));
Document doc = db.parse(inStream);
NodeList nl = doc.getElementsByTagName("a:Contestant");
for(int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Node contestant = (Element) node;
// Extract the contestant data
NodeList contestantProperties = contestant.getChildNodes();
if (contestantProperties.item(0).getFirstChild() != null) {
String age = contestantProperties.item(0).getFirstChild().getNodeValue();
}
if (contestantProperties.item(1).getFirstChild() != null) {
String bio = contestantProperties.item(1).getFirstChild().getNodeValue();
}
if (contestantProperties.item(2).getFirstChild() != null) {
String city = contestantProperties.item(2).getFirstChild().getNodeValue();
}
//ToDO: Extract the other properties of Contestant following pattern above
}
}
}
Call the above method as follows: parseContestants(xml);
For JSON, sample code (step 3) which parses and extracts the Contestant data:
We will use GSON which is a Java library that can be used to convert a JSON string to an equivalent Java object.
Add GSON to your project by adding the following line to your build.gradle file: compile 'com.google.code.gson:gson:2.4'
Add the following Contestant class to your project:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Contestant {
#SerializedName("Age")
#Expose
private Integer Age;
#SerializedName("Bio")
#Expose
private String Bio;
#SerializedName("City")
#Expose
private String City;
#SerializedName("ContestantID")
#Expose
private Integer ContestantID;
#SerializedName("CurrentWeekPoints")
#Expose
private Integer CurrentWeekPoints;
#SerializedName("FirstName")
#Expose
private String FirstName;
#SerializedName("ImageURL")
#Expose
private String ImageURL;
#SerializedName("LastName")
#Expose
private String LastName;
#SerializedName("Occupation")
#Expose
private String Occupation;
#SerializedName("State")
#Expose
private String State;
#SerializedName("Status")
#Expose
private String Status;
#SerializedName("TotalPoints")
#Expose
private Integer TotalPoints;
public Integer getAge() {
return Age;
}
public void setAge(Integer Age) {
this.Age = Age;
}
public String getBio() {
return Bio;
}
public void setBio(String Bio) {
this.Bio = Bio;
}
public String getCity() {
return City;
}
public void setCity(String City) {
this.City = City;
}
public Integer getContestantID() {
return ContestantID;
}
public void setContestantID(Integer ContestantID) {
this.ContestantID = ContestantID;
}
public Integer getCurrentWeekPoints() {
return CurrentWeekPoints;
}
public void setCurrentWeekPoints(Integer CurrentWeekPoints) {
this.CurrentWeekPoints = CurrentWeekPoints;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public String getImageURL() {
return ImageURL;
}
public void setImageURL(String ImageURL) {
this.ImageURL = ImageURL;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public String getOccupation() {
return Occupation;
}
public void setOccupation(String Occupation) {
this.Occupation = Occupation;
}
public String getState() {
return State;
}
public void setState(String State) {
this.State = State;
}
public String getStatus() {
return Status;
}
public void setStatus(String Status) {
this.Status = Status;
}
public Integer getTotalPoints() {
return TotalPoints;
}
public void setTotalPoints(Integer TotalPoints) {
this.TotalPoints = TotalPoints;
}
}
Add the following Contestants class to your project:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Contestants {
#SerializedName("Contestants")
#Expose
private List<Contestant> Contestants = new ArrayList<Contestant>();
#SerializedName("ResponseCode")
#Expose
private Boolean ResponseCode;
#SerializedName("ResponseMessage")
#Expose
private String ResponseMessage;
public List<Contestant> getContestants() {
return Contestants;
}
public void setContestants(List<Contestant> Contestants) {
this.Contestants = Contestants;
}
public Boolean getResponseCode() {
return ResponseCode;
}
public void setResponseCode(Boolean ResponseCode) {
this.ResponseCode = ResponseCode;
}
public String getResponseMessage() {
return ResponseMessage;
}
public void setResponseMessage(String ResponseMessage) {
this.ResponseMessage = ResponseMessage;
}
}
The above classes were generated by jsonschema2pojo
To parse the JSON into their equivalent Java objects:
private Contestants parseContestants(String json) {
return new Gson().fromJson(json, Contestants.class);
}
Sample code for AsyncTask (step 4):
private class GetContestantsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
String xml = getContestants("Rjfk#vDV43F", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");
parseContestants(xml);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
Call the AsyncTask as follows:
GetContestantsAsync getContestantsAsync = new GetContestantsAsync();
getContestantsAsync.execute();
Iam using CefSharp's SchemeHandler in order to grab resources from my C# project like .css, .js or .png files using a custom url for example custom://cefsharp/assets/css/style.css
I've 2 custom classes in order to archive this.
First class, MyCustomSchemeHandlerFactory will be the one that handles the custom Scheme and it looks like this, where "custom" will be the custom scheme:
internal class MyCustomSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "custom";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new MyCustomSchemeHandler();
}
}
The next class I've implemented is MyCustomSchemeHandler which will receive the call and output a response and it looks like this:
internal class MyCustomSchemeHandler : IResourceHandler
{
private static readonly IDictionary<string, string> ResourceDictionary;
private string mimeType;
private MemoryStream stream;
static MyCustomSchemeHandler()
{
ResourceDictionary = new Dictionary<string, string>
{
{ "/home.html", Properties.Resources.index},
{ "/assets/css/style.css", Properties.Resources.style}
};
}
public Stream Stream { get; set; }
public int StatusCode { get; set; }
public string StatusText { get; set; }
public string MimeType { get; set; }
public NameValueCollection Headers { get; private set; }
public Stream GetResponse(IResponse response, out long responseLength, out string redirectUrl)
{
redirectUrl = null;
responseLength = -1;
response.MimeType = MimeType;
response.StatusCode = StatusCode;
response.StatusText = StatusText;
response.ResponseHeaders = Headers;
var memoryStream = Stream as MemoryStream;
if (memoryStream != null)
{
responseLength = memoryStream.Length;
}
return Stream;
}
public bool ProcessRequestAsync(IRequest request, ICallback callback)
{
// The 'host' portion is entirely ignored by this scheme handler.
var uri = new Uri(request.Url);
var fileName = uri.AbsolutePath;
string resource;
if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
{
var resourceHandler = ResourceHandler.FromString(resource);
stream = (MemoryStream)resourceHandler.Stream;
var fileExtension = Path.GetExtension(fileName);
mimeType = ResourceHandler.GetMimeType(fileExtension);
callback.Continue();
return true;
}
else
{
callback.Dispose();
}
return false;
}
void GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl)
{
responseLength = stream == null ? 0 : stream.Length;
redirectUrl = null;
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusText = "OK";
response.MimeType = mimeType;
}
bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback)
{
//Dispose the callback as it's an unmanaged resource, we don't need it in this case
callback.Dispose();
if (stream == null)
{
bytesRead = 0;
return false;
}
//Data out represents an underlying buffer (typically 32kb in size).
var buffer = new byte[dataOut.Length];
bytesRead = stream.Read(buffer, 0, buffer.Length);
dataOut.Write(buffer, 0, buffer.Length);
return bytesRead > 0;
}
bool CanGetCookie(Cookie cookie)
{
return true;
}
bool CanSetCookie(Cookie cookie)
{
return true;
}
void Cancel()
{
}
}
Inside this class I've defined a custom resource dictionary which will dictate what file from the resources will be used, so as I stated in the first example, custom://cefsharp/assets/css/style.css should load the resource Properties.Resources.style, the problem is that nothing gets loaded once I enter to the specific url, I've tried to output the mimeType and It works but somehow the file itself won't output correctly. Is there something wrong with my implementation?
Additionaly I've tried to output the raw file in the form of:
if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
{
MessageBox.Show(resource);
}
And it outputs the correct file without any problems.
To load the custom Scheme I use the following code before initializing CefSharp:
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = MyCustomSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new MyCustomSchemeHandlerFactory()
});
The above classes were based on the following links:
MyCustomSchemeHandlerFactory: FlashResourceHandlerFactory.cs
MyCustomSchemeHandler: CefSharpSchemeHandler.cs and ResourceHandler.cs
Since Cefsharp changed a bit in last few months here is an updated and easier way of handling 'file' protocol. I wrote blog post on this matter.
What you want to add is your scheme handler and its factory:
using System;
using System.IO;
using CefSharp;
namespace MyProject.CustomProtocol
{
public class CustomProtocolSchemeHandler : ResourceHandler
{
// Specifies where you bundled app resides.
// Basically path to your index.html
private string frontendFolderPath;
public CustomProtocolSchemeHandler()
{
frontendFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "./bundle/");
}
// Process request and craft response.
public override bool ProcessRequestAsync(IRequest request, ICallback callback)
{
var uri = new Uri(request.Url);
var fileName = uri.AbsolutePath;
var requestedFilePath = frontendFolderPath + fileName;
if (File.Exists(requestedFilePath))
{
byte[] bytes = File.ReadAllBytes(requestedFilePath);
Stream = new MemoryStream(bytes);
var fileExtension = Path.GetExtension(fileName);
MimeType = GetMimeType(fileExtension);
callback.Continue();
return true;
}
callback.Dispose();
return false;
}
}
public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "customFileProtocol";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new CustomProtocolSchemeHandler();
}
}
}
And then register it before calling Cef.Initialize:
var settings = new CefSettings
{
BrowserSubprocessPath = GetCefExecutablePath()
};
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CustomProtocolSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomProtocolSchemeHandlerFactory()
});
If you simply need to return a string, then you can use ResourceHandler.FromString(html, mimeType). For this you just need to implement the ISchemeHandlerFactory.
https://github.com/cefsharp/CefSharp/blob/cefsharp/47/CefSharp/ResourceHandler.cs#L98
Example reading from a file https://github.com/cefsharp/CefSharp/blob/cefsharp/47/CefSharp.Example/CefSharpSchemeHandlerFactory.cs#L17 which can be translated to reading from a string quite simply.
i have this the code and i have this problem
i am trying to save a new user to my web site : the query is succeded but without insertion
ie the table "User" and the table "UserAcl" still without any modification and it is clear that the query is executed
File User.cs:
File Compte.cs
public bool SaveUser(string identification, string acc, string mot, string notify, string nom, string phone, string mail) {
try
{
if (identification == null || acc == null || nom == null || mail == null || mot == null) return false;
ITransaction transaction = User.OpenSession().BeginTransaction();
User u = new User() { Account = acc, Identification = identification, ContactEmail = mail, ContactName = nom, ContactPhone = phone, NotifyEmail = notify, Password = mot };
User.OpenSession().SaveOrUpdate(u);
transaction.Commit();
ITransaction transaction2 = User.OpenSession().BeginTransaction();
Useracl ua = new Useracl { Account = acc, UserID = identification, AccessLevel = 1, AclID = (Useracl.GetUseracl().Count + 1).ToString() };
Useracl.OpenSession().SaveOrUpdate(ua);
transaction2.Commit();
return true;
}
catch { return false; }
}
File Administration.cs
public ActionResult Index()
{
ViewBag.Title = c.GetUserID().Count.ToString();
return View();
}
public ActionResult BeforeRegister()
{
return View();
}
public ActionResult AfterRegister(string Pseudo, string Phone, string Email, string Password, string Notify)
{
bool a = c.SaveUser((c.GetPassword().Count + 1).ToString(), (c.GetPassword().Count + 1).ToString(), Password, Notify, Pseudo, Phone, Email);
if (a)
{
return RedirectToAction("Index", "Administration");
}
else
return RedirectToAction("BeforeRegister", "Administration");
}
First, you could use if (!String.IsNullOrEmpty(myString)) rather than if (myString==null).
Also, you may want to use your sessions within a using block.
bool ret= new bool();
if ((!String.IsNullOrEmpty(foo1)) && (!String.IsNullOrEmpty(foo2)))
{
//ConnectionDB is a public class, with a static method ISessionFactory SessionFactory(), and the method OpenSession() returns an ISession
using (NHibernate.ISession nhSession = ConnectionDB.SessionFactory.OpenSession())
{
try
{
User u = new User();
//set your User
nhSession.Transaction.Begin();
nhSession.Save(u);
nhSession.Transaction.Commit();
nhSession.Close();
ret = true;
}
catch (Exception ex)
{
ret = false;
}
}
return ret;
Now, about the query not inserting, it could be a mapping problem, or maybe you're supressing the exception elsewhere (like your static method User.OpenSession().SaveOrUpdate(u))