Get file path from Visual Studio editor - c#

I'm developing a Visual Studio Package, written in C#.
How do I get the full path of the active editor programatically?

When working macros you can use
DTE.ActiveDocument.Path + DTE.ActiveDocument.Name
to get the full path. Likely this is the same in C# when making VS packages?

This is how you get the full path of the focused (active) document in Visual Studio:
DTE dte = (DTE)GetService(typeof(DTE));
string document = dte.ActiveDocument.FullName;

I had a similar problem when developing ASP.NET Web Forms custom server controls.
In order to obtain a reference to the DTE object and create a virtual path to the directory of the file being edited I used the following code inside my custom server control file:
[Bindable(true)]
[Category("Behavior")]
[DefaultValue("")]
[Editor(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor))]
public string Url
{
get
{
object urlObject = ViewState["Url"];
if (urlObject == null)
{
if (DesignMode)
{
// Get a reference to the Visual Studio IDE
EnvDTE.DTE dte = this.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
// Interface for accessing the web application in VS
IWebApplication webApplication = (IWebApplication)this.Site.GetService(typeof(IWebApplication));
// Path of document being edited (Web form in web application)
string activeDocumentPath = dte.ActiveDocument.Path;
// Physical path to the web application root
string projectPath = webApplication.RootProjectItem.PhysicalPath;
// Create virtal path
string relativePath = activeDocumentPath.Replace(projectPath, "~\\");
return relativePath.Replace('\\','/');
}
else
{
return String.Empty;
}
}
else
{
return (string)urlObject;
}
}
set
{
ViewState["Url"] = value;
}
}
This is useful quickly navigating to a file near the one being edited when using the UrlEditor

In VS 2010 and 2008, you right click the tab at the top and select "Copy Full Path" from the context menu. See my image below.

Related

Deploy addin project with ppt slide within solution and include it in deployed folder

I am trying to deploy my project having power point slide in solution exlorer. however after I build these it gives me an error as it does not find this ##.ppt file in bin debug. I used build action as content and copy to output directory as copy always but seems of no help. is there any other option for this
Below is my code where I am trying to copy shapes from ppt saved in solution explorer to current ppt now after i deploy since this ppt doesnt add with deployed files it cannot find ppt so it doesnt add shapes.
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
String programfilesPath = AppDomain.CurrentDomain.BaseDirectory;
//var filesPath = Directory.GetParent(Directory.GetParent(Directory.GetParent(programfilesPath).ToString()).ToString());
String fullPath = programfilesPath;
string pptname = "Moons.ppt";
String themePresentationPath = fullPath + pptname;
// PowerPoint.Application ppapp2 =
var temporaryPresentation = ppApp.Presentations.Open(themePresentationPath, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
int countlargest = ppslr.Shapes.Count;
string shapecount = harveyballs.SelectedItem.Label.ToString();
int count = Convert.ToInt32(shapecount);
ppslr.Shapes.SelectAll();
PowerPoint.ShapeRange ppShR = ppApp.ActiveWindow.Selection.ShapeRange;
ppShR[count + 1].Copy();
temporaryPresentation.Close();
PowerPoint.SlideRange ppslr2 = ppApp.ActiveWindow.Selection.SlideRange;
ppslr2.Shapes.Paste();
it does not find this ##.ppt file in bin debug
The debug folder is used as an output when current configuration is set to Debug. Are you sure that you have the Debug configuration set in Visual Studio?

Files that are upload does not show up in the Project solution(Mvc5)

I have implement the following code to upload a file. The file is upload to the location ("../App_Data/uploads") but it does not show up in the project. I have to include the file manually in the project. Why is the file not showing up?
public ActionResult ChangeSetting(SettingViewModel setting)
{
string userId = User.Identity.GetUserId();
ApplicationUser currentUser = this._appUserRepo.Find(e => e.Id.Equals(userId)).FirstOrDefault();
if (setting.PictureUrl != null)
{
if (setting.PictureUrl.ContentLength > 0)
{
string fileName = Path.GetFileName(setting.PictureUrl.FileName);
if (fileName != null)
{
string path = Path.Combine(Server.MapPath("../App_Data/uploads"), fileName);
setting.PictureUrl.SaveAs(path);
if (currentUser != null)
{
currentUser.PictureUrl = path;
currentUser.PictureSmalUrl = path;
currentUser.PictureBigUrl = path;
}
}
}
}
if (setting.FirstName != null)
{
if (currentUser != null) currentUser.FirstName = setting.FirstName;
}
_appUserRepo.Update(currentUser);
return RedirectToAction("index", "Admin");
}
Why is the file not showing up?
Because that's how Visual Studio projects work - only files that you manually include into the project are shown in the solution explorer. Files that get added dynamically to folders afterwards by eternal processes do not show up in Visual Studio (unless you manually include them and make them part of the solution). But that's probably not something you should be worried about. The files uploaded by users won't automagically appear in your Visual Studio project. The important thing is that they are present at the expected location and that your web application is capable of accessing them at runtime. Just open the physical location of the folder in Windows Explorer to confirm that your code is working as expected.

Update dynamic Web Reference via command line (wsdl tool)

I have a problem with updating dynamic Web Reference using WSDL.exe tool.
When I'm using "Update Web Reference" in VS, everything is working as expected.
Below is generated code (part of Reference.cs file):
public MyService() {
this.Url = global::ServerReference.Properties.Settings.Default.ServerReference_Reference_MyService;
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
I'm getting necessary information from application properties which are then stored in config file and therefore can be changed without rebuilding application.
However when I use following command:
.\tools\wsdl.exe /l:cs /n:ServerReference /o".\ServerReference\Web References\Reference\Reference.cs" http://localhost:52956/MyService/MyService.asmx
it is created with fixed URL address in Reference.cs file.
Does anybody know how I should change my command to achieve the same Reference.cs file as in Visual Studio?
I don't think you can generate the same code with wsdl.exe.
But if the main thing you want to achieve is generating code that takes the service address from app.config then you can use wsdl.exe with the "/appsettingurlkey" switch.
The code you'll get will be something like this:
public WebService1() {
string urlSetting = System.Configuration.ConfigurationManager.AppSettings["ConfigKeyForServiceUrl"];
if ((urlSetting != null)) {
this.Url = urlSetting;
}
else {
this.Url = "http://localhost:65304/WebService1.asmx";
}
}
Be aware that it reads from 'appSettings' not from 'applicationSettings' through the Settings class, so you'll have to modify your app.config. And it doesn't contain the 'UseDefaultCredentials' stuff either.

Not able to get Application startup path on click on setup.exe

I am publishing a Windows project and on click on form I am installing another setup to install.
I am not getting the current Application Startup Path on clickevent on button.
On debug and Release it is showing the right path but after publishing it is giving
C:\Users\username\AppData\Local\Apps\2.0 path
Already I have used :
Application.StartupPath
Application.Executablepath
Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location))
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase))
Path.Combine(Directory.GetCurrentDirectory())
But of no use it always show
C:\Users\username\AppData\Local\Apps\2.0 path
You are getting that path because it's the one used by ClickOnce. ClickOnce applications are installed under the profile of the user who installed them.
Edit :
Method 1:
Here's a way to get the path where your application was installed from (works only if your application was installed) (parts of this were written by #codeConcussion) :
// productName is name you assigned to your app in the
// Project properties -> Publish -> Publish Settings
public static string GetInstalledFromDir(string productName)
{
using (var key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Uninstall"))
{
if (key != null)
{
var appKey = key.GetSubKeyNames().FirstOrDefault(x => GetValue(key, x, "DisplayName") == productName);
return appKey == null ? null : GetValue(key, appKey, "UrlUpdateInfo");
}
}
return null;
}
private static string GetValue(RegistryKey key, string app, string value)
{
using (var subKey = key.OpenSubKey(app))
{
if (subKey == null || !subKey.GetValueNames().Contains(value))
{
return null;
}
return subKey.GetValue(value).ToString();
}
}
Here's how to use it :
Uri uri = new Uri(GetInstalledFromDir("ProductName"));
MessageBox.Show(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)));
Method 2 :
You can also try
System.Deployment.Application.ApplicationDeployment.CurrentDeployment.ActivationUri
But I think this one works only if your app was installed from the internet
try this:
Process.GetCurrentProcess().MainModule.FileName
BTW, is it ClickOnce deployment? If so then the directory you are getting looks about right.

read string from .resx file in C#

How to read the string from .resx file in c#? please send me guidelines . step by step
ResourceManager shouldn't be needed unless you're loading from an external resource.
For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:
Assuming a project namespace: UberSoft.WidgetPro
And your resx contains:
You can just use:
Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
This example is from the MSDN page on ResourceManager.GetString():
// Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());
// Retrieve the value of the string resource named "welcome".
// The resource manager will retrieve the value of the
// localized resource using the caller's current culture setting.
String str = rm.GetString("welcome");
Try this, works for me.. simple
Assume that your resource file name is "TestResource.resx", and you want to pass key dynamically then,
string resVal = TestResource.ResourceManager.GetString(dynamicKeyVal);
Add Namespace
using System.Resources;
Open .resx file and set "Access Modifier" to Public.
var <Variable Name> = Properties.Resources.<Resource Name>
Assuming the .resx file was added using Visual Studio under the project properties, there is an easier and less error prone way to access the string.
Expanding the .resx file in the Solution Explorer should show a .Designer.cs file.
When opened, the .Designer.cs file has a Properties namespace and an internal class. For this example assume the class is named Resources.
Accessing the string is then as easy as:
var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
var exampleXmlString = resourceManager.GetString("exampleXml");
Replace JoshCodes.Core.Testing.Unit with the project's default namespace.
Replace "exampleXml" with the name of your string resource.
Followed by #JeffH answer, I recommend to use typeof() than string assembly name.
var rm = new ResourceManager(typeof(YourAssembly.Properties.Resources));
string message = rm.GetString("NameOfKey", CultureInfo.CreateSpecificCulture("ja-JP"));
If for some reason you can't put your resources files in App_GlobalResources, then you can open resources files directly using ResXResourceReader or an XML Reader.
Here's sample code for using the ResXResourceReader:
public static string GetResourceString(string ResourceName, string strKey)
{
//Figure out the path to where your resource files are located.
//In this example, I'm figuring out the path to where a SharePoint feature directory is relative to a custom SharePoint layouts subdirectory.
string currentDirectory = Path.GetDirectoryName(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"]));
string featureDirectory = Path.GetFullPath(currentDirectory + "\\..\\..\\..\\FEATURES\\FEATURENAME\\Resources");
//Look for files containing the name
List<string> resourceFileNameList = new List<string>();
DirectoryInfo resourceDir = new DirectoryInfo(featureDirectory);
var resourceFiles = resourceDir.GetFiles();
foreach (FileInfo fi in resourceFiles)
{
if (fi.Name.Length > ResourceName.Length+1 && fi.Name.ToLower().Substring(0,ResourceName.Length + 1) == ResourceName.ToLower()+".")
{
resourceFileNameList.Add(fi.Name);
}
}
if (resourceFileNameList.Count <= 0)
{ return ""; }
//Get the current culture
string strCulture = CultureInfo.CurrentCulture.Name;
string[] cultureStrings = strCulture.Split('-');
string strLanguageString = cultureStrings[0];
string strResourceFileName="";
string strDefaultFileName = resourceFileNameList[0];
foreach (string resFileName in resourceFileNameList)
{
if (resFileName.ToLower() == ResourceName.ToLower() + ".resx")
{
strDefaultFileName = resFileName;
}
if (resFileName.ToLower() == ResourceName.ToLower() + "."+strCulture.ToLower() + ".resx")
{
strResourceFileName = resFileName;
break;
}
else if (resFileName.ToLower() == ResourceName.ToLower() + "." + strLanguageString.ToLower() + ".resx")
{
strResourceFileName = resFileName;
break;
}
}
if (strResourceFileName == "")
{
strResourceFileName = strDefaultFileName;
}
//Use resx resource reader to read the file in.
//https://msdn.microsoft.com/en-us/library/system.resources.resxresourcereader.aspx
ResXResourceReader rsxr = new ResXResourceReader(featureDirectory + "\\"+ strResourceFileName);
//IDictionaryEnumerator idenumerator = rsxr.GetEnumerator();
foreach (DictionaryEntry d in rsxr)
{
if (d.Key.ToString().ToLower() == strKey.ToLower())
{
return d.Value.ToString();
}
}
return "";
}
I added the .resx file via Visual Studio. This created a designer.cs file with properties to immediately return the value of any key I wanted. For example, this is some auto-generated code from the designer file.
/// <summary>
/// Looks up a localized string similar to When creating a Commissioning change request, you must select valid Assignees, a Type, a Component, and at least one (1) affected unit..
/// </summary>
public static string MyErrorMessage {
get {
return ResourceManager.GetString("MyErrorMessage", resourceCulture);
}
}
That way, I was able to simply do:
string message = Errors.MyErrorMessage;
Where Errors is the Errors.resx file created through Visual Studio and MyErrorMessage is the key.
Once you add a resource (Name: ResourceName and Value: ResourceValue) to the solution/assembly, you could simply use "Properties.Resources.ResourceName" to get the required resource.
I added my resource file to my project directly, and so I was able to access the strings inside just fine with the resx file name.
Example: in Resource1.resx, key "resourceKey" -> string "dataString".
To get the string "dataString", I just put Resource1.resourceKey.
There may be reasons not to do this that I don't know about, but it worked for me.
The easiest way to do this is:
Create an App_GlobalResources system folder and add a resource file to it e.g. Messages.resx
Create your entries in the resource file e.g. ErrorMsg = This is an error.
Then to access that entry: string errormsg = Resources.Messages.ErrorMsg
The Simplest Way to get value from resource file.
Add Resource file in the project.
Now get the string where you want to add like in my case it was text block(SilverLight).
No need to add any namespace also.Its working fine in my case
txtStatus.Text = Constants.RefractionUpdateMessage;
Constants is my resource file name in the project.
Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("param1",Assembly.GetExecutingAssembly());
String str = rm.GetString("param2");
param1 = "AssemblyName.ResourceFolderName.ResourceFileName"
param2 = name of the string to be retrieved from the resource file
This works for me.
say you have a strings.resx file with string ok in it. to read it
String varOk = My.Resources.strings.ok
ResourceFileName.ResourceManager.GetString(ResourceFileName.Name)
2.return Resource.ResponseMsgSuccess;

Categories