add shortcut to my program when right click - windows

Im not sure what the exact term should i called. I want to add shortcut to my C# program when i right click in windows.
From my findings, it got something to do with configure the "regedit". I have this example, but it was made for IE. can anyone point me to any references that can solve my problems?
references:
http://blog.voidnish.com/?p=17
http://www.codeguru.com/cpp/misc/misc/internetexplorer/article.php/c11007/
thank you very much.
UPDATED today..
Based on response from Factor Mystic, i add this code to the original. I have 2 solutions. One, It was created in registry HKEY_ CLASSES_ ROOT, but i cannot see the result when i right click the doc files.
private const string ProgName = "Software\\Classes\\Word.Document\\shell";
private const string MenuName = "Software\\Classes\\Word.Document\\shell\\NewTesting";
public const string Command =Software\\Classes\\Word.Document\\shell\\NewTesting\\command";
private void Form1_Load(object sender, EventArgs e)
{
txtProgram.Text = "Word.Document.8";
txtName.Text = "Testing";
txtPath.Text = "C:\\temp\\encriptTest.exe";
check();
addItem()
}
public void check()
{
RegistryKey regmenu = null;
RegistryKey regcmd = null;
try
{
//this.CheckSecurity();
regmenu = Registry.ClassesRoot.OpenSubKey(MenuName, false);
}
catch (ArgumentException ex)
{
// RegistryPermissionAccess.AllAccess can not be used as a parameter for GetPathList.
MessageBox.Show(this, "An ArgumentException occured as a result of using AllAccess. "
+ "AllAccess cannot be used as a parameter in GetPathList because it represents more than one "
+ "type of registry variable access : \n" + ex);
}
catch (SecurityException ex)
{
// RegistryPermissionAccess.AllAccess can not be used as a parameter for GetPathList.
MessageBox.Show(this, "An ArgumentException occured as a result of using AllAccess. " + ex);
this.btnAddMenu.Enabled = false;
//this.btnRemoveMenu.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
finally
{
if (regmenu != null)
regmenu.Close();
if (regcmd != null)
regcmd.Close();
}
}
private void CheckSecurity()
{
//check registry permissions
RegistryPermission regPerm;
regPerm = new RegistryPermission(RegistryPermissionAccess.Write, "HKEY_CLASSES_ROOT\\" + ProgName);
regPerm.AddPathList(RegistryPermissionAccess.Write, "HKEY_CLASSES_ROOT\\" + MenuName);
regPerm.AddPathList(RegistryPermissionAccess.Write, "HKEY_CLASSES_ROOT\\" + Command);
regPerm.Demand();
}
private void addItem()
{
RegistryKey regmenu = null;
RegistryKey regcmd = null;
RegistryKey regprog = null;
try
{
regprog = Registry.ClassesRoot.CreateSubKey(ProgName);
if (regmenu != null)
regmenu.SetValue("", this.txtProgram.Text);
regmenu = Registry.ClassesRoot.CreateSubKey(MenuName);
if (regmenu != null)
regmenu.SetValue("", this.txtName.Text);
regcmd = Registry.ClassesRoot.CreateSubKey(Command);
if (regcmd != null)
regcmd.SetValue("", this.txtPath.Text);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString());
}
finally
{
if (regprog != null)
regprog.Close();
if (regmenu != null)
regmenu.Close();
if (regcmd != null)
regcmd.Close();
}
}
Second, create in HKEY_ LOCAL_ MACHINE.
private bool Add_Item(string Extension,string MenuName, string MenuDescription, string MenuCommand)
{
//receive .doc,OpenTest,Open with Opentest,path: C:\\temp\\encriptTest.exe %1
bool ret = false;
RegistryKey rkey = //receive .doc extension (word.Document.8)
Registry.ClassesRoot.OpenSubKey(Extension); //set HKEY_LOCAL_MACHINE\software\classes\word.Document.8
if (rkey != null)
{
string extstring = rkey.GetValue("").ToString();
rkey.Close();
if (extstring != null)
{
if (extstring.Length > 0)
{
rkey = Registry.ClassesRoot.OpenSubKey(extstring, true);
if (rkey != null) //with extension file receive OpenTest as shell
{
string strkey = "shell\\" + MenuName + "\\command"; //..\shell\OpenTest\command
RegistryKey subky = rkey.CreateSubKey(strkey);
if (subky != null)
{
subky.SetValue("", MenuCommand); // path: C:\\temp\\encriptTest.exe %1
subky.Close();
subky = rkey.OpenSubKey("shell\\" + MenuName, true); //..\shell\OpenTest
if (subky != null)
{
subky.SetValue("", MenuDescription); // name displayed: Open with &OpenTest
subky.Close();
}
ret = true;
}
rkey.Close();
}
}
}
}
return ret;
}
}
My concerned, which Main Key should i use?

I believe you want to add items to the Explorer context menu.
Here is a nice article on CodeProject that shows you how to do it:
http://www.codeproject.com/KB/cs/appendmenu.aspx (basically it's just adding the appropriate keys to the windows registry)

You're going to want to determine the file type (ProgID) of .doc files. You can find this in HKEY_CURRENT_USER\Software\Classes\.doc (it is the default value).
Then add the key HKEY_CURRENT_USER\Software\Classes\<ProgID>\shell\NewMenuOption\command, where the default value is the path to your program.
You can do all this with Registry.SetValue and GetValue.
Check out this msdn page to get started.
Edit: Additional info, the difference between hive keys:
HKEY_LOCAL_MACHINE\Software\Classes and HKEY_CURRENT_USER\Software\Classes are similar, but HKLM is for system defaults/all user settings, and HKCU is for per user settings. Per user settings don't require elevated privileges, so you can write your context menu keys as a regular user with no pain.
HKEY_CLASSES_ROOT is a view combining HKEY_LOCAL_MACHINE\Software\Classes and HKEY_CURRENT_USER\Software\Classes, with writes directed to HKLM. This is a shortcut to writing system default values, and many tutorials show this because it's slightly simpler, but unless you're installing the application for all users I don't recommend it.
Advanced registry info on MSDN

Thank you very much for the responses. Very2 apreciate Them..
As Per Conlcusion, 3 ways on solving my prob. in easy understadable approach:
Adding shortcut in 3 ways:
1. create directly in registry window:
http://www.codeguru.com/cpp/misc/misc/internetexplorer/article.php/c11007/
2. shortcut available only to folders.
http://www.codeproject.com/KB/cs/appendmenu.aspx
http://blog.voidnish.com/?p=17
3. shortcut available to all files and folders.
http://www.autoitscript.com/forum/index.php?showtopic=103265&view=findpost&p=731920

Related

How to update outlook Search folder result for a new search programmaticaly without changing the folder name

I created Outlook search folder using add-in express for a outlook plugin as below. it is based on this article.
is there similar way to update search folder name for a new result ?
private void adxOutlookEvents_AdvancedSearchComplete(object sender, object hostObj) {
Outlook.Search advancedSearch = null;
Outlook.Results advancedSearchResults = null;
Outlook.MailItem resultItem = null;
System.Text.StringBuilder strBuilder = null;
try {
advancedSearch = hostObj as Outlook.Search;
if (advancedSearch.Tag == advancedSearchTag) {
System.Diagnostics.Debug.WriteLine("!!! adxOutlookEvents_AdvancedSearchComplete");
advancedSearchResults = advancedSearch.Results;
if (advancedSearchResults.Count > 0) {
if (HostMajorVersion > 10) {
object folder = advancedSearch.GetType().InvokeMember("Save",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.InvokeMethod |
System.Reflection.BindingFlags.Public,
null, advancedSearch,
new object[] { advancedSearchTag });
}
} else {
System.Diagnostics.Debug.WriteLine("!!!" + "There are no items found.");
}
}
} catch (Exception ex) {
MessageBox.Show(ex.Message, "An exception is occured");
} finally {
if (resultItem != null) Marshal.ReleaseComObject(resultItem);
if (advancedSearchResults != null)
Marshal.ReleaseComObject(advancedSearchResults);
}
}
Application.AdvancedSearch returns Search object. You can call Search.Save passing the name (string) - it will return MAPIFolder object. You can modify the MAPIFolder.Name property at any time.

How to apply compatplaylist to HwCertTestCollection

For HLK testing automation I would like to apply the compatplaylist on my test list.
Generell automation instruction, but no info how to apply a playlist.
One option is to modify the master test list based on the compatplaylist - both are xml based (with the help of Export-HwCertTestCollectionToXml and import-hwcerttestcollectionfromxml),
But maybe somebody already has a solution or knows an offical support for it.
Try this:-
public static PlaylistManager ApplyPlaylist(Project projectname, string playlistpath)
{
PlaylistManager pl_manager = null;
try
{
pl_manager = new PlaylistManager(projectname);
if (pl_manager == null)
Console.WriteLine("Cannot make playlist manager for the project:- {0}", projectname.Name.ToString());
if(pl_manager.IsPlaylistLoaded() == true)
{
Console.WriteLine("Playlist loaded.. unloading ");
pl_manager.UnloadPlaylist();
if (pl_manager.IsPlaylistLoaded() == false)
Console.WriteLine("Unloaded successfully");
}
else
{
if (File.Exists(playlistpath))
{
pl_manager.LoadPlaylist(playlistpath);
if (pl_manager.IsPlaylistLoaded() == false)
Console.WriteLine("Error in applying playlist:- {0}", playlistpath);
else
Console.WriteLine("Loaded playlist:- {0}", playlistpath);
}
else
{
Console.WriteLine("ERROR!Playlist file {0} not found!", playlistpath);
return pl_manager;
}
}
}
catch(Exception e)
{
Console.WriteLine("Exception:-{0}", e.ToString());
}
return pl_manager;
}

how to calculate the file size in C#

In my asp mvc 3 application, I have an action which allows the user to download a given file.
Here is the code :
public FilePathResult DownloadFile(string fileName)
{
try
{
string uploadsDocumentPath = System.Configuration.ConfigurationManager.AppSettings["uploadsDocumentPath"].ToString();
string ext = Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); // henter info fra windows registry
if (regKey != null && regKey.GetValue("Content Type") != null)
{
mimeType = regKey.GetValue("Content Type").ToString();
}
return File(uploadsDocumentPath + fileName, mimeType, fileName);
}
catch (Exception)
{
throw;
}
}
I want to be able to allow only files with size less than 150MB to be downloaded. But I can't find how to calculate this type of file's size.
Any ideas ?
I guess this should work:
FileInfo file = new FileInfo(uploadsDocumentPath + fileName);
if(file.Length > 157286400)
{
// Return error here.
}

BlackBerry - Downloaded images are corrupted on wifi with HttpConnection

In my app I need to download several images from a server. I use this code to get a byte array :
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
The url are formed with the suffix ";deviceSide=false;ConnectionType=MDS - public" (without spaces) and it is working perfectly well.
The problem is that with phones that do not have a sim card, we can't connect to the internet via the MDS server. So we changed to use the connection factory and let BB choose whatever he wants :
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
The connection works because it select the good prefix (interface=wifi in our case), but this create another problem.
Some images are not well downloaded, some of them (not the sames at each try) are corrupted, but only when the phone use a wifi connection to get these images.
How can I avoid this problem ? What method to get a connection do I have to use ? Is it possible to check if the user have a sim card in orderto use MDS - public ?
Here is an example of a corrupted image :
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
try this:
public static String buildURL(String url) {
String connParams = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connParams = ";interface=wifi"; //Connected to a WiFi access point.
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
//
if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
connParams = ";deviceside=false;ConnectionType=mds-public";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
ServiceRecord record = getWAP2ServiceRecord();
//
if (record != null) {
connParams = ";deviceside=true;ConnectionUID=" + record.getUid();
} else {
connParams = ";deviceside=true";
}
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connParams = ";deviceside=false";
}
}
Log.d("connection param"+url+connParams);
//
return url+connParams;
}
private static ServiceRecord getWAP2ServiceRecord() {
String cid;
String uid;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
//
for (int i = records.length -1; i >= 0; i--) {
cid = records[i].getCid().toLowerCase();
uid = records[i].getUid().toLowerCase();
//
if (cid.indexOf("wptcp") != -1
&& records[i].getUid().toLowerCase().indexOf("wap2") !=-1
&& uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
//
return null;
}
What happens when you append interface=wifi? Can you run the network diagnostic tool attached to below kb article and run all tests with SIM removed
http://supportforums.blackberry.com/t5/Java-Development/What-Is-Network-API-alternative-for-legacy-OS/ta-p/614822
Please also note that when download large files over BES/MDS there are limits imposed by MDS. Please ensure you review the below kb article
http://supportforums.blackberry.com/t5/Java-Development/Download-large-files-using-the-BlackBerry-Mobile-Data-System/ta-p/44585
You can check to see if coverage is sufficient for BIS_B (MDS public) but that won't help you if you are trying to support SIM-less users. I wonder if the problem is in an incomparability between the connection on Wi-Fi and IOUtilities.streamToBytes(). Try coding as recommended in the API documents.

MVC 3 The process cannot access the file because it is being used by another process

I upload a file in my MVC 3 project.
[HttpPost]
public ActionResult MyUpload(HttpPostedFileBase file)
{
string filePath = string.Empty;
string path = "C:\\";
string filePath = string.Empty;
try
{
if (file != null && file.ContentLength > 0)
{
filePath = path + file.FileName;
file.SaveAs(filePath);
file.InputStream.Dispose();
GC.Collect();
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
}
catch (Exception e)
{
if (file.InputStream != null)
file.InputStream.Dispose();
GC.Collect();
if (!string.IsNullOrEmpty(filePath))
{
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath); //here is the error
}
}
}
in that code, if an exception occured after I saved the file I can't delete it (also I cann't upload it again) because I get the error
The process cannot access the file
'[filePath]' because it is being used by another process.
What's wrong with that code ?
edit
I had to change the file.InputStream.Dispose(); to
file.InputStream.Close();
file.InputStream.Dispose();
file.InputStream = null;
And, now it's working fine.
Instead of checking if the file.InputStream is not null inside the catch block, you should dispose it inside the finally block, like this:
if (file != null && file.ContentLength > 0)
{
try
{
filePath = path + file.FileName;
file.SaveAs(filePath);
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
catch (Exception e)
{
if (!string.IsNullOrEmpty(filePath))
{
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath); //here is the error
}
}
finally
{
file.InputStream.Close();
file.InputStream.Dispose();
GC.Collect();
}
}
By the way, the InputStream property is a read-only property. You can't set it to null.

Resources