How to validate mssql server credentials - inno-setup

In my project, I use Inno to run a .sql script to create a database. I use a custom page to write SQL Server instance name user and password to run the script.
I would like to add the validation of the entered credentials. What's the best way?
Update:
I'm testing this approach
function ConnDBAndExecSql(istanza,utente,password:string):Boolean;
var
ADOConnection: Variant;
begin
Result := False;
try
// create the ADO connection object
ADOConnection := CreateOleObject('ADODB.Connection');
// build a connection string; for more information, search for ADO
// connection string on the Internet
ADOConnection.ConnectionString :=
'Provider=SQLOLEDB.1;' + // provider
'Data Source='+ istanza +';' + // server name
'Persist Security Info=True;' +
'User Id=' + utente + ';' + // user name
'Password='+ password + '; '; // password
// open the connection by the assigned ConnectionString
ADOConnection.Open;
Result := True;
//ADOConnection.Connected:=True;
except
Result:= False;
end;
end;

Related

Business Central Get Token SharePoint

I'm trying to connect the business central with the sharepoint, I already did it in the postman, it worked fine, the GET and POST.
But now Im trying to do it on BC, the token is created but not working, I think it has some problem with the connection or the URL's.
codeunit 50100 "APISharePoint"
{
var
OAuth2: Codeunit OAuth2;
ClientIdTxt: Label '4d148348-137a-40e7-b20c-a458c2a03c65', Locked = true;
ClientSecret: Label 'Ai2pOhE7yeZ8WRxrwSrHdpVtNqJg51tg2X+s8CJDLy4=', Locked = true;
ResourceUrlTxt: Label 'https://crmbc384959.sharepoint.com', Locked = true;
OAuthAuthorityUrlTxt: Label 'https://login.microsoftonline.com/ec36749a-af47-4f04-892c-98666b6cac1b/oauth2/v2.0/token', Locked = true;
procedure GetAccessToken(): Text
var
PromptInteraction: Enum "Prompt Interaction";
AccessToken: Text;
AuthCodeError: Text;
RedirectURLTxt: Text;
begin
// OAuth2.GetDefaultRedirectURL(RedirectURLTxt);
RedirectURLTxt := 'https://localhost';
if OAuth2.AcquireTokenWithClientCredentials(ClientIdTxt, ClientSecret, OAuthAuthorityUrlTxt, RedirectURLTxt, ResourceURLTxt, AccessToken) then
exit(AccessToken)
else
exit('');
end;
procedure HttpGet(AccessToken: Text; Url: Text /*var JResponse: JsonObject*/): Boolean
var
Client: HttpClient;
Headers: HttpHeaders;
RequestMessage: HttpRequestMessage;
ResponseMessage: HttpResponseMessage;
RequestContent: HttpContent;
ResponseText: Text;
IsSucces: Boolean;
begin
Headers := Client.DefaultRequestHeaders();
Headers.Add('Authorization', StrSubstNo('Bearer %1', AccessToken));
Headers.Add('Accept', 'application/json;odata=verbose');
RequestMessage.Content.GetHeaders(Headers); //asd
Headers.Remove('Content-Type');
Headers.Add('Content-Type', 'application/json;odata=verbose');
RequestMessage.SetRequestUri(Url);
RequestMessage.Method := 'GET';
if Client.Send(RequestMessage, ResponseMessage) then
if ResponseMessage.IsSuccessStatusCode() then begin
if ResponseMessage.Content.ReadAs(ResponseText) then
IsSucces := true;
// end else
// ResponseMessage.Content.ReadAs(ResponseText);
// JResponse.ReadFrom(ResponseText);
exit(IsSucces);
end;
end;
Maybe your problem is the combination of GET with a request content.
As far as i know, the underlaying implementation of the HttpClient in .NET does not support GET with a request content. You can read more about it here: How to use HttpClient to send content in body of GET request?
Maybe you can try GET without setting the content-type on the content or use POST or PUT instead.
But you didn't supply a error message so this is just a guess.

unable to create session: control: unable to connect to initial hosts: Invalid Cosmos DB account or key

I have been trying to connect to cosmos cassandra db using gocql.
func GetSession(cosmosCassandraContactPoint, cosmosCassandraPort, cosmosCassandraUser, cosmosCassandraPassword string) *gocql.Session {
clusterConfig := gocql.NewCluster(cosmosCassandraContactPoint)
port, err := strconv.Atoi(cosmosCassandraPort)
if err != nil {
log.Fatal(err)
}
clusterConfig.Port = port
clusterConfig.ProtoVersion = 4
clusterConfig.Authenticator = gocql.PasswordAuthenticator{Username: cosmosCassandraUser, Password: cosmosCassandraPassword}
clusterConfig.SslOpts = &gocql.SslOptions{Config: &tls.Config{MinVersion: tls.VersionTLS12}}
clusterConfig.ConnectTimeout = 10 * time.Second
clusterConfig.Timeout = 10 * time.Second
clusterConfig.DisableInitialHostLookup = true
// uncomment if you want to track time taken for individual queries
//clusterConfig.QueryObserver = timer{}
// uncomment if you want to track time taken for each connection to Cassandra
//clusterConfig.ConnectObserver = timer{}
session, err := clusterConfig.CreateSession()
if err != nil {
log.Fatal("Failed to connect to Azure Cosmos DB", err)
}
return session
}
I have been getting the following error :
unable to create session: control: unable to connect to initial hosts: Invalid Cosmos DB account or key
Not sure what the issue here is.
It doesn't look like you've configured the necessary options for the SSL/TLS configuration, particularly the certificates.
I haven't connected to a Cosmos DB before so I'm not sure of the certs/keys required but I previously helped someone configure the gocql driver with the right TLS settings in this post -- https://community.datastax.com/questions/3753/.
In their environment, they needed to provide the certs and keys to connect as follows:
certPath, _ := filepath.Abs("/home/erick/astra-bundle/cert")
keyPath, _ := filepath.Abs("/home/erick/astra-bundle/key")
caPath, _ := filepath.Abs("/home/erick/astra-bundle/ca.crt")
cert, _ := tls.LoadX509KeyPair(certPath, keyPath)
caCert, _ := ioutil.ReadFile(caPath)
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
cluster.SslOpts = &gocql.SslOptions{
Config: tlsConfig,
EnableHostVerification: false,
}
Details are in the post above. I hope this helps. Cheers!
It seems your account or key is wrong.
First,please make sure your API is CASSANDRA API.You can check at here.
Second,please make sure your account or key is right.
COSMOSDB_CASSANDRA_CONTACT_POINT=<value for "CONTACT POINT">
COSMOSDB_CASSANDRA_PORT=<value for "PORT">
COSMOSDB_CASSANDRA_USER=<value for "USERNAME">
COSMOSDB_CASSANDRA_PASSWORD=<value for "PRIMARY PASSWORD">
You can find them here:
More details,you can refer to this documentation.
Hope this can help you.

Passing certificate and key as string to ListenAndServeTLS

I am creating an app using Go and I am trying to start a https server using the ListenAndServeTLS function. Here is my code:
func StartServer() {
defer config.CapturePanic()
c := config.GetInstance()
serverAddress := fmt.Sprintf(":%s", c.GetConfig().ServerPort)
server := http.Server{Addr: serverAddress}
log.Info("Starting local server")
http.HandleFunc("/", login.Handler)
http.HandleFunc("/login", login.Handler)
http.HandleFunc("/settings", settings.Handler)
//cert, _ := data.Asset("my-cert.pem")
//key, _ := data.Asset("my-key.pem")
err := server.ListenAndServeTLS("my-cert.crt", "my-cert.key")
if err != nil {
log.WithError(err).Fatal("Error stopping local server")
}
}
The thing is that I would like to embed my certificate and its key inside my executable file and then pass them to the the server.ListeAndServeTLS function as a string or a byte array. However this function does not take these types of arguments. Is there another way to do this?
Note: I am aware that it is a bad practice to embed a private key inside a client application, however what I am trying to do here is just to create a config webpage that will be hosted as https://localhost:8080.
You can build your own server object and still call ListenAndServeTLS. Since your tls config has certificates, it will ignore the passed-in filenames.
I'm omitting the return on error for conciseness, please do not:
// Generate a key pair from your pem-encoded cert and key ([]byte).
cert, err := tls.X509KeyPair(<cert contents>, <key contents>)
// Construct a tls.config
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert}
// Other options
}
// Build a server:
server := http.Server{
// Other options
TLSConfig: tlsConfig,
}
// Finally: serve.
err = server.ListenAndServeTLS("", "")
In my case, I was unable to load files from disk, but did have the certificates passed in to the environment as variables ([]byte).
Adding on to Marc's answer, I had to only change the top line.
// Append signed leaf certificate and intermediate to a single
certChain := append(leaf.PublicBytes, intermediate.PublicBytes...)
// Generate a key pair from your pem-encoded cert and key ([]byte).
cert, err := tls.X509KeyPair(certChain, leaf.PrivateBytes)
...

How to authenticate username and password in Inno Setup by reading registry

I want to authenticate the password from registry.
While installing it should read the password from registry using Inno Setup.
Just see the official example for the RegQueryStringValue function:
var
Country: String;
begin
if RegQueryStringValue(HKEY_CURRENT_USER, 'Control Panel\International',
'sCountry', Country) then
begin
{ Successfully read the value }
MsgBox('Your country: ' + Country, mbInformation, MB_OK);
end;
end;

Is it possible to add HTML form in Inno setup?

I have created a custom installer for a game. I need to update version of my installer with a new feature. The game needs to register to play online. So I need to embed register form from web page (or use HTML codes directly into Inno Setup pages after installation done. So people doesn't need to visit page and able to register play online via Inno Setup.
Create a new page in installer with embedded browser in it.
I recommend to use this component: https://code.google.com/p/inno-web-browser/
Usage is really simple: https://code.google.com/p/inno-web-browser/source/browse/trunk/Example.iss
When user advances to your (newly created) page, navigate to your website (which should be running somewhere on server).
There's no native support for including a web page to Inno Setup installer. Neither I'm aware of any 3rd party extension that would support it.
Instead, you can code a custom installer page using the CreateInputQueryPage function to query user registration details and send them to your web site.
A simple example:
[Code]
var
UserPage: TInputQueryWizardPage;
procedure InitializeWizard;
begin
UserPage := CreateInputQueryPage(wpWelcome,
'Registration', 'Who are you?',
'Please specify your name and username tor register, then click Next.');
UserPage.Add('Name:', False);
UserPage.Add('User name:', False);
end;
function NextButtonClick(CurPageID: Integer): Boolean;
begin
Result := True;
if CurPageID = UserPage.ID then
begin
if (UserPage.Values[0] = '') or (UserPage.Values[1] = '') then
begin
MsgBox('You must enter your name and username.', mbError, MB_OK);
Result := False;
end;
end;
end;
procedure CurStepChanged(CurStep: TSetupStep);
var
WinHttpReq: Variant;
RegisterUrl: string;
begin
if CurStep = ssDone then
begin
try
RegisterUrl :=
'https://www.example.com/register.php?' +
Format('name=%s&username=%s', [UserPage.Values[0], UserPage.Values[1]])
Log('Sending registration request: ' + RegisterUrl);
WinHttpReq := CreateOleObject('WinHttp.WinHttpRequest.5.1');
WinHttpReq.Open('GET', RegisterUrl, False);
WinHttpReq.Send('');
Log('Registration report send result: ' +
IntToStr(WinHttpReq.Status) + ' ' + WinHttpReq.StatusText);
except
Log('Error sending registration report: ' + GetExceptionMessage);
end;
end;
end;
(Note that this lacks URL-encoding of the data).
Or simply open the registration form at the end of the installation in a web browser.
[Run]
Filename: "https://www.example.com/register.php"; \
Description: "&Open registration form"; \
Flags: shellexec runasoriginaluser postinstall

Resources