Strange issue when no breakpoint is set when calling SslStream.AuthenticateAsServer - .net-4.5

I am adding some code to a legacy application running .net 4.5.2. I copied some code from .net 4.8 solution for decrypting the Ssl Stream. My Code works fine when I have a breakpoint right on or right after SslStream.AuthenticateAsServer. if I statement "return sslStream"
public SslStream DecrtyptStream(TcpClient client)
{
bool clientCertificateRequired = false;
SslStream sslStream = null;
if (gTLS_CertEnable == "Yes")
{
clientCertificateRequired = true;
sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(_validateServerCertificate));
}
else
{
sslStream = new SslStream(client.GetStream(), false);
}
sslStream.ReadTimeout = 60000;
sslStream.WriteTimeout = 5000;
if (gTLS_Ver == "TLS1.0")
{
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls, true);
}
else if (gTLS_Ver == "TLS1.1")
{
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11, true);
}
else
{
//https://stackoverflow.com/questions/38236302/the-client-and-server-cannot-communicate-because-they-do-not-possess-a-common-a
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls12, true);
}
return sslStream;
}
When I remove the breakpoint I get this error:
The client and server cannot communicate, because they do not possess
a common algorithm.
So as shown in a stackoverflow post I changed it to
sslStream.AuthenticateAsServer(_serverCertificate, clientCertificateRequired, SslProtocols.Tls11 | SslProtocols.Tls | SslProtocols.Tls12, true);
I get this error message:
The supplied message is incomplete. The signature was not verified
But still if I add a breakpoint, this error does not happen.

Related

Play game saves ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution doesn't invoke save function

Good day!
I am new to Google Play Services and want to save JSON(string) into the cloud and it doesn't work. I narrowed down a problem through phone and debug texts and realized that a function from ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution is not called which is strange because in the tutorial that I watched everything worked and the user logged in successfuly.
here is a code snippet with a comments and a function that is not invoked(I can send a whole script if needed also). Is there something else I am missing?
public void OpenSaveToCloud(bool saving)
{
// debugtext.text = "hello";
if(Social.localUser.authenticated)
{
debugtext.text = "Authorized and proceed to save";
issaving = saving;
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution
(SAVE_NAME, GooglePlayGames.BasicApi.DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime, SavedGameOpen); //SavedGame open must be called
}
else{
debugtext.text = "No authentication";
}
}
private void SavedGameOpen(SavedGameRequestStatus status, ISavedGameMetadata meta)//this function is not called
{
if(status == SavedGameRequestStatus.Success)
{
// debugtext.text = "hello in save1";
if (issaving)//if is saving is true we are saving our data to cloud
{
debugtext.text = "Saving....";
byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(GetDataToStoreinCloud());
SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(meta, update, data, SaveUpdate);
}
else//if is saving is false we are opening our saved data from cloud
{
debugtext.text = "Loading...";
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(meta, ReadDataFromCloud);
}
}
else{
debugtext.text = "Save request status broke";
}
}
What I checked twice before posting question:
Turned on Saved Games in google console
made build with your keystore and password
add email id in game service's tester section
Mistake is that you have to initialize save games from start as well and I didn't know that so answer would be
if (platform == null)
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().EnableSavedGames().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
platform = PlayGamesPlatform.Activate();
}

Can two ASP . NET Core 5.0 web api cause "The content may be already have been read by another component" errpr 400 if they accessed same db be4?

My API was as follows:
[HttpPut("{id}")]
public async Task<ActionResult<HomeContextModel>> EditHomeContext(int id, string title, string context, string subcontext, IFormFile imageFile)
{
HomeContextModel homeContextModel = await _context.HomeContext.Include(x => x.Image).Include(x => x.Button).Include(x => x.Logo).ThenInclude(y => y.Image)
.FirstOrDefaultAsync(m => m.Context_Id == id);
//HomeContextModel homeContextModel = await GetHomeContextModel(id);
if (homeContextModel == null)
{
return BadRequest("Context Id cannot be null");
}
if (imageFile != null)
{
ImageModel imageModel = homeContextModel.Image;
if (imageModel != null)
{
string cloudDomain = "https://privacy-web.conveyor.cloud";
string uploadPath = _webHostEnvironment.WebRootPath + "\\Images\\";
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string filePath = uploadPath + imageFile.FileName;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
using (var memoryStream = new MemoryStream())
{
await imageFile.CopyToAsync(memoryStream);
imageModel.Image_Byte = memoryStream.ToArray();
}
imageModel.ImagePath = cloudDomain + "/Images/" + imageFile.FileName;
imageModel.Modify_By = "CMS Admin";
imageModel.Modity_dt = DateTime.Now;
//_context.Update(imageModel);
}
}
homeContextModel.Title = title;
homeContextModel.Context = context;
homeContextModel.SubContext = subcontext;
_context.Entry(homeContextModel).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HomeContextModelExists(homeContextModel.Context_Id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok("Home Context Edit Successfully");
}
It's an API for the Content Management System (CMS) to change the content of the Homepage using a Flutter webpage that make put request onto this API.
Everything works fine. In the last few days, where I tested and tested again during the development. So before today, I've wrapped up them and submitted to the necessary place (It's a university FYP).
Until now it cause me this error when I was using this to prepare my presentation:
Error 400 failed to read the request form Unexpected end of stream ..."
After all the tested I tried:
Internet solutions
restore the database
repair Microsoft VS 2019 (As this issue was fixed before after I
updated my VS 2019 from 16.8. to the latest 16.11.7)
Use the ASP .NET file which didn't caused this issue before
Then I realized it may be because of I used another older ASP file to accessed the same database before. Does this really cause this matter?
If yes, then now how should I solved it, with the action I already done (listed as above)?
EDIT: Additional description to the situation
The above API I set breakpoint before, on the first line, using Swagger to test it.
It turns out that it didn't go into the API and straightaway return the error 400
REST API can have parameters in at least two ways:
As part of the URL-path
(i.e. /api/resource/parametervalue)
As a query argument
(i.e. /api/resource?parameter=value)
You are passing your parameters as a query instead of a path as indicated in your code. And that is why it is not executing your code and returning 400.

AEM - How to tweak activation error message

We are working in an AEM 6.1 environment and have created an activation preprocessor that will stop pages from being activated if certain attributes are not set. That works great but we'd also like to change the error message that's displayed by the activation process when the preprocessor throws a ReplicationExcdeption. Can anyone point me to the code that actually displays the error message?
We overrided several functions in SiteAdmin.Actions.js. Copy it from libs folder /apps/cq/ui/widgets/source/widgets/wcm/SiteAdmin.Actions.js or use CQ.Ext.override
We need to override CQ.wcm.SiteAdmin.scheduleForActivation and CQ.wcm.SiteAdmin.internalActivatePage methods.
We do it with using the following code
CQ.wcm.SiteAdmin.internalActivatePage = function(paths, callback) {
if (callback == undefined) {
// assume scope is admin and reload grid
var admin = this;
callback = function(options, success, response) {
if (success) admin.reloadPages();
else admin.unmask();
};
}
preActionCallback = function(options, success, response) {
if (success) {
var responseObj = CQ.Util.eval(response);
if (responseObj.activation) {
CQ.HTTP.post(
CQ.shared.HTTP.externalize("/bin/replicate.json"),
callback,
{ "_charset_":"utf-8", "path":paths, "cmd":"Activate" }
);
} else {
CQ.wcm.SiteAdmin.preactivateMessage(responseObj);
}
}else{
CQ.Ext.Msg.alert(
CQ.I18n.getMessage("Error"), CQ.I18n.getMessage("Could not activate page."));
}
admin.unmask();
};
CQ.HTTP.get(
"/apps/sling/servlet/content/preActivateValidator.html?path=" + paths,
preActionCallback
);
};
This path /apps/sling/servlet/content/preActivateValidator.html (You can use any other link and extension) returns json with some info about messages, which are parsed in custom method and generates custom error messages CQ.wcm.SiteAdmin.preactivateMessage:
CQ.wcm.SiteAdmin.preactivateMessage = function(responseObj) {
var message = "";
var incorrectItems = responseObj.incorrectItems;
if (responseObj.countOfIncorrectItems > 1) message = message + "s";
if (responseObj.missingMetadata) {
message = message + "Please, set \"Programming Type\" for next videos:<br/>";
var missingMetadataPaths = responseObj.missingMetadata;
for(var i = 0; i < missingMetadataPaths.length; i++){
message = message + ""+missingMetadataPaths[i].path+"<br/>";
}
message += "<br/>";
}
if(message == ""){
message = "Unknown error.";
}
CQ.Ext.Msg.alert(
CQ.I18n.getMessage("Error"), CQ.I18n.getMessage(message));
}
So you can implement component or servlet which will verify your attributes and will generate JSON.

Xamarin.Forms Consume Rest Service

I'm new to Xamarin and developing native apps in general (I have made html5 apps in the past).
I have started on a Xamarin.Forms project and I'm trying to contact a REST like API (need to GET an URL which will return a json array).
Normally from C# I would use RestSharp and perform this call using the RestClient.
I'm not having any luck installing that package from Xamarin Studio though, but I have got the Microsoft HTTP Libraries installed.
I'm pretty sure this is a very trivial task to perform, I just haven't been able to adapt the samples I have found online to work for me.
Anyone who could post how this is done please (remember I'm new to this so don't expect me to understand everything that is different from say a normal console app)?
It is easy with HTTP Client and JSON.NET here is a example of a GET:
public async Task<List<Appointment>> GetDayAppointments(DateTime day)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken);
//Your url.
string resourceUri = ApiBaseAddress;
HttpResponseMessage result = await client.GetAsync (resourceUri, CancellationToken.None);
if (result.IsSuccessStatusCode) {
try {
return GetDayAppointmentsList(result);
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
} else {
if(TokenExpired(result)){
App.SessionExpired = true;
App.ShowLogin();
}
return null;
}
return null;
}
private List<Appointment> GetDayAppointmentsList(HttpResponseMessage result){
string content = result.Content.ReadAsStringAsync ().Result;
JObject jresponse = JObject.Parse (content);
var jarray = jresponse ["citas"];
List<Appointment> AppoinmentsList = new List<Appointment> ();
foreach (var jObj in jarray) {
Appointment newApt = new Appointment ();
newApt.Guid = (int)jObj ["id"];
newApt.PatientId = (string)jObj ["paciente"];
newApt.Name = (string)jObj ["nombre"];
newApt.FatherLstName = (string)jObj ["paterno"];
newApt.MotherLstName = (string)jObj ["materno"];
string strStart = (string)jObj ["horaIni"];
TimeSpan start;
TimeSpan.TryParse (strStart, out start);
newApt.StartDate = start;
string strEnd = (string)jObj ["horaFin"];
TimeSpan end;
TimeSpan.TryParse (strEnd, out end);
newApt.EndDate = end;
AppoinmentsList.Add (newApt);
}
return AppoinmentsList;
}
I use System.Net.WebClient and our asp.net WebAPI interface:
public string GetData(Uri uri)
{//uri like "https://webapi.main.cz/api/root"
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
//You can set webClient.Headers there
webClient.Encoding = System.Text.Encoding.UTF8;
ret = webClient.DownloadString(uri));//Test some data received
//In ret you can have JSON string
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
4
public string SendData(Uri uri, byte[] data)
{//uri like https://webapi.main.cz/api/PostCheckLicence/
string ret = "ERROR";
try
{
using (WebClient webClient = new WebClient())
{
webClient.Headers[HttpRequestHeader.Accept] = "application/octet-stream";
webClient.Headers[HttpRequestHeader.ContentType] = "text/bytes";
webClient.Encoding = System.Text.Encoding.ASCII;
byte[] result = webClient.UploadData(uri, data);
ret = Encoding.ASCII.GetString(result);
if (ret.Contains("\"ResultWebApi\":\"OK"))
{//In ret you can have JSON string
}
else
{
}
}
}
catch (Exception ex) { ret = ex.Message; }
return ret;
}
x
I've some examples in my Github repo. Just grab the classes there and give them a try. The API is really easy to use:
await new Request<T>()
.SetHttpMethod(HttpMethod.[Post|Put|Get|Delete].Method) //Obligatory
.SetEndpoint("http://www.yourserver.com/profilepic/") //Obligatory
.SetJsonPayload(someJsonObject) //Optional if you're using Get or Delete, Obligatory if you're using Put or Post
.OnSuccess((serverResponse) => {
//Optional action triggered when you have a succesful 200 response from the server
//serverResponse is of type T
})
.OnNoInternetConnection(() =>
{
// Optional action triggered when you try to make a request without internet connetion
})
.OnRequestStarted(() =>
{
// Optional action triggered always as soon as we start making the request i.e. very useful when
// We want to start an UI related action such as showing a ProgressBar or a Spinner.
})
.OnRequestCompleted(() =>
{
// Optional action triggered always when a request finishes, no matter if it finished successufully or
// It failed. It's useful for when you need to finish some UI related action such as hiding a ProgressBar or
// a Spinner.
})
.OnError((exception) =>
{
// Optional action triggered always when something went wrong it can be caused by a server-side error, for
// example a internal server error or for something in the callbacks, for example a NullPointerException.
})
.OnHttpError((httpErrorStatus) =>
{
// Optional action triggered when something when sending a request, for example, the server returned a internal
// server error, a bad request error, an unauthorize error, etc. The httpErrorStatus variable is the error code.
})
.OnBadRequest(() =>
{
// Optional action triggered when the server returned a bad request error.
})
.OnUnauthorize(() =>
{
// Optional action triggered when the server returned an unauthorize error.
})
.OnInternalServerError(() =>
{
// Optional action triggered when the server returned an internal server error.
})
//AND THERE'S A LOT MORE OF CALLBACKS THAT YOU CAN HOOK OF, CHECK THE REQUEST CLASS TO MORE INFO.
.Start();
And there's a couple of examples.
For all my Xamarin Forms app I use Tiny.RestClient.
It's easy to get it and easy to use it.
You have to download this nuget.
And after it just very easy to use it :
var client = new TinyRestClient(new HttpClient(), "http://MyAPI.com/api");
var cities = client.
GetRequest("City").
AddQueryParameter("id", 2).
AddQueryParameter("country", "France").
ExecuteAsync<City>> ();
Hopes that helps.

Firefox: Communicator presence issue

We are using NameCtrl in our application and works fine in IE. But the same is not working in Firefox. The firefox website says that they doesnt support ActiveX controls. http://support.mozilla.com/en-US/kb/ActiveX
Is there a way to show communicator presence in Firefox too?
A little late, but this IS possible using browsers other than IE.
if(window.ActiveXObject) {
nameCtrl = new ActiveXObject("Name.NameCtrl");
} else {
try {
nameCtrl = new ActiveXObject("Name.NameCtrl");
} catch (e){
nameCtrl = (function(b){
var c = null;
try {
c = document.getElementById(b);
if (!Boolean(c) && (Boolean(navigator.mimeTypes) && navigator.mimeTypes[b] && navigator.mimeTypes[b].enabledPlugin)) {
var a = document.createElement("object");
a.id = b;
a.type = b;
a.width = "0";
a.height = "0";
a.style.setProperty("visibility", "hidden", "");
document.body.appendChild(a);
c = document.getElementById(b)
}
} catch (d) {
c = null
}
return c
})("application/x-sharepoint-uc");
}
}
if(nameCtrl && nameCtrl.PresenceEnabled){
// code here
}
The NameCrl is an ActiveX component so it will only work in Internet Explorer.
There is no way to do this without custom development. I would suggest using the UCMA APis, building a service that queries presence, and building a JavaScript API to call this service.