|
Richard MacCutchan wrote: No one here can guess what your code is doing. To be fair, I could guess.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
If you run your application on the WebServer where it is hosted, you may get more detail about the error without having to do anything else.
Try to RDC (Remote Desktop Connection) to that server.
|
|
|
|
|
No problem; there's a simple and guaranteed solution to this.
Step 1: Turn your computer off.
That's it. You will not see this error message again.
You're welcome.
|
|
|
|
|
I spent all day on this. It just started happening recently.
So I package a model in Angular, and create a body of JSON using JSON.stringify(model)
Then package it all up and send it as a promise. I just noticed that the JSON quotes are escaped out with a slash, and it crashes the API. If I take the slashes out, the API accepts the JSON.
I'm not sure what to make of this, and if I should fix the client side or work on the server side with this.
I put the replace(/\/g, "") in below to test the theory that it's the slashes crashing the API. Now the API works, but I can't see this as a permanent fix.
validateTokenAsPromise(signIn: SignIn): Promise<SignIn> {
const authUrl = this.baseUrl + "api/auth/AuthenticateAccount";
const toSignIn = JSON.stringify(signIn).replace(/\\/g, "");
const httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json"
})
};
return this.http.post<SignIn>(authUrl, toSignIn, httpOptions).toPromise();
}
I send it to a .Net Core controller api, and the api rejects the call, because of the data in the body.
The data has the quotes escaped out.
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[HttpPost("AuthenticateAccount")]
public async Task<SignIn> AuthenticateAccount([FromBody] SignIn authParam)
{
Sending this data to the API, normally it just sends raw, but I wrote a special service to handle Google SignIn and Googles gapi and gapi.auth2. I can't see how this special API" would encode the JSON.
{\"Id\":\"114251204162343478403\",\"FirstName\":\"John\",\"LastName\":\"Smith\",\"AccountName\":\"jsmith@hackme.com\",\"Password\":\"2H3HY4ZwE8Sb5Ajz\",\"Token\":\"eyJhbGciOiJIUsdadasdasd1lIjoiSmltIiwiZW1haWwiOiJqa2lya2VyeEBnbWFpbC5jb20iLCJuYmYiOjE1OTM0NjkwMDYsImV4cCI6MTU5MzY0MTgwNiwiaWF0IjoxNTkzNDY5MDA2LCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo1MDAxLyIsImF1ZCI6asdsadasdasdasdwMS9hcGkifQ.WdpYg8qDIUtIT4uobyAWVQ01k9iNYJ6wPpa6FIXm3Yg\",\"Role\":\"Customer\",\"ExpiresAt\":\"2020-06-29T23:26:03.812Z\",\"IdpId\":\"gapi\",\"RememberMe\":true,\"Avatar\":{\"Url\":\"https://lh3.googleusercontent.com/a-/AOasdasdasdGJB_aUO-asdasdasdg-ob=s96-c\"}}
Don't get excited about the data, it's fake.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Try removing the JSON.stringify call. I suspect the post method is encoding it again, so it's sending a string rather than a SignIn object.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Your spot on!
That was the issue. Double stringify.
But after thinking about it last night, and realizing the double stringify, I think I'll keep the replace function. So I put it back to my example. After testing without, seems to be more reliable with it. Weird, I create the model before I send the post. And I'm leaving the .Net side as is.
signIn(): Observable<boolean> {
let subject = new Subject<boolean>();
this.auth2.signIn().then(user => {
const profile = user.getBasicProfile(),
auth = user.getAuthResponse(),
token = localStorage.getItem("authToken");
let gU = new SignIn();
gU.Id = profile.getId();
gU.FirstName = profile.getGivenName();
gU.LastName = profile.getFamilyName();
gU.AccountName = profile.getEmail();
gU.Password = "2LsdFDdsfb5Ejr";
gU.Token = token !== null ? token : "";
gU.Role = "Account";
gU.ExpiresAt = new Date(auth.expires_at);
gU.IdpId = "google";
gU.RememberMe = true;
gU.Avatar = new Avatar();
gU.Avatar.Url = profile.getImageUrl();
this.validateTokenAsPromise(gU)
.then(user => {
this.zone.run(() => {
if (user) {
localStorage.setItem("Account", JSON.stringify(user, null, "\t"));
if (user.Token) {
localStorage.setItem("authToken", user.Token);
}
this.user$.next(user);
this.isLoggedIn$.next(true);
this.auth2SignedIn.emit(true);
subject.next(true);
} else {
this.isLoggedIn$.next(false);
this.auth2SignedIn.emit(false);
subject.next(false);
}
});
},
(err) => {
console.error("GAuth2 Service Error", err);
this.isLoggedIn$.next(false);
this.auth2SignedIn.emit(false);
subject.next(false);
});
});
return subject.asObservable();
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
hello! I have a problem when I want to retrieve data in my application I got this error :
erreur du serveur dans l'application '/'. opération non valide. la connexion est fermée
in asp.net MVC
|
|
|
|
|
Something is setup wrong. Not sure what you want us to do.
Social Media - A platform that makes it easier for the crazies to find each other.
Everyone is born right handed. Only the strongest overcome it.
Fight for left-handed rights and hand equality.
|
|
|
|
|
At a guess, you forgot to open your database connection. But it is just a guess, since you haven't shown us any of your code or the details of the error.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
here's the error:
Erreur du serveur dans l'application '/'.
Opération non valide. La connexion est fermée.
Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code.
Détails de l'exception: System.InvalidOperationException: Opération non valide. La connexion est fermée.
Erreur source:
Une exception non gérée s'est produite lors de l'exécution de la requête Web actuelle. Les informations relatives à l'origine et l'emplacement de l'exception peuvent être identifiées en utilisant la trace de la pile d'exception ci-dessous.
Trace de la pile:
[InvalidOperationException: Opération non valide. La connexion est fermée.]
System.Data.ProviderBase.DbConnectionClosed.get_ServerVersion() +80
System.Data.Odbc.OdbcConnection.get_ServerVersion() +12
|
|
|
|
|
this my code:
public DataSet GetLs(string que)
{
DataSet ds1 = new DataSet();
try
{
cn.Open();
cm.Connection = cn;
cm.CommandText = que;
cm.CommandType = CommandType.Text;
OdbcDataAdapter da1 = new OdbcDataAdapter(cm);
da1.Fill(ds1);
return ds1;
}
catch (Exception e)
{
throw e;
}
finally
{
cn.Close();
}
}
my function
public JsonResult LstDepartement()
{
DataSet ds2 =Dt.GetLsts ("select * from Departement");
List<Departement> lstDepart = new List<Departement>();
foreach (DataRow dr1 in ds2.Tables[0].Rows)
{
lstDepart.Add(new Departement
{
ID = dr1["Id_Depart"].ToString(),
Désignation = dr1["Departement"].ToString(),
});
}
return Json(lstDepart, JsonRequestBehavior.AllowGet);
}
|
|
|
|
|
Except ... The first bit of code doesn't call the second:
public DataSet GetLs(string que)
{
...
}
public JsonResult LstDepartement()
{
DataSet ds2 =Dt.GetLsts ("select * from Departement");
...
} GetLs and GetLsts are not the same method ...
And to be honest, doing SQL that way is a very poor idea.
The trouble is that it's prone to SQL Injection. Suppose you want to get departments that all use the same SalesCode - that's easy, add a WHERE clause that specifies the code:
DataSet ds2 =Dt.GetLsts ("SELECT * FROM Departement WHERE SalesCode = " + salescCode);
But ... that's really dangerous!
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.
When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood' The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable; Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x'; A perfectly valid SELECT
DROP TABLE MyTable; A perfectly valid "delete the table" command
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.
So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
And your system has no way to add parameters to a command, because you don't create the command until you have built the command string!
I'd strongly suggest you scrap that code and "do it properly" instead.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
GetLs and GetLsts both have the same instructions.
I don't add the where clause because I populate a dropdown list.
that's the reason why I use it.
my GetLsts is:
public DataSet GetLsts(string que)
{
DataSet ds1 = new DataSet();
try
{
cnxs.Open();
cmds.Connection = cnxs;
cmds.CommandText = que;
cmds.CommandType = CommandType.Text;
SqlDataAdapter da1 = new SqlDataAdapter(selectCommand: cmds);
da1.Fill(ds1);
return ds1;
}
catch (Exception e)
{
throw e;
}
finally
{
cnxs.Close();
}
}
I don't know if
|
|
|
|
|
Read the error message - it's pretty explicit.
The OdbcConnection object is not open.
That means that you have created an instance, and either tried to open it but the operation failed (and you swallowed the exception), you didn't try to open it, or you opened it then subsequently closed it again.
Without your code, there isn't a lot we can add to that...
Your code should look something like this:
using (OdbcConnection con = new OdbcConnection(strConnect))
{
con.Open();
using (OdbcCommand cmd = new OdbcCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
{
cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
using (OdbcDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int age = (int) reader["Age"];
string desc = (string) reader["Description"];
Console.WriteLine($"{age}\n{desc}");
}
}
}
}
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi all, I have a Winforms application which I want to use a local DAL when a remote Net Core API is not available. Currently I have if statements (lots of them ) such as
if(! APIAvailable())
Call the local DAL;
else
Call the Remote API;
The API and local DAL have identical methods and properties, I would like a more elegant and extendable way of handling this
Any ideas guys ?
"We can't stop here - this is bat country" - Hunter S Thompson - RIP
|
|
|
|
|
Surely that check need to be in your local DAL where there are limited methods and you choose between the source.
Or using the accepted nomenclature create a datacontext based on the availability at initiation and use that everywhere.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
That check need to be in your local DAL where there are limited methods and you choose between the source.
That's what I currently do and it results in lots of if statements
"We can't stop here - this is bat country" - Hunter S Thompson - RIP
|
|
|
|
|
Your DAL should only have about 6 methods accessing the database/API, called by your business object layer. I suspect your BO layer is calling into the database.
If the DAL has a property IsAPIAvailable set at initialisation which should set a DataContext property that all the methods in the DAL call to access the data source.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
How is APIAvailable implemented, and how likely is it to change?
Perhaps you could have both services implement an interface, and do something with DI to inject the correct implementation.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi Richard, what I do to see if my API service is running is, ping it and if I get a reply create a socket on the port and try to open it
This is the code I use ( which I believe I got from OG years ago )
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace BOMBuilder
{
public class NetworkUtils
{
private StringBuilder errormessage = new StringBuilder();
private bool portIsOpen = false;
private bool serverIsUp = true;
private bool hasErrors = false;
private bool HasErrors
{
get
{
return hasErrors;
}
set
{
hasErrors = value;
}
}
private bool ServerIsUp
{
get
{
return serverIsUp;
}
set
{
serverIsUp = value;
}
}
private bool PortIsOpen
{
get
{
return portIsOpen;
}
set
{
portIsOpen = value;
}
}
private StringBuilder Errormessage
{
get
{
return errormessage;
}
set
{
errormessage = value;
}
}
public string GetErrorMessage()
{
return Errormessage.ToString();
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct ICMP_OPTIONS
{
public byte Ttl;
public byte Tos;
public byte Flags;
public byte OptionsSize;
public IntPtr OptionsData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct ICMP_ECHO_REPLY
{
public int Address;
public int Status;
public int RoundTripTime;
public short DataSize;
public short Reserved;
public IntPtr DataPtr;
public ICMP_OPTIONS Options;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 250)]
public string Data;
}
[DllImport("icmp.dll", SetLastError = true)]
private static extern IntPtr IcmpCreateFile();
[DllImport("icmp.dll", SetLastError = true)]
private static extern bool IcmpCloseHandle(IntPtr handle);
[DllImport("icmp.dll", SetLastError = true)]
private static extern int IcmpSendEcho(IntPtr icmpHandle, int destinationAddress, string requestData, short requestSize, ref ICMP_OPTIONS requestOptions, ref ICMP_ECHO_REPLY replyBuffer, int replySize, int timeout);
public void Ping(IPAddress ip, int port)
{
this.ServerIsUp = false;
this.PortIsOpen = true;
IntPtr icmpHandle = IcmpCreateFile();
ICMP_OPTIONS icmpOptions = new ICMP_OPTIONS();
icmpOptions.Ttl = 20;
ICMP_ECHO_REPLY icmpReply = new ICMP_ECHO_REPLY();
string sData = "x";
IcmpSendEcho(icmpHandle, BitConverter.ToInt32(ip.GetAddressBytes(), 0), sData, (short)sData.Length, ref icmpOptions, ref icmpReply, Marshal.SizeOf(icmpReply), 1);
IcmpCloseHandle(icmpHandle);
ServerIsUp = icmpReply.Status == 0;
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
if (ServerIsUp)
s.Connect(ip, port);
}
catch (SocketException se)
{
PortIsOpen = false;
HasErrors = true;
Errormessage.Append(se.Message);
}
finally
{
if (s.Connected)
s.Disconnect(false);
}
}
public bool ServerIsRunningOn(IPAddress iPAddress, int port)
{
this.Ping(iPAddress, port);
return (this.ServerIsUp && this.PortIsOpen);
}
}
}
"We can't stop here - this is bat country" - Hunter S Thompson - RIP
|
|
|
|
|
I tried that once in a WinForms app, it didn't work very well.
I wrote the same thing, a ping check, but it sort of got unstable as sometimes pings were rejected. I think the webmaster turned off pings after I wrote the code, or it was turned off somewhere in the pipe. It became an issue after I deployed the program in production use.
Then I went to another form of checking, not a ping but a HTTP reply and it worked much better.
My WinForms app already had a qualified DAL and business logic, which worked fine, but the online check is the part that was not stable. Basically what I'm saying is that after you fix the part your working on now, you'll end up revisiting the check part again.
In hindsight, I think bullet proofing the API server and it's controller actions, such as writing very simple code using a model and repository, and load testing that API call is the correct thing to do.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Yes I think you're right I should forget about whether I have access to the the internet - like everything these days you're screwed without it - thanks for your time
"We can't stop here - this is bat country" - Hunter S Thompson - RIP
|
|
|
|
|
Face some problem when using checkbox list..
need some help
the checkbox with the text. no matter how i adjust.. it also wont be align...
this is my code:
<asp:CheckBoxList ID="ChkEditAccess" runat="server" OnSelectedIndexChanged="ChkEditAccess_SelectedIndexChanged" AutoPostBack="true" RepeatLayout="Flow" TextAlign="Right" Style="text-align:left;" RepeatDirection="Vertical" CellSpacing="20">
<asp:ListItem >Admin</asp:ListItem>
<asp:ListItem>Report</asp:ListItem>
<asp:ListItem>Dashboard</asp:ListItem>
</asp:CheckBoxList>
the outcome result :
the checkbox and the text, is, not align to center,
the checkbox is slightly higher than the text.
<img src="https://i.postimg.cc/xJZ0ZGpy/OutCome.jpg" alt="Result" >
i try different way. vertical align, text align, align item all dint work...
modified 30-May-20 12:25pm.
|
|
|
|
|
Hi all, I have a net core 3.1 api service which runs perfectly on my Linux dev machine but fails to start on a remote Linux machine with a HTTP/1.1 500 Internal Server Error - I know this a very sweeping error message !! how can I track / catch the exception ? I've tried the usual try catch method but because this doesn't have a front end I don't see any feedback
"We can't stop here - this is bat country" - Hunter S Thompson - RIP
|
|
|
|
|
Do you have access to log in to the remote server? If so, you could try using the dotnet command to run the application from the command line.
Otherwise, you might need to enable detailed errors:
ASP.NET Core Web Host | Microsoft Docs[^]
You can either set the ASPNETCORE_DETAILEDERRORS environment variable to true , or add:
.UseSetting(WebHostDefaults.DetailedErrorsKey, "true") to your host builder.
Handle errors in ASP.NET Core | Microsoft Docs[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|