Suppose I have a project A and project B. I want to access config file of project A in project B then how I can achieve this?
Note: I'm trying to access custom section of the config file as below
var connectionManagerDataSection = ConfigurationManager.GetSection(ConnectionManagerDataSection.SectionName) as ConnectionManagerDataSection;
List<AddEndpoint> AddEndpoint = new List<AddEndpoint>();
if (connectionManagerDataSection != null)
{
foreach (MyConfigInstanceElement endpointElement in connectionManagerDataSection.ConnectionManagerEndpoints)
{
var endpoint = new AddEndpoint() { Name = endpointElement.Name, Code = endpointElement.Code };
AddEndpoint.Add(endpoint);
}
}
Related
I create a Servicebus-Namespace using AzureNative on Pulumi:
public void CreateNamespace(string namespaceName, SkuName skuname, SkuTier tier)
{
var namespace = new Namespace(namespaceName, new NamespaceArgs
{
Location = _resourceGroup.Location,
NamespaceName = namespaceName,
ResourceGroupName = _resourceGroup.Name,
Sku = new Pulumi.AzureNative.ServiceBus.Inputs.SBSkuArgs
{
Name = skuname,
Tier = tier
}
});
}
The Servicebus Namespace is created correctly. After creating the Servicebus-Namespace I need to retrieve the ConnectionString for this resource. Either for the automatically created RootManageSharedAccessKey or alternatively by creating a specific additional policy for that task.
Within the Azure Portal I can retrieve the Key by navigating through
Settings/Shared access policies/Policy/ and copying the Primary access key from there.
I did not find any property or function within the AzureNative.ServiceBus - Namespace that seem to lead to that key. Any way to retrieve that property?
I solved it by creating a new NamespaceRule and return ListNamespaceKeys-Properties:
var namespaceRule = new NamespaceAuthorizationRule(rulename, new NamespaceAuthorizationRuleArgs
{
AuthorizationRuleName = rulename,
NamespaceName = namespace.Name,
ResourceGroupName = _resourceGroup.Name,
Rights = new[]
{
AccessRights.Listen,
AccessRights.Send
}
});
var nameSpaceKeys = Output
.Tuple(namespace.Name, namespaceRule.Name)
.Apply(t => ListNamespaceKeys.InvokeAsync(new ListNamespaceKeysArgs
{
NamespaceName = t.Item1,
AuthorizationRuleName = t.Item2,
ResourceGroupName = _resourceGroup.GetResourceName()
}));
Now NamespaceKeys contains all the required Properties like PrimaryConnectionString etc.
In my asp.web api 2.0 project I have a Json file, where all the error codes are mapped. I want to read the json file in order to return response to the caller.
I am unable to read the same, however if I use console application following code works, any suggestion will be helpful.
Code that works in console application:
var assembly = Assembly.GetExecutingAssembly();
using (var stream = new StreamReader(assembly.GetManifestResourceStream("ConsoleApp24.Utilities.StatusCodes.json") ?? throw new InvalidOperationException()))
{
var status = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
Using above code provides assembly as null in web api project, hence I changed it to following:
var assembly = GetWebEntryAssembly();
using (var stream = new StreamReader(assembly.GetManifestResourceStream("PaymentAccount.Api.Resources.StatusCodes.json") ?? throw new InvalidOperationException()))
{
var status = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
private Assembly GetWebEntryAssembly()
{
if (System.Web.HttpContext.Current == null ||
System.Web.HttpContext.Current.ApplicationInstance == null)
{
return null;
}
var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();
while (type != null && type.Namespace == "ASP")
{
type = type.BaseType;
}
return type == null ? null : type.Assembly;
}
The exception I get is:
Operation is not valid due to the current state of the object.
With Server.MapPath it is easy for ASP.NET to find your files but the file still have to be inside of the application root folder, here is some official documentation on this function.
Just place file inside your root folder, and then use Server.MapPath this will allow your ASP.NET application to find your file in the Server file system.
string json = File.ReadAllText(Server.MapPath("~/files/myfile.json"));
You can try this :
public object Get()
{
string allText = System.IO.File.ReadAllText(#"c:\data.json");
object jsonObject = JsonConvert.DeserializeObject(allText);
return jsonObject;
}
this code returns json text
I have a new-style csproj project file that overrides IntermediateOutputPath. It looks like this:
<PropertyGroup>
<TargetFramework>netstandard1.6</TargetFramework>
<IntermediateOutputPath>new\path\to\obj</IntermediateOutputPath>
</PropertyGroup>
The problem is, my Visual Studio extension can't access IntermediateOutputPath property. Project.Properties seems to have much less stuff compared to old project format.
I've also tried project.ConfigurationManager.ActiveConfiguration.Properties with the similar success.
Is there any way to get this information from Visual Studio extension?
So I created a simple extension to print all the properties
private string GetPropertiesString(Properties properties)
{
StringBuilder test = new StringBuilder();
foreach (Property property in properties)
{
try
{
test.AppendLine(property.Name + ":=" + property.Value.ToString());
Console.WriteLine(property.Name + ":=" + property.Value.ToString());
}
catch (Exception ex)
{
var x = ex.Message;
}
}
return test.ToString();
}
private void MenuItemCallback(object sender, EventArgs e)
{
DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;
var sol = dte2.Solution;
var projs = sol.Projects;
foreach (var proj in sol)
{
var project = proj as Project;
var rows = project.ConfigurationManager.ConfigurationRowNames as IEnumerable<object>;
foreach (var row in rows)
{
var config = project.ConfigurationManager.ConfigurationRow(row.ToString()).Item(1) as Configuration;
string configs = GetPropertiesString(config.Properties);
}
}
}
And this gave below output
LanguageVersion:=
RunCodeAnalysis:=False
NoStdLib:=False
ErrorReport:=prompt
CodeAnalysisUseTypeNameInSuppression:=True
CodeAnalysisInputAssembly:=bin\Debug\WindowsFormsApp1.exe
CodeAnalysisDictionaries:=
GenerateSerializationAssemblies:=2
CodeAnalysisModuleSuppressionsFile:=GlobalSuppressions.cs
StartWorkingDirectory:=
Optimize:=False
DocumentationFile:=
StartPage:=
OutputPath:=bin\Debug\
TreatWarningsAsErrors:=False
EnableASPDebugging:=False
IncrementalBuild:=True
CodeAnalysisFailOnMissingRules:=False
CodeAnalysisLogFile:=bin\Debug\WindowsFormsApp1.exe.CodeAnalysisLog.xml
DefineConstants:=DEBUG;TRACE
UseVSHostingProcess:=True
StartProgram:=
DefineDebug:=False
CodeAnalysisIgnoreBuiltInRules:=True
CodeAnalysisRuleSetDirectories:=;F:\VS2017\Team Tools\Static Analysis Tools\\Rule Sets
CodeAnalysisCulture:=
CodeAnalysisOverrideRuleVisibilities:=False
CodeAnalysisRuleAssemblies:=
DefineTrace:=False
DebugSymbols:=True
CodeAnalysisIgnoreBuiltInRuleSets:=True
CodeAnalysisRuleSet:=MinimumRecommendedRules.ruleset
NoWarn:=
CodeAnalysisIgnoreGeneratedCode:=True
EnableSQLServerDebugging:=False
BaseAddress:=4194304
RemoteDebugEnabled:=False
StartURL:=
AllowUnsafeBlocks:=False
TreatSpecificWarningsAsErrors:=
PlatformTarget:=AnyCPU
EnableUnmanagedDebugging:=False
StartWithIE:=False
StartArguments:=
IntermediatePath:=new\path\to\obj2\
CodeAnalysisRuleDirectories:=;F:\VS2017\Team Tools\Static Analysis Tools\FxCop\\Rules
DebugInfo:=full
CheckForOverflowUnderflow:=False
RemoteDebugMachine:=
Prefer32Bit:=True
CodeAnalysisSpellCheckLanguages:=
CodeAnalysisRules:=
RegisterForComInterop:=False
FileAlignment:=512
StartAction:=0
EnableASPXDebugging:=False
ConfigurationOverrideFile:=
WarningLevel:=4
RemoveIntegerChecks:=False
In the CS project I had added
<IntermediateOutputPath>new\path\to\obj2</IntermediateOutputPath>
As you can see IntermediateOutputPath is coming up as IntermediatePath. So you can use
var config = project.ConfigurationManager.ConfigurationRow("Debug").Item(1) as Configuration;
config.Properties.Item("IntermediatePath").Value
Edit-1 - .NET standard project
Edit-2 - 12-Aug-2017
So after digging more into the issue I found out the property is a MSBuild property as such and not a CSProject related property. That is why you don't see it in the Properties attribute. This requires a bit different direction to get the value using IVsBuildPropertyStorage.GetPropertyValue
private IVsBuildPropertyStorage GetBuildPropertyStorage(EnvDTE.Project project)
{
IVsSolution solution = (IVsSolution)ServiceProvider.GetService(typeof(SVsSolution));
IVsHierarchy hierarchy;
int hr = solution.GetProjectOfUniqueName(project.FullName, out hierarchy);
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
return hierarchy as IVsBuildPropertyStorage;
}
private string GetBuildProperty(string key, IVsBuildPropertyStorage Storage)
{
string value;
int hr = Storage.GetPropertyValue(key, null, (uint)_PersistStorageType.PST_USER_FILE, out value);
int E_XML_ATTRIBUTE_NOT_FOUND = unchecked((int)0x8004C738);
// ignore this HR, it means that there's no value for this key
if (hr != E_XML_ATTRIBUTE_NOT_FOUND)
{
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
}
return value;
}
And then later use these methods to get the value
var project = proj as EnvDTE.Project;
IVsBuildPropertyStorage storage = GetBuildPropertyStorage(project);
string outputPath = GetBuildProperty("IntermediateOutputPath", storage);
And this gives me the correct value of the property
I'm doing a project Template. there is some custom parameters ( The services and attributes that he will be using during the implementation of the project ). Each service needs a specific reference. So depending on the custom parameters, I prepare a list that contains the paths of the needed assemblies. How can I add them to the project ?! I tried the following code but no result.`
var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync(#"path").Result;
var projects = solution.Projects;
foreach (EnvDTE.Project proj in solution.Projects)
{
if (proj.Name == projectName)
{
VSLangProj.VSProject vsproj = (VSLangProj.VSProject)proj.Object;
foreach (string dll in Wizard.View.View.refs)
{
vsproj.References.Add(dll);
}
}
}`
I'm trying to use libgit2sharp to get a previous version of a file. I would prefer the working directory to remain as is, at the very least restored to previous condition.
My initial approach was to try to stash, checkout path on the file I want, save that to a string variable, then stash pop. Is there a way to stash pop? I can't find it easily. Here's the code I have so far:
using (var repo = new Repository(DirectoryPath, null))
{
var currentCommit = repo.Head.Tip.Sha;
var commit = repo.Commits.Where(c => c.Sha == commitHash).FirstOrDefault();
if (commit == null)
return null;
var sn = "Stash Name";
var now = new DateTimeOffset(DateTime.Now);
var diffCount = repo.Diff.Compare().Count();
if(diffCount > 0)
repo.Stashes.Add(new Signature(sn, "x#y.com", now), options: StashModifiers.Default);
repo.CheckoutPaths(commit.Sha, new List<string>{ path }, CheckoutModifiers.None, null, null);
var fileText = File.ReadAllText(path);
repo.CheckoutPaths(currentCommit, new List<string>{path}, CheckoutModifiers.None, null, null);
if(diffCount > 0)
; // stash Pop?
}
If there's an easier approach than using Stash, that would work great also.
Is there a way to stash pop? I can't find it easily
Unfortunately, Stash pop requires merging which isn't available yet in libgit2.
I'm trying to use libgit2sharp to get a previous version of a file. I would prefer the working directory to remain as is
You may achieve such result by opening two instances of the same repository, each of them pointing to different working directories. The Repository constructor accepts a RepositoryOptions parameter which should allow you to do just that.
The following piece of code demonstrates this feature. This creates an additional instance (otherRepo) that you can use to retrieve a different version of the file currently checked out in your main working directory.
string repoPath = "path/to/your/repo";
// Create a temp folder for a second working directory
string tempWorkDir = Path.Combine(Path.GetTempPath(), "tmp_wd");
Directory.CreateDirectory(newWorkdir);
// Also create a new index to not alter the main repository
string tempIndex = Path.Combine(Path.GetTempPath(), "tmp_idx");
var opts = new RepositoryOptions
{
WorkingDirectoryPath = tempWorkDir,
IndexPath = tempIndex
};
using (var mainRepo = new Repository(repoPath))
using (var otherRepo = new Repository(mainRepo.Info.Path, opts))
{
string path = "file.txt";
// Do your stuff with mainrepo
mainRepo.CheckoutPaths("HEAD", new[] { path });
var currentVersion = File.ReadAllText(Path.Combine(mainRepo.Info.WorkingDirectory, path));
// Use otherRepo to temporarily checkout previous versions of files
// Thank to the passed in RepositoryOptions, this checkout will not
// alter the workdir nor the index of the main repository.
otherRepo.CheckoutPaths("HEAD~2", new [] { path });
var olderVersion = File.ReadAllText(Path.Combine(otherRepo.Info.WorkingDirectory, path));
}
You can get a better grasp of this RepositoryOptions type by taking a look at the tests in RepositoryOptionFixture that exercise it.