Generating RDP file on the fly - remote-desktop

I want to create a web application similar to TS Web Access, where I can create rdp files on the fly for Remote Apps configured on the server. Any idea??

We had to do this exact thing.
private void InvokeRDPSign(String fileName, String certificateThumbPrint)
{
Process signingProcess = new Process();
signingProcess.StartInfo.FileName = #"rdpsign.exe";
String arguments = String.Format("/sha1 {0} {1}", certificateThumbPrint, fileName);
signingProcess.StartInfo.Arguments = arguments;
signingProcess.StartInfo.UseShellExecute = false;
signingProcess.StartInfo.RedirectStandardOutput = true;
signingProcess.StartInfo.WorkingDirectory = Environment.SystemDirectory;
signingProcess.Start();
String signingOutput = signingProcess.StandardOutput.ReadToEnd();
signingProcess.WaitForExit();
int exitCode = signingProcess.ExitCode;
//TODO: should we throw an error if the exitcode is not 0
}
Be aware that that the RDPSign.exe is different on each version of windows. You will find that an older version of the utility will ignore newer settings from the signature.

well Having looked at a 'rdp' file this is the contents:
screen mode id:i:2
desktopwidth:i:1280
desktopheight:i:768
session bpp:i:32
winposstr:s:2,3,1430,104,2230,704
compression:i:1
keyboardhook:i:2
displayconnectionbar:i:1
disable wallpaper:i:1
disable full window drag:i:1
allow desktop composition:i:0
allow font smoothing:i:0
disable menu anims:i:1
disable themes:i:0
disable cursor setting:i:0
bitmapcachepersistenable:i:1
full address:s: [YOUR IP]
audiomode:i:0
redirectprinters:i:1
redirectcomports:i:0
redirectsmartcards:i:1
redirectclipboard:i:1
redirectposdevices:i:0
autoreconnection enabled:i:1
authentication level:i:0
prompt for credentials:i:0
negotiate security layer:i:1
remoteapplicationmode:i:0
alternate shell:s:
shell working directory:s:
gatewayhostname:s:
gatewayusagemethod:i:4
gatewaycredentialssource:i:4
gatewayprofileusagemethod:i:0
promptcredentialonce:i:1
drivestoredirect:s:
Just create that as a string, seems straightforward.
ps I have no idea what the 'winposstr' parameter is...

Related

Create persistent Sqlite db in Windows phone 8

I am trying my hands on Windows phone 8 applications and I am stuck into a weird situation here. I am using sqlite in order to create sqlite db and add values into the database. I am able to create the database and add the values in the database successfully but I am having a weird situation here.
Everytime I close the emulator and start the project again the database gets created again which should not be happening because I created the db the very first time I run the application.
Does anybody know why, and how I can prevent it from recreating the database each time?
public string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "aa.sqlite"));
private SQLiteConnection dtCon;
public MainPage()
{
InitializeComponent();
CreateDatabase();
dtCon = new SQLiteConnection(DB_PATH);
var tp = dtCon.Query<Contacts>("select * from contacts").ToList();
}
private async void CreateDatabase()
{
bool isDatabaseExisting = false;
//Checking if database already exists
try
{
Windows.Storage.StorageFile storagefile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("aa.sqlite");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
//if not exists then creating database
if (!isDatabaseExisting)
{
String str = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "sqlite.db");
AddDataToDB(DB_PATH);
}
}
private void AddDataToDB(string str)
{
// Create the database connection.
dtCon = new SQLiteConnection(str);
// Create the table Task, if it doesn't exist.
dtCon.CreateTable<Contacts>();
Contacts oContacts = new Contacts();
oContacts.Name = "dfgdf";
oContacts.Detail = "asdfsf";
dtCon.Insert(oContacts);
}
I'm pretty sure when you close your emulator and restart, you're basically just uninstalling the application. Which is why your files or not there anymore -- as it looks like you're storing your data in isolated storage. I do not know if there is anyway around this.
You can buy a very cheap Windows 8/8.1 Phone and the files will persist until you manually uninstall the test application.
As #Chubosaurus says, closing and re-opening the emulator will remove all the apps. You can generally keep it running as long as you want and keep re-deploying your app to the emulator (although obviously rebooting the host PC will kill it).
You can save and restore the data from your emulator image via the ISETool command. See more here
Try adding Console.WriteLine("True"); and Console.WriteLine("False"); into the expected places after checking isDatabaseExisting to see/understand what the code path really is.

WPF Click-Once deployment promoting from stage to production

I've a WPF Application that actually uses a Web server for downloading the app and execute it on the client... I've also created a staging enviorment for that application when I put the release as soon as new features are added / bug fixed.
I've not found a reasonable way of promoting from staging to production since the app.config is hashed... so I can't change my pointments (DB/Services) editing it...
My actual way is publishing for staging, increasing of 1 the publish version and publishing for production...but this is quite frustrating.... since I've to do twice the work...any sugeestion?
Thanks
Our team encountered the same situation a year ago. We've solved the situation by following this steps:
Determine the latest ClickOnce application version;
Removing the *.deploy extensions;
Making the necessary *.config file changes;
Updating the manifest file (*.manifest) by using 'Mage.exe' and your certificate (see also: MSDN);
Update the deployment manifest (*.application) in the application version directory and in the root directory, again by using 'Mage.exe';
Adding back the *.deploy extensions.
Hereby a short code sample for calling Mage, really not that complicated though.
// Compose the arguments to start the Mage tool.
string arguments = string.Format(
#"-update ""{0}"" -appmanifest ""{1}"" -certfile ""{2}""",
deploymentManifestFile.FullName,
applicationManifestFile.FullName,
_certificateFile);
// Add password to the list of arguments if necessary.
arguments += !string.IsNullOrEmpty(_certificateFilePassword) ? string.Format(" -pwd {0}", _certificateFilePassword) : null;
// Start the Mage process and wait it out.
ProcessStartInfo startInfo = new ProcessStartInfo(_mageToolPath, arguments);
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
Process mageProcess = Process.Start(startInfo);
mageProcess.WaitForExit();
// Show all output of the Mage tool to the current console.
string output = mageProcess.StandardOutput.ReadToEnd();
// Determine the update of the manifest was a success.
bool isSuccesfullyConfigured = output.ToLower().Contains("successfully signed");

How to disable file in use check in WPF OpenFileDialog?

My WPF app is using the Microsoft.Win32.OpenFileDialog to select a SQL Server 2008 database to open.
It works OK but for one issue: When the database selected in the dialog was previously opened at some time since last boot, the file seems to be held open by SQL server in the background (even when it is not opened by my app and my app has been restarted). This causes a "file is used by another application" warning when OK is clicked in the OpenFileDialog and i can not use the dialog to open that particular database until the computer is rebooted. It seems the OpenFileDialog tries to open the file selected and doing that discovers that it is already opened by another app (SQL Server). How do i disable the OpenFileDialog from trying to open the selected file and just return the filename of the selected file without any checks?
My code looks like this:
public void OpenDatabase() {
// Let user select database to open from file browser dialog
// Configure open file dialog box
var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = ""; // Default file name
dlg.DefaultExt = ".mdf"; // Default file extension
dlg.Filter = "Databases (.mdf)|*.mdf|All Files|*.*"; // Filter files by extension
dlg.CheckFileExists = false;
dlg.CheckPathExists = false;
// Show open file dialog box
bool? result = dlg.ShowDialog(); // Gives file in use warning second time!
// Process open file dialog box results
if (result == true) {
// Open document
string filename = dlg.FileName;
TryOpenDatabase(filename);
}
}
The underlying option is OFN_NOVALIDATE for early Windows versions, FOS_NOVALIDATE for the Vista dialog you get on later versions of Windows and .NET. The description from MSDN:
Do not check for situations that would prevent an application from opening the selected file, such as sharing violations or access denied errors.
Which is what you see happening now, the dialog sees a sharing violation on the database file. This option is in fact exposed on the OpenFileDialog wrapper class, add this line of code to fix your problem:
dlg.ValidateNames = false;
The MSDN forum has a post about this
It is in the OpenFileDialog API, you can turn that off using
ValidateNames = false
on the Dialog.

Is it possible to launch a Silverlight 4 OOB application from a web page? [duplicate]

This question already has an answer here:
Launch Silverlight Out-of-Browser from browser post-installation
(1 answer)
Closed 2 years ago.
I'm planning to build a download manager application and would like to be able to launch the application when a user clicks a button the site. The application would obviously already need to be installed on the client machine.
There are a few reasons why this needs to be written using Silverlight, but they're not really relevant to the question. I only mention it so that people don't suggest that I use another technology.
Doing a bit of a mash up from two other posts [1] and [2].
But of course this will only work for Windows not Mac. There you will have to fallback to the #michael-s-scherotter style solution.
private void Button_Click(object sender, RoutedEventArgs e)
{
if (Application.Current.HasElevatedPermissions && System.Windows.Interop.ComAutomationFactory.IsAvailable)
{
string run = "\""%ProgramFiles%\\Microsoft Silverlight\\sllauncher.exe"\" /emulate:"Silverface.xap" /origin:\"http://www.silverlight.net/content/samples/apps/facebookclient/ClientBin/Silverface.xap\" /overwrite";
dynamic cmd = ComAutomationFactory.CreateObject("WScript.Shell");
cmd.Run(run, 1, true);
}
}
Yes. Here is an example:
http://www.silverlight.net/content/samples/apps/facebookclient/sfcquickinstall.aspx
I found a trick that launches the installed silverlight OOB from the silverlight app in-browser. Both applications should be singed and have the elevated trust.
When a user installs the silverlight OOB App first time, retrive the path and argument values from the shortcut file of the OOB app on desktop. (ref: How I can use Shell32.dll in Silverlight OOB) If you know the the path and argument values, you can launch the OOB app using Com Object.
Send the retrive the path and argument values to the silverlight App in-browser. (ref: http://msdn.microsoft.com/en-us/library/dd833063(v=vs.95).aspx)
Store the path and argument values in a cookie.
Now, the silverlight app in-browser is able to launch the silverlight OOB using the path and argument values in the cookie.
using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
{
shell.Run(launchPath);
}
I hope this trick is useful to you :)
It is possible if you agree to install the app each time the user clicks on it.
You also should set the app to require elevated trust in its OOB settings.
Just uninstall the app on startup (for example, in main window constructor):
if (Application.Current.HasElevatedPermissions && Application.Current.InstallState == InstallState.Installed)
{
string launcherPath = string.Empty;
using (dynamic shell = AutomationFactory.CreateObject("Shell.Application"))
{
string launcher64 = #"C:\Program Files (x86)\Microsoft Silverlight";
string launcher32 = #"C:\Program Files\Microsoft Silverlight";
dynamic folder64 = shell.NameSpace(launcher64);
if (folder64 != null)
{
launcherPath = launcher64;
}
else
{
dynamic folder32 = shell.NameSpace(launcher32);
if (folder32 != null)
{
launcherPath = launcher32;
}
}
}
using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
{
var origin = Application.Current.Host.Source.OriginalString;
var launchCmd = string.Format(#"""{0}\sllauncher.exe"" /uninstall /origin:""{1}""", launcherPath, origin);
shell.Run(launchCmd);
}
}
(the code for uninstall was taken from this post: http://www.wintellect.com/blogs/sloscialo/programmatically-uninstalling-silverlight-out-of-browser-application)

Is it possible to access the Mac OS X pasteboard when logged in via SSH?

We have the following snippet.
OSStatus createErr = PasteboardCreate(kPasteboardClipboard, &m_pboard);
if (createErr != noErr) {
LOG((CLOG_DEBUG "failed to create clipboard reference: error %i" createErr));
}
This compiles fine, however, it fails to run when called from SSH. This is because there is no pasteboard available in the SSH terminal. However, the idea here is to share clipboards between computers.
When run from desktop terminal, this works just fine. But when run from SSH, PasteboardCreate returns -4960 (aka, coreFoundationUnknownErr). I assume that the only way around this issue is to run the application from within the same environment as the pasteboard, but is this possible?
Synergy+ issue 67
Accessing the pasteboard directly looks to be a no-go. First, launchd won't register the processes1 with the pasteboard server's mach port. You'd first need find a way to get the pasteboard server's mach port (mach_port_names?). Also, direct communication between user sessions is prohibited2, and other communication is limited. I'm not sure if your program will have the rights to connect to the pasteboard server.
Here's a first shot at an illustrative example on using Apple events to get & set the clipboard as a string. Error handling is minimal to nonexistent (I'm not certain how I feel about require_noerr). If you're going to get/set clipboard data multiple times during a run, you can save the Apple events and, when copying to the clipboard, use AECreateDesc & AEPutParamDesc or (maybe) AEBuildParameters. AEVTBuilder might be of use.
NSString* paste() {
NSString *content;
AppleEvent paste, reply = { typeNull, 0L };
AEBuildError buildError = { typeNull, 0L };
AEDesc clipDesc = { typeNull, 0L };
OSErr err;
err = AEBuildAppleEvent(kAEJons, kAEGetClipboard,
typeApplicationBundleID, "com.apple.finder", strlen("com.apple.finder"),
kAutoGenerateReturnID, kAnyTransactionID,
&paste, &buildError,
""
);
require_noerr(err, paste_end);
err = AESendMessage(&paste, &reply, kAEWaitReply, kAEDefaultTimeout);
err = AEGetParamDesc(&reply, keyDirectObject, typeUTF8Text, &clipDesc);
require_noerr(err, pastErr_getReply);
Size dataSize = AEGetDescDataSize(&clipDesc);
char* clipData = malloc(dataSize);
if (clipData) {
err = AEGetDescData(&clipDesc, clipData, dataSize);
if (noErr == err) {
content = [NSString stringWithCString:clipData encoding:NSUTF8StringEncoding];
} else {}
free(clipData);
}
AEDisposeDesc(&clipDesc);
pastErr_getReply:
AEDisposeDesc(&reply);
pasteErr_sending:
AEDisposeDesc(&paste);
paste_end:
return content;
}
OSStatus copy(NSString* clip) {
AppleEvent copy, reply = { typeNull, 0L };
AEBuildError buildError = { typeNull, 0L };
OSErr err = AEBuildAppleEvent(kAEJons, kAESetClipboard,
typeApplicationBundleID, "com.apple.finder", strlen("com.apple.finder"),
kAutoGenerateReturnID, kAnyTransactionID,
&copy, &buildError,
"'----':utf8(#)",
AEPARAMSTR([clip UTF8String])
/*
"'----':obj {form: enum(prop), want: type(#), seld: type(#), from: null()}"
"data:utf8(#)",
AEPARAM(typeUTF8Text),
AEPARAM(pClipboard),
AEPARAMSTR([clip UTF8String])
*/
);
if (aeBuildSyntaxNoErr != buildError.fError) {
return err;
}
AESendMessage(&copy, &reply, kAENoReply, kAEDefaultTimeout);
AEDisposeDesc(&reply);
AEDisposeDesc(&copy);
return noErr;
}
I'm leaving the Core Foundation approach above, but you'll probably want to use NSAppleEventDescriptor to extract the clipboard contents from the Apple Event reply.
err = AESendMessage(&paste, &reply, kAEWaitReply, kAEDefaultTimeout);
require_noerr(err, pasteErr_sending);
// nsReply takes ownership of reply
NSAppleEventDescriptor *nsReply = [[NSAppleEventDescriptor alloc] initWithAEDescNoCopy:&reply];
content = [[nsReply descriptorAtIndex:1] stringValue];
[nsReply release];
pasteErr_sending:
AEDisposeDesc(&paste);
paste_end:
return content;
}
An NSAppleEventDescriptor is also easier to examine in a debugger than an AEDesc. To examine replies, you can also to set the AEDebugReceives environment variable when using osascript or Script Editor.app:
AEDebugReceives=1 osascript -e 'tell application "Finder" to get the clipboard'
References:
"Configuring User Sessions"
"Communicating Across Login Sessions"
Mach Kernel Interface, especially:
mach_msg_header
mach_msg
CFMessagePort Reference (mach port wrapper):
CFMessagePortCreateRemote
CFMessagePortSendRequest
Apple Events Programming Guide
Apple Event Manager Reference
AEBuild*, AEPrint* and Friends
AEBuildAppleEvent on CocoaDev
Mac OS X Debugging Magic (for AEDebugSends and other AEDebug* environment variables)
I tried doing it in AppleScript, and it worked (even when invoked via SSH). My script is as follows:
#!/usr/bin/osascript
on run
tell application "Finder"
display dialog (get the clipboard)
end tell
end run
This definitely isn't an ideal solution, but perhaps if you worked out how AppleScript does it then it'd help you implement it yourself.
Take a look at pbpaste (getting the contents of the clipboard) and pbcopy (copying contents TO the clipboard). Works fine, also over SSH. :)
On Mac OS X Snow Leopard:
(source: hillrippers.ch)
On Ubuntu 9.04:
(source: hillrippers.ch)
You can access the pasteboard with PasteboardCreate via SSH on SnowLeopard but not on Leopard or Tiger.
You probably don't want to use pbcopy and pbpaste for a full pasteboard sync since those only deal with plain text, RTF, and EPS. If, for example, you copy an image and then try to write it out with pbpaste, you'll get no output.
Assuming you have an app running in the user's session on both computers, you could serialize the pasteboard data out to a file, transfer it over SSH, read it from your app on the remote side, and then put the pasteboard data on the remote pasteboard. However, getting the pasteboard serialization right may be tricky and I'm not sure how portable pasteboard data is between OSes and architectures.

Resources