Call WebService (asmx) from winfor with https, not working - c#

We are converting our old webservices (asmx) to use https, trying to get it working locally.
I have a test app I wrote in winforms jsut to call the service.
Trying to modify it to call via https, following this pattern
https://www.codeproject.com/Questions/751059/Call-https-Webservice-in-Console-Application
(Not sure I trust this pattern 100%, but it's a place to start, looks like it's trying to ignore all errors)
private void button8_Click(object sender, EventArgs e)
{
System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
}
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{
AdStudent.ADStudent ws = new AdStudent.ADStudent();
ws.Url = "https://localhost/JCDCADStudent/ADStudent.asmx";
try
{
string str = ws.GetGuidString("Brown.Eric");
MessageBox.Show("secure guid is " + str + ".");
}
catch (Exception ex)
{
string cleanMsg = GetCleanMsg(ex.Message);
MessageBox.Show("\n\n " + cleanMsg + "\n\n\n\n\nProgrammer Msg:\n\n" + ex.Message, "Error");
}
}
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
private string GetCleanMsg(string message)
{
string startTag = "<ClientMsg>";
string endTag = "</ClientMsg>";
Int32 start = message.IndexOf(startTag) + startTag.Length;
Int32 end = message.IndexOf(endTag);
try
{
return message.Substring(start, end - start);
}
catch (Exception ex)
{
return "UNABLE TO PARSE MESSAGE : \n " + message;
}
}
}
}
I get the exception
{"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."}
inner exception
The remote certificate is invalid according to the validation procedure.
When I try and just run the HTTPS in the browser, it complains that like the title or subject field is not formatted correctly. but If I tell it to ignore that it opens the web service, I'm guessing that is the problem,
How do I fix it?
How do I get a better error like the one the browser gives me, to report in my app?
The cert was provided by our IT team, I'm not sure I can get it changed, it's a long-standing cert used for Dev.
Maybe I can get it regenerated correctly (it's applied to our machines via network policy)

Related

How to fix "request error" from google cloud storage?

I used google.cloud.storage for .mp3 files. I tried it before and it worked.
now I writed another new function that uses the existing storage function.
everything was suppose to work but I get this weird error:
"Google.Apis.Requests.RequestError
text-to-speach#XXXXXXXXXXX.iam.gserviceaccount.com does not have storage.objects.create access to objectsound/voiceAnimals20.mp3. [403]"
I dont know what to begin with. can anybody help me?
the Ok storage function is here:
public static string VoiceStorage(int catId, string URL,
Dictionary<string, int> voicesCounter)
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
#"C:\wordproject-XXXXXXXXXX.json");
// upload the image storage
//----------------
string voiceName;
voiceName = "voice" + BLLcategory.GetCategoryById(catId).CategoryName
+ voicesCounter[BLLcategory.GetCategoryById(catId).CategoryName]++ +
".mp3";
string bucketName = "XXXXXXXX";
var storage = StorageClient.Create();
using (var f = File.OpenRead(URL))
{
try
{
var res = storage.UploadObject(bucketName, voiceName, null,
f);
URL = "https://storage.cloud.google.com/" + bucketName + "/" +
voiceName;
}
catch (Exception e)
{
throw e;
}
}
return URL;
}
the new not working function is:
private void button12_Click(object sender, EventArgs e)
{
foreach (COMimageObject obj in BLLobject.GetObjects())
{
if(obj.VoiceURL==null)
{
try
{
string url=BLLtextToSpeach.TextToSpeach(obj.Name);
url=BLLtextToSpeach.VoiceStorage(
BLLimage.GetImageById(obj.ImageID).CategoryID,
url, voicesCounter);
BLLobject.UpdateVoiceURL(obj.ObjectId, url);
}
catch (Exception)
{
throw;
}
}
}
}
the catch happening after the line with url=BLLtextToSpeach.VoiceStorage
tnx!!
What the error mean is that the service account of the text-to-speach api doesn't have create access on the objectsound bucket. Go to the bucket permissions and add the text-to-speach service account with storage creator rights.
When you get this error:
[403] Errors [ Message[.................iam.gserviceaccount.com does
not have storage.buckets.list access to the Google Cloud project.
you need to have permissions in your service account from the IAM to read the buckets
storage.buckets.get Read bucket metadata, excluding IAM policies.
storage.buckets.list List buckets in a project. Also read bucket
metadata,
https://cloud.google.com/storage/docs/access-control/iam-permissions
The "Firebase Admin" will enable all necessary permissions.

Web Service Returns Object reference not set to an instance of an object

I'm using web service exposed from govt. website to submit my client transaction and get the response back.i'm passing correct parameters to webservice in the correct formats the same webservice with the exact same parameter is working when I'm using testing tool SOAPUI but when I'm running through my c# code getting the Error.Below is the signature of web service function :
int WebSvcFunction(string login,string pwd,string xmlClaimInput,out string xmlDRGDetails,out byte[] auditFileContent,out byte[] reportFileContent,out string errorMessage);
Can anyone Correct me what's wrong I'm doing?
Below is my code onbutton click :
private void btnTestService_Click(object sender, EventArgs e)
{
try
{
string xmlDRGDetails = (string)null;
byte[] auditFileContent = (byte[])null;
byte[] reportFileContent = (byte[])null;
string errorMessage = (string)null;
int m = objWebservicesSoapClient.WebSvcFunction(gstrLoginId, gstrpwd, rTxtDrgTab.Text.ToString(), out xmlDRGDetails,
out auditFileContent , out reportFileContent, out errorMessage);
MessageBox.Show(string.Format("Success {0}", m));
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Source: {0}\nDescription:{1}\nTarget Site:{2}\nCall Stack:{3}", (object)ex.Source, (object)ex.Message, (object)ex.TargetSite, (object)ex.StackTrace), "Convert DRG", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Returning a File from a ASP.NET web api to android

I have a ASP.Net web api which is intended to send a new file over the internet encoded as Base64. To do so, I have a public exposed REST service:
string imei = ControllerContext.Request.Headers.GetValues("IMEI").FirstOrDefault();
byte[] FileAsBytes = null;
String base64 = null;
var svcs = new CrudService.CrudServiceClient();
if (svcs.IsDeviceAccepted(imei))
{
FileAsBytes = svcs.DownloadSoftwareVersion();
}
if(FileAsBytes != null)
{
base64 = Convert.ToBase64String(FileAsBytes);
}
return base64;
and a Private service, CRUD service, which communicates directly with the database and the core layers.
After some debugging I found out that this service returns the correct lenght, something like 4194304 bytes, which seems to correspond to the size of file. However on the client side, I am contacting this service inside a AsyncTask:
#Override
protected String doInBackground(String... params) {
Log.i("UpdateManager: ", "Inside doInBackground");
try {
String imei = params[0];
String urlString = "http://10.118.18.50/Mobile.RESTPublicService/api/SoftwareUpdate";
HttpPost post = new HttpPost(urlString);
post.addHeader("IMEI", imei);
response = httpClient.execute(post);
Log.w("Update-Response: ",
Integer.toString(response.getStatusLine().getStatusCode())
+ " " + response.getStatusLine());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
is = response.getEntity().getContent();
IOUtils.copy(is, writer, "UTF-8");
_log.debug(writer.toString());
Log.w("CONTENT: ", writer.toString());
byte[] result = new byte[MAX_FILE_SIZE]; //7242880 b
result = decodeBase64(writer.toString());
Log.w("BYTE ARRAY LENGTH: ", Integer.toString(result.length));
}
} catch (ClientProtocolException e) {
Log.e("Client: ", e.getMessage());
_log.error(e.getMessage());
return FAILED_DUE_TO_EXCEPTION;
} catch (IOException e) {
Log.e("IO: ", e.getMessage());
_log.error(e.getMessage());
return FAILED_DUE_TO_EXCEPTION;
}
return response.getStatusLine().toString();
}
The interesting point here is the result = decodeBase64(writer.toString()); and the decodeBase64 method:
protected byte[] decodeBase64(String s) {
return Base64.decode(s);
}
The String s is what I get from the webservice:
UEsDBBQACAgIAJteK0IAAAAAAAAAAAAAAAAZAAQAcmVzL2FuaW0vYWN0aXZpdHlmYWRlLnhtbP7KAABdkN9OwjAchc+PbW4YErnwgkRuuSGEek1MDI/SsMkmbF26es8D+AA+hs+hD6Wn0GXKab60/fq/ETK8CyCY4xNgL4TuCUPuyANZkEeyIXvySiaTqnGFbc1RO2MxHr9YU2+PbamRps5cWlmWv1ntKtNQ6ia3psqxXJbOtRul
This is not the whole file, but I can see that this is base64 encoded
When this string is passed inti the decodeBase64 method I only get this error message:
Then the application terminates. Is this the way to handle Base64 String? Can someone suggest how I can create a file from this base64 string? My first thought was to convert it to a byte array, and then create a file.
Looks to me like you've got a quoted string there - because " is what seems to be making it blow up. Is the web service returning a JSON string? If it is, then it will be surrounded by quotes and you have to take those off in order to parse it from base 64.

Facebook Extended Permission in C#

I'm developping a Facebook Application (using ASP.NET C# and Nathan Totten's Facebook C# SDK) and trying to access to extended permissions.
I tried on localhost (with an existing app in facebook), and everybody works. But when I try to use it directly in facebook, I obtain a blank page (i'm still connected on facebook).
Here is my code :
Page/aspx :
protected void btn_ask_question_Click(object sender, EventArgs e)
{
if (ControllerAccess.testUserConnected())
{
if (txt_ask_question.InnerText != "")
{
Dictionary<string, object> action = new Dictionary<string,object>();
action.Add("action", "askQuestion");
action.Add("message", txt_ask_question.InnerText);
action.Add("idTheme", ddl_choose_question_category.SelectedValue);
HttpContext.Current.Session["ActionToDo"] = action;
String s = Controller.GetExtendedPermission2(this, ControllerAccess.getScopeByAction("askQuestion"));
try{
Response.Redirect(s, false);
} catch(Exception ex)
{
}
}
}
}
In my Page_Load() :
if (HttpContext.Current.Session["ActionToDo"] != null)
{
Dictionary<string, object> action = HttpContext.Current.Session["ActionToDo"] as Dictionary<string, object>;
String s = action["action"].ToString();
switch (s)
{
case "askQuestion":
Guid idTheme;
Boolean themeExists = Guid.TryParse(action["idTheme"].ToString(), out idTheme);
if(themeExists)
{
askQuestion(action["message"].ToString(), idTheme);
lbl_errors.Text = "Votre question a bien été posée";
}
break;
default:
break;
}
HttpContext.Current.Session["ActionToDo"] = null;
}
In Control.cs :
public static string GetCustomOAuthDialogParameters(string AppID, string RedirectURI, string Scope, string State)
{
string CustomParameters = "?client_id=" + AppID + "&redirect_uri=" + RedirectURI + "&scope=" + Scope + "&state=" + State;
return CustomParameters;
}
public static void GetExtendedPermission(Page page, String scope)
{
ecritureFichier("GetExtendedPermission");
Label lbl_errors = page.Form.FindControl("lbl_errors") as Label;
string OAuthDialogAbsoluteURL = "";
try
{
string OAuthDialogURL = "https://www.facebook.com/dialog/oauth";
string PageLocation = GetCurrentPageFacebookPublishedPath(page.Request); //The redirect page (eg: https://apps.facebook.com/democsharpsdk/TestsExtendedPermission.aspx)
string UniqueReferenceCode = Guid.NewGuid().ToString();
OAuthDialogAbsoluteURL = OAuthDialogURL + GetCustomOAuthDialogParameters(AppID, PageLocation, scope, UniqueReferenceCode);
page.Response.Redirect(OAuthDialogAbsoluteURL, false);
}
catch (Exception exp)
{
lbl_errors.Text += "Erreur Catchée via ASP.NET : " + exp.Message;
}
}
The blank page appears when I use this line : page.Response.Redirect(OAuthDialogAbsoluteURL, false);
But I log all my steps and my OAuthDialogAbsoluteURL is correct :
https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXXXXXXXX&redirect_uri=https://apps.facebook.com/name_of_my_app&scope=email&state=0443030f-dddd-4fe6-9d6c-9454409d01b3
When I type it into the adress bar manually, everything works correctly.
Do you have any idea about the difference between local version and published version or why the redirect doesn't work? Maybe facebook block some requests?
Thanks.
Make sure you settings point to the hosted version if you want to use the app to test different environments. Facebook doesn't let you authorise a user from a site that isn't connect to your app for security reasons.
Normally, you would see an error like "URL isn't owned by Application" or similar.
I finally resolved my problem usingChrome Debugger. The error was :
Refused to display document because display forbidden by X-Frame-Options
I used Javascript to fix it, and did my redirection like this :
Response.Write("<script>");
Response.Write("window.open('"+redirect+"','_top')");
Response.Write("</script>");
Hope it'll help some people.

asp.net (C#) Facebook GetInfo()

I am struggling to get off with ground with some Facebook dev work. All I want to do is retireve some user info for the logged in user. This is the code I got from another site & it looks fine to me, however is always returns IsConnected() to be false.
I am running this code within an iframe on my facebook app (in sandbox mode)
private const string APPLICATION_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private const string SECRET_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
public Facebook.Rest.Api Api;
private Facebook.Session.ConnectSession _connectSession;
protected void Page_Load(object sender, EventArgs e)
{
_connectSession = new Facebook.Session.ConnectSession(APPLICATION_KEY,SECRET_KEY);
if (!_connectSession.IsConnected())
{
lit.Text = "Please sign-in with Facebook.";
}
else
{
try
{
Api = new Facebook.Rest.Api(_connectSession);
Facebook.Schema.user u = Api.Users.GetInfo();
img.ImageUrl = u.pic_square;
lit.Text = string.Format("Welcome, " + u.name);
}
catch (Exception ex)
{
lit.Text = ex.Message;
}
}
}
See this other SO question about a similar problem. The poster apparently found what he was looking for, but didn't know how to implement it. You may be able to do so, since there's a lot of information in the question body.

Categories

Resources