How do I forward request to another proxy server using TIdHTTPProxyServer (proxy chain) - delphi

currently I want to make my indy proxy server forward the request to another proxy server. I have found this link and made a try by myself. But my code does not work without any error message as if I had made no change. My code is as below in C++ XE2.
void __fastcall TForm3::MyProxyHTTPBeforeCommand(TIdHTTPProxyServerContext *AContext)
{
TIdIOHandlerStack* tempIO = new TIdIOHandlerStack(NULL);
TIdConnectThroughHttpProxy* tempProxy = new TIdConnectThroughHttpProxy(NULL);
tempProxy->Enabled = true;
tempProxy->Host = "localhost";
tempProxy->Port = 8181 ;
tempIO->TransparentProxy = tempProxy;
AContext->OutboundClient->IOHandler = tempIO;
}

Finally I found I did something stupid. The correct code should be as follow...
void __fastcall TForm3::MyProxyHTTPBeforeCommand(TIdHTTPProxyServerContext *AContext)
{
TIdIOHandlerStack* tempIO = new TIdIOHandlerStack(AContext->OutboundClient);
TIdConnectThroughHttpProxy* tempProxy = new TIdConnectThroughHttpProxy(AContext->OutboundClient);
tempProxy->Enabled = true;
tempProxy->Host = "localhost";
tempProxy->Port = 8181 ;
tempIO->TransparentProxy = tempProxy;
AContext->OutboundClient->IOHandler = tempIO;

Related

ServiceNow integration with C# and dotnet core application

protected void Button1_Click(object sender, EventArgs e)
{
//Incident Service
IncidentService.ServiceNowSoapClient soapClient = new IncidentService.ServiceNowSoapClient();
soapClient.ClientCredentials.UserName.UserName = "username"; // username have SOAP role in SNow.
soapClient.ClientCredentials.UserName.Password = "Password1";
IncidentService.getRecords _getRecords = new IncidentService.getRecords();
IncidentService.getRecordsResponseGetRecordsResult[] getRecordsResponses = soapClient.getRecords(_getRecords);
_getRecords.active = true;
// Note: Please enable SOAP/REST services in your SNow dev instance table(s), Also,
// Go to system web services --> properties -> enable the 3rd option from the bottom.(This property sets the elementFormDefault attribute of the embedded XML schema to the value of unqualified)
//ServiceNowSoapClient client = new ServiceNowSoapClient();
//client.ClientCredentials.UserName.UserName = "username"; // username have SOAP role in SNow.
//client.ClientCredentials.UserName.Password = "Password1";
//insert newRecord = new insert();
//insertResponse insertResponse = new insertResponse();
//newRecord.first_name = "Jackson";
//newRecord.last_name = "Chris";
//newRecord.phone_number = "911-911-9999";
//newRecord.number = "CUS3048232";
try
{
//insertResponse = client.insert(newRecord);
//TextBox1.Text = insertResponse.sys_id;
getRecordsResponses = soapClient.getRecords(_getRecords);
for (int i = 0; i < getRecordsResponses.Length; i++)
{
TextBox2.Text = getRecordsResponses[i].short_description;
TextBox3.Text = getRecordsResponses[i].category;
}
}
catch (Exception ex)
{
TextBox1.Text = ex.Message;
}
//finally { client.Close(); }
}
How do you leverage ServiceNow data that reside in enterprise servicenow(CMDB,ITIL,various enterprise dbs, new dbs) dev,prod instances
to create End to End automated applications with C#, dotnetcore.
our goal is to Automate applications end to end with ServiceNow, dotnetcore, C#, docker containers, Ansible, Automic.
I know you probably don't need, maybe someone looking for the same finds this question.
I developed an library just for that.
https://emersonbottero.github.io/ServiceNow.Core/

Progress Bar is NULL after the execution of a thread

I have a form with a progress bar and a button that uploads an xml to a server.
While the button is pressed a new thread is created that creates a socket and then it sends the data to the server in chunks and in the meanwhile it updates the progress bar.
Now, when the upload button is pressed for a second time i get an access violation and in the debugger the address of the Progress Bar object is NULL.
I can't figure out why the Progress Bar is getting freed so if anyone has any idea i would be grateful.
P.S. The target OS is windows
P.S.2 If the same code runs on the main thread without the usage of a thread then i don't seem to have this issue and even if i skip the usage of the progress bar in overall in the thread it is set to null again after the first push of the upload button.
The thread Constructor:
__fastcall UploadRouteThread::UploadRouteThread(bool CreateSuspended) : TThread(CreateSuspended)
{
this->OnTerminate = OnTerminateHandler;
ioHandlerStack = new TIdIOHandlerStack();
tcpClient = new TIdTCPClient();
tcpClient->ReadTimeout = -1;
tcpClient->UseNagle = true;
tcpClient->IOHandler = ioHandlerStack;
tcpClient->OnConnected = OnConnectedHandler;
}
The OnTerminate handler:
void __fastcall UploadRouteThread::OnTerminateHandler(TObject *Sender)
{
TabbedwithNavigationForm->UploadButton->Text = "Upload";
TabbedwithNavigationForm->UploadButton->Enabled = false;
TabbedwithNavigationForm->ProgressBar->Visible = false;
tcpClient->DisconnectNotifyPeer();
ShowMessage("Data uploaded.");
delete ioHandlerStack;
delete tcpClient;
TabbedwithNavigationForm->OptionButton->Enabled = true;
TabbedwithNavigationForm->RetrieveRoutesButton->Enabled = true;
TabbedwithNavigationForm->TrackButton->Enabled = true;
TabbedwithNavigationForm->MediaButton->Enabled = true;
}
The Execute method:
void __fastcall UploadRouteThread::Execute()
{
FreeOnTerminate = true;
tcpClient->Connect();
}
Two supplumentary functions:
void __fastcall UploadRouteThread::SetHostPort(UnicodeString host, unsigned short port)
{
tcpClient->Host = host;
tcpClient->Port = port;
}
void __fastcall UploadRouteThread::SetXML(AnsiString xmlString)
{
this->xmlString = xmlString;
}
The OnConnect Handler:
void __fastcall UploadRouteThread::OnConnectedHandler(TObject *Sender)
{
NextPacketSize nps;
TIdBytes bytes;
int chunks;
int bytesLength;
nps.PacketID = BasicPacket::DATA_UPLOAD;
nps.size = xmlString.Length();
tcpClient->IOHandler->WriteDirect(RawToBytes(&nps, sizeof(nps)), sizeof(NextPacketSize));
bytes = RawToBytes(xmlString.c_str(), xmlString.Length());
bytesLength = bytes.get_length();
chunks = ceil(float(bytesLength) / 256.0);
int previousSizeSent(0);
for(int i = 1; i <= chunks; i++)
{
if(Terminated)
break;
int bytesToSend = 256;
TByteDynArray byteDynArray;
if((bytesToSend > bytesLength))
{
bytesToSend = bytesLength;
}
byteDynArray = bytes.CopyRange(previousSizeSent, bytesToSend);
tcpClient->IOHandler->WriteDirect(ToBytes(byteDynArray, byteDynArray.get_length(), 0),
byteDynArray.get_length());
sent = (float(i) / float(chunks)) * 100;
TThread::Synchronize(this, UpdateProgressBarInternal);
previousSizeSent += bytesToSend;
bytesLength -= bytesToSend;
}
}
And the Update method for the progress bar:
void __fastcall UploadRouteThread::UpdateProgressBarInternal()
{
if(!TabbedwithNavigationForm->ProgressBar->Visible)
{
TabbedwithNavigationForm->ProgressBar->Visible = true;
TabbedwithNavigationForm->ProgressBar->Max = 100;
}
TabbedwithNavigationForm->ProgressBar->Value = sent;
}
I don't see anything in this code that would cause the ProgressBar pointer to become NULL. So either you are corrupting memory, or something else in other code not shown here is the culprit. Either way, to troubleshoot this you can run your app in the IDE debugger and set a Data Breakpoint on the ProgressBar variable before you run your thread for the first time. If something changes the value of that pointer, the breakpoint will be hit, and you can look at the call stack to figure out what is happening.
With that said, your thread is not very well organized. And there is a much simpler way to handle the chunking - let Indy do it for you. It has an OnWork event that you can use for your ProgressBar updates.
Try something more like this:
__fastcall UploadRouteThread::UploadRouteThread(String host, TIdPort port, AnsiString xmlString)
: TThread(false)
{
this->FreeOnTerminate = true;
this->OnTerminate = OnTerminateHandler;
this->xmlString = xmlString;
tcpClient = new TIdTCPClient();
tcpClient->Host = host;
tcpClient->Port = port;
tcpClient->UseNagle = true;
tcpClient->OnWork = OnWorkHandler;
}
__fastcall UploadRouteThread::~UploadRouteThread()
{
delete tcpClient;
}
void __fastcall UploadRouteThread::OnTerminateHandler(TObject *Sender)
{
TabbedwithNavigationForm->UploadButton->Text = "Upload";
TabbedwithNavigationForm->UploadButton->Enabled = false;
TabbedwithNavigationForm->ProgressBar->Visible = false;
if (FatalException)
ShowMessage("Data not uploaded.");
else
ShowMessage("Data uploaded.");
TabbedwithNavigationForm->OptionButton->Enabled = true;
TabbedwithNavigationForm->RetrieveRoutesButton->Enabled = true;
TabbedwithNavigationForm->TrackButton->Enabled = true;
TabbedwithNavigationForm->MediaButton->Enabled = true;
}
void __fastcall UploadRouteThread::OnWorkHandler(TObject *ASender, TWorkMode AWorkMode, __int64 AWorkCount)
{
if (Terminated)
Sysutils::Abort();
sent = (double(AWorkCount) * 100.0) / xmlString.Length();
// consider using TThread::Queue() instead so that you don't block
// the upload waiting for the UI to be updated...
TThread::Synchronize(this, &UpdateProgressBarInternal);
}
void __fastcall UploadRouteThread::Execute()
{
tcpClient->Connect();
try
{
NextPacketSize nps;
nps.PacketID = BasicPacket::DATA_UPLOAD;
nps.size = xmlString.Length();
tcpClient->IOHandler->Write(RawToBytes(&nps, sizeof(nps)));
tcpClient->BeginWork(wmWrite, xmlString.Length());
tcpClient->IOHandler->Write(RawToBytes(xmlString.c_str(), xmlString.Length()));
tcpClient->EndWork(wmWrite);
/* alternatively:
TIdMemoryBufferStream *strm = new TIdMemoryBufferStream(xmlString.c_str(), xmlString.Length());
try
{
// optional
tcpClient->IOHandler->SendBufferSize = 256;
// this calls (Begin|End)Work() internally...
tcpClient->IOHandler->Write(strm, 0, false);
}
__finally
{
delete strm;
}
*/
}
__finally
{
tcpClient->Disconnect();
}
}
void __fastcall UploadRouteThread::UpdateProgressBarInternal()
{
if (!TabbedwithNavigationForm->ProgressBar->Visible)
{
TabbedwithNavigationForm->ProgressBar->Visible = true;
TabbedwithNavigationForm->ProgressBar->Max = 100;
}
TabbedwithNavigationForm->ProgressBar->Value = sent;
}

Write the Indy 10 of Delphi Codes's to C ++ Builder's Indy 10

I am new to learn C ++ Builder. Three days ago, I installed Embarcadero®. C++Builder® 2010. This language is very interesting for me to learn.
In Delphi, I generally write a simple proxy-server using TIdMappedPortTCP of Indy 9 and 10. I usually use its OnExecute and OnOutboundData events to modify data as it passes through the proxy.
Since I'm new in C ++ Builder, so I don't know how to convert my Delphi code to the exactly right C ++ Builder code.
I've tried and tried many ways, including reading several books, one of which is Borland C ++ Builder - The Complete Reference, by Herbert Schildt, as well as to increase knowledge. Unfortunately, in the book was not discussed at all very important things related to my condition. Also, I find references on google, but I've not found.
So, I ventured to ask for your help. I really need it.
Please help! Thank you very much.
The following is my Indy 10's Delphi code that I want to write to C ++ Builder.
......
procedure TForm.IdMappedPortTCP1Execute(AContext: TIdContext);
var
Mydata, NetData: string;
begin
if (Pos('HTTP',netstring(AContext)) <> 0) or (Pos('GET',netstring(AContext)) <> 0) then begin
NetData := netstring(AContext);
TIdMappedPortContext(AContext).OutboundClient.IOHandler.Write(AddHeader(netstring(AContext),'Connection: Keep-Alive'));
Sleep(1000);
Mydata := 'GET http://website.com/ HTTP/1.1'+#13#10+'Host: website.com'#13#10;
NetData := Mydata + Netdata;
TIdMappedPortContext(AContext).NetData := netbyte(Netdata);
TIdMappedPortContext(AContext).OutboundClient.IOHandler.Write(netbyte(Mydata + NetData));
end;
end;
......
A literal translation to C++Builder would look like this:
......
String __fastcall AddHeader(String S, String Header)
{
S = StringReplace(S, "\r\n\r\n", "\r\n" + Header + "\r\n\r\n", TReplaceFlags() << rfReplaceAll);
return S;
}
void __fastcall TForm::IdMappedPortTCP1Execute(TIdContext *AContext)
{
String Mydata, NetData;
if ((netstring(AContext).Pos("HTTP") != 0) || (netstring(AContext).Pos("GET") != 0))
{
NetData = netstring(AContext);
TIdMappedPortContext(AContext)->OutboundClient->IOHandler->Write(AddHeader(netstring(AContext), "Connection: Keep-Alive"));
Sleep(1000);
Mydata = "GET http://website.com/ HTTP/1.1\r\nHost: website.com\r\n";
NetData = Mydata + Netdata;
static_cast<TIdMappedPortContext*>(AContext)->NetData = netbyte(Netdata);
static_cast<TIdMappedPortContext*>(AContext)->OutboundClient->IOHandler->Write(netbyte(Mydata + NetData));
}
}
......
Here is a slightly condensed version:
......
String __fastcall AddHeader(String S, String Header)
{
return StringReplace(S, "\r\n\r\n", "\r\n" + Header + "\r\n\r\n", TReplaceFlags() << rfReplaceAll);
}
void __fastcall TForm::IdMappedPortTCP1Execute(TIdContext *AContext)
{
String NetData = netstring(AContext);
if ((NetData.Pos("HTTP") != 0) || (NetData.Pos("GET") != 0))
{
Sleep(1000);
String Mydata = "GET http://website.com/ HTTP/1.1\r\nHost: website.com\r\n" + AddHeader(NetData, "Connection: Keep-Alive");
static_cast<TIdMappedPortContext*>(AContext)->NetData = netbyte(Mydata);
}
}
......
But either way, this is definitely NOT a reliable way to implement a viable HTTP proxy in Indy. In fact, Indy 10 introduced a specific TIdHTTPProxyServer component for that very purpose. You should seriously consider using that instead of TIdMappedPortTCP. For example, the above can be done in TIdHTTPProxyServer like this:
class TIdHTTPProxyServerContextAccess : public TIdHTTPProxyServerContext
{
public:
void SetCommand(String Value) { FCommand = Value; }
void SetDocument(String Value) { FDocument = Value; }
void SetTarget(String Value) { FTarget = Value; }
};
void __fastcall TForm1.IdHTTPProxyServer1HTTPBeforeCommand(TIdHTTPProxyServerContext *AContext)
{
static_cast<TIdHTTPProxyServerContextAccess*>(AContext)->SetCommand("GET");
static_cast<TIdHTTPProxyServerContextAccess*>(AContext)->SetTarget ("http://website.com/");
static_cast<TIdHTTPProxyServerContextAccess*>(AContext)->SetDocument("/");
AContext->Headers->Values["Host"] = "website.com";
AContext->Headers->Values["Connection"] = "Keep-Alive";
/*
the original code was not changing the Host/Port where the
HTTP request was being sent to. But if you needed to,
you can do it like this...
static_cast<TIdTCPClient*>(AContext->OutboundClient)->Host = "website.com";
static_cast<TIdTCPClient*>(AContext->OutboundClient)->Port = 80;
*/
}
Update: the netstring() and netbyte() functions you linked to have syntax errors, and have unnecessary overhead (there is no need to involve MIME just to convert a String into a byte array and vice versa, Indy has functions specifically for that purpose). Here are the corrected versions:
String __fastcall netstring(TIdMappedPortContext* AContext)
{
return BytesToStringRaw(AContext->NetData);
}
TIdBytes __fastcall netbyte(String S)
{
return ToBytes(S, IndyTextEncoding_8Bit());
}
So, you could actually just eliminate the functions altogether:
void __fastcall TForm::IdMappedPortTCP1Execute(TIdContext *AContext)
{
TIdMappedPortContext *ctx = static_cast<TIdMappedPortContext*>(AContext)
String NetData = BytesToStringRaw(ctx->NetData);
if ((NetData.Pos("HTTP") != 0) || (NetData.Pos("GET") != 0))
{
Sleep(1000);
String Mydata = "GET http://website.com/ HTTP/1.1\r\nHost: website.com\r\n" + AddHeader(NetData, "Connection: Keep-Alive");
ctx->NetData = ToBytes(Mydata);
}
}

Enable Seamless mode using AxInterop.MSTSCLib

I have an application that use AxInterop.MSTSCLib activeX to create remote connection to another PC similar to the following application:
http://www.codeproject.com/Articles/43705/Remote-Desktop-using-C-NET
My question, is there an option that I can config to connect the PC in seamless mode?
I know this is over a year old but I am assuming this is what you want to do:
rdp.Server = "Server";
rdp.UserName = "Username";
rdp.Domain = "Domain";
IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
secured.ClearTextPassword = User.Password;
rdp.AdvancedSettings8.ConnectionBarShowMinimizeButton = false;
rdp.AdvancedSettings8.ConnectionBarShowPinButton = false;
rdp.AdvancedSettings8.ConnectionBarShowRestoreButton = false;
rdp.AdvancedSettings8.EnableWindowsKey = 0;
rdp.AdvancedSettings8.RedirectClipboard = true;
rdp.AdvancedSettings8.RedirectDrives = true;
rdp.AdvancedSettings8.RedirectPrinters = true;
rdp.AdvancedSettings8.SmartSizing = true;
rdp.SecuredSettings3.StartProgram = "LaunchApp Path";
rdp.Connect();
In addition follow what #Hans Passant suggested above..

Creating a process in ASP.NET MVC controller

I have a requirement to run an application through my MVC controller. To get the installation path I used following link (I used answer provided by Fredrik Mörk). It worked and I could able to run the exe through a process. The problem occurred when I deployed this solution on IIS where it did not create the process as it was creating in local dev environment. Can anybody tell me how to create a windows process through a solution which is hosted on IIS ?
private string GetPathForExe(string fileName)
{
private const string keyBase = #"SOFTWARE\Wow6432Node\MyApplication";
RegistryKey localMachine = Registry.LocalMachine;
RegistryKey fileKey = localMachine.OpenSubKey(string.Format(#"{0}\{1}", keyBase, fileName));
object result = null;
if (fileKey != null)
{
result = fileKey.GetValue("InstallPath");
}
fileKey.Close();
return (string)result;
}
public void StartMyApplication()
{
Process[] pname = Process.GetProcessesByName("MyApplication");
if (pname.Length == 0)
{
string appDirectory = GetPathForExe("MyApplication");
Directory.SetCurrentDirectory(appDirectory);
ProcessStartInfo procStartInfo = new ProcessStartInfo("MyApplication.exe");
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
}
}

Resources