get application path in asp.net vnext - c#

I've been trying to open a file in asp.net 5 and have not been having a lot of success.
In the past you used Server.MapPath or HostingEnvironment.ApplicationPhysicalPath. They are both gone in the OWIN based framework.
There is a HostingEnvironment class but it's in the System.Aspnet but it needs to be initialized by the hosting environment (it no longer has a static member for ApplicationPhysicalPath but I'm guessing the WebRoot member does that now. The problem is I can't find a reference to it anywhere.
I've also looked at Context.GetFeature<> but it doesn't seem to have any feature that would show the application path, just request and response related info. The code listing the features can be found here.
<snark>Is the ability to work with files a discontinued feature in ASP.NET?</snark>
There is also the possibility that I can't brain very well right now and missed something.

You can get it from the ApplicationBasePath property of Microsoft.Framework.Runtime.IApplicationEnvironment serivce.
Example: https://github.com/aspnet/Mvc/blob/9f1cb655f6bb1fa0ce1c1e3782c43a2d45ca4e37/test/WebSites/FilesWebSite/Controllers/DownloadFilesController.cs#L28

There are two approaches now:
using Microsoft.Extensions.PlatformAbstractions;
public Startup(IApplicationEnvironment appEnv)
{
// approach 1
var path01 = PlatformServices.Default.Application.ApplicationBasePath;
// approach 2
var path02 = appEnv.ApplicationBasePath;
}

Related

C# AWS Parameter Store - Configuration not loading SystemManagerConfiguration in .Net 6

Application is not able to talk to AWS Parameter Store in .NET 6.
It is always talking to appsettings.json.
I tried debugging locally, still same behavior. Not able to find the SystemManagerConfiguration under list of configuration .
var builder = WebApplication.CreateBuilder();
var connectionString = builder.Configuration.GetConnectionString("OrderTrackerDatabase");
Packages Used
Library Source Code : https://github.com/aws/aws-dotnet-extensions-configuration
image
I got the same issue and finally resolved it.
The samples code in https://github.com/aws/aws-dotnet-extensions-configuration missed one line as below after called "AddSystemsManager" method in .Net 6.
builder.Services.Configure<Settings>(builder.Configuration.GetSection($"common:settings"));
After added above line, then I'm able to get the correct values from AWS Parameter Store when using the settings.
I've also created an issue of this in GitHub as below -
https://github.com/aws/aws-dotnet-extensions-configuration/issues/114
I believe the problem might be the trailing slash after "/OrderTracking/", try "/OrderTracking" instead.
WebApplication.CreateBuilder() will create new instance and doesn't carry over the SystemManager configuration.
Instead, use IConfiguration instance through constructor DI.
var connectionString = _configuration.GetConnectionString("OrderTrackerDatabase");
In my case this extensions method was returning null at my lambda:
private static IConfiguration InitializeConfiguration() => new ConfigurationBuilder()
.AddSystemsManager($"/my-data", true, TimeSpan.FromMinutes(5))
.Build();
Because the role of lambda didn't have permission for read SSM for that resource.
User: is not authorized to perform: ssm:GetParametersByPath on resource
So, just add necessary permission (ssm:GetParametersByPath) for the role of lambda to your resource at System Manager.
In my case, I am using lambda serverless, so the IConfig is always null when it is passed to the controller.
I resolved it by changing the IOptions<Settings> settings in the Controller constructor to IConfiguration settings and then access the parameters by name like _settings.GetValue<string>("ParameterName")
A little less "Object Oriented", but it seemed much easier than this complex solution

How can I use DI to create an instance of the page that I navigate to with my route?

Here is the situation that I have:
I have set up a route like this:
Routing.RegisterRoute("Cars/CarMgmtPage", typeof(CarMgmtPage));
When a button is clicked it calls the following:
await Shell.Current.GoToAsync("Cars/CarMgmtPage", true);
However CarMgmtPage takes constructors in the argument like this;
public CarMgmtPage(IAddCar addCar1,
IAddCar addCar2)
What I need to do is to use the Microsoft.Extensions.DependencyInjection that is used in my application to create this page something like this:
var abc = Startup.ServiceProvider.GetRequiredService<CarMgmtPage>();
But I have no idea how to go about this as it seems the Xamarin Shell handles the creation of the page and I don't see how I can fit DI into that.
I hope someone has some ideas on how to do this.
It would seem that at this time this is not possible. There are a couple of issues in the Xamarin Github talking about this:
[Enhancement] Dependency Injection support for creating ContentPage in Shell. #8359
Current status of this is:
Under consideration-High Interest in Enhancements on Jun 2, 2020
Also
[WiP] .NET MAUI Shell Improvements #10804
So the answer to this is that it we can hopefully expect this in the near future but right now it's still at the planning stage.

a proxy type with the name account has been defined by another assembly

We have 2 orgs running in our on-premise crm 2011 system.
We have generated early bound classes for both orgs.
One of our plugins is throwing the "a proxy type with the name account has been defined by another assembly" error when deactivating an account.
That plugin only references one of the early bound dll's.
How do I get the CRM system to respect the namespace of these references.
I've tried the few items that show up from Google and none are working.
Since you can reproduce this with 2 vanilla orgs I would imaging there is something OUTSIDE the code layer we can do without having to go back and refactor a bunch of code for the 2 orgs.
Thanks,
Jon
The problem is actually with WCF attempting to deserialize the server response and not being able to identify the correct type. The best method to sort this issue is to pass in the current assembly using Assembly.GetExecutingAssembly() to the ProxyTypesBehavior() while creating the proxy like so.
using (serviceProxy = new OrganizationServiceProxy(config.OrganizationUri,
config.HomeRealmUri,
config.Credentials,
config.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior(Assembly.GetExecutingAssembly()));
}
You may run into this issue when referencing different assemblies containing proxy-classes, i.e. one assembly wrapping the server SDK (Microsoft.Xrm.Sdk) and another assembly wrapping the client SDK (Microsoft.Xrm.Sdk.Client).
In such a scenario it seems to be required to tell the OrganizationServiceProxy which assembly should be used to resolve the proxy classes.
This should help:
var credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential(userName, password, domain);
var proxy = new OrganizationServiceProxy(new Uri(discoveryUrl), null, credentials, null);
proxy.EnableProxyTypes(typeof(CrmServiceContext).Assembly);
var context = CrmServiceContext(proxy);
The important thing is to call EnableProxyTypes by passing the correct assembly. I saw another solution using CrmConnection but CrmConnection is only available in the client SDK, which means that you can't instantiate a "server-OrganizationServiceProxy" this way. EnableProxyTypes(Assembly assembly) works for both sides.
Hope this helps.
Regards,
MH
It maybe years since this question has been raised. However, I faced this problem recently and have been extremely worried about thousands of lines of code to be changed. However, I was lucky to find the following simple change to get myself out of hell:
Suppose there are two context objects you deal with:
an OrganizationServiceContext object: context1
a CrmSvcUtil Context object: context2
and a single OrganizationServiceProxy object: service
if in a single method, you make multiple CRUD operations using the same service object but with either of context objects as exemplified above, it is highly probable that this error be raised. However, by doing the following, you can prevent it to happen.
Every time you want to work with context1, you precede the context object with the service object as following:
service.EnableProxyTypes(typeof(OrganizationServiceContext).Assembly);
using (var context1 = new OrganizationServiceContext(_service)){
// your classic code here
}
Also, every time you want to work with context2, you follow the same structure:
service.EnableProxyTypes(typeof(HiwebContext).Assembly);
using (var context = new XYZContext(this._service)){
// your CrmSvcUtil none-classic code here
}
this normally means that there is one or more assemblies with the same method name or property to fix this use the fully qualified name of the assembly.. for example in the using System.IO for example if you had a method named the same way in your Class code that conflicts with System.IO.... you would write your fix like
thisObject.System.IO.Path( ---- ) = somthing for example.. does this make sense..?
I found that adding the Assembly.GetExecutingAssembly() solved the problem.
adding the Assembly.GetExecutingAssembly() solve my problem, you also need to add using System.Reflection;
thanks

How can I get the URL of the current page from within a C# App_Code class?

I have a logging class that, well, logs things. I would like to add the ability to automatically have the current page be logged with the messages.
Is there a way to get the information I'm looking for?
Thanks,
From your class you can use the HttpContext.Current property (in System.Web.dll). From there, you can create a chain of properties:
Request
Url and RawUrl
The underlying object is a Page object, so if you cast it to that, then use any object you would normally use from within a Page object, such as the Request property.
It's brittle and hard to test but you can use System.Web.HttpContext.Current which will give you a Request property which in turn has the RawUrl property.
public static class MyClass
{
public static string GetURL()
{
HttpRequest request = HttpContext.Current.Request;
string url = request.Url.ToString();
return url;
}
}
I tried to break it down a little :)
In the past I've also rolled my own logging classes and used Console.Writeln() but really there are a number of good logging options that already exist so why go there? I use NLog pretty much everywhere; it is extremely flexible with various log output destinations including console and file, lots of log format options, and is trivial to set up with versions targeting the various .net frameworks including compact. Running the installer will add NLog config file options to the Visual Studio Add New Item dialog. Using in your code is simple:
// declare in your class
private static Logger logger = LogManager.GetCurrentClassLogger();
...
// use in your code
logger.Debug(() => string.Format("Url: {0}", HttpContext.Current.Request.Url));

OAuth in C# as a client

I've been given 6 bits of information to access some data from a website:
Website Json Url (eg: http://somesite.com/items/list.json)
OAuth Authorization Url (eg: http://somesite.com/oauth/authorization)
OAuth Request Url (eg: http://somesite.com/oauth/request)
OAuth Access Url (eg: http://somesite.com/oauth/access)
Client Key (eg: 12345678)
Client Secret (eg: abcdefghijklmnop)
Now, I've looked at DotNetOpenAuth and OAuth.NET libraries, and while I'm sure they are very capable of doing what I need, I just can't figure out how to use either in this way.
Could someone post some sample code of how to consume the Url (Point 1.) in either library (or any other way that may work just as well)?
Thanks!
I also just started working with OAuth a month ago and was also confused by all these libraries. One thing I realized about these libraries is that they're quite complicated (as you have found out). Another thing that makes it hard is that there wasn't a lot of example (it was worse in my case because I was trying to implement a Provider and not a Client).
Originally, I wanted to use the latest OAuth 2.0 but the only .NET library out there that implements it is DotNetOpenAuth. It's probably one of the most complete .NET OAuth library out there but it'll take too long for me to understand (due to not knowing WCF, MVC, etc). I have since downgraded to OAuth 1.0a because I found these examples for DevDefined OAuth. I don't know about you but I found it easier to learn from examples.
It looks like you only want to implement a Client so make sure to look at the Consumer examples. Try to compile the examples and ignore the Provider examples because you don't need them and it'll make you more confused. Be patient. If you're still confused, it might be a good idea to look at some of the libraries made for other languages as they might have easier to understand documentations.
OK, I know your last post was months ago, but in case you were still working on this (or for people like me who would have loved to see an answer to this question), here's some information regarding the NullReferenceException you encountered creating the OAuth request:
The null reference comes from the IServiceLocator that is used to resolve dependencies. If you don't explicitly pass one into the constructor, it uses the static property ServiceLocator.Current in the Microsoft.Practices.ServiceLocation namespace.
This is one of the many pitfalls of using static methods and global state, is you hide issues like this from the consumer of your API. So if you haven't specified a default service locator, then null is returned, resulting in the NullReferenceException.
So to fix this issue, I wired up an implementation of IServiceLocator that uses StructureMap (one of the many IoC containers available) as the container. Lastly, you will need to register instances for two interfaces: ISigningProvider and INonceProvider. Luckily, several standard implementations exist in the OAuth.Net.Components assembly, such as GuidNonceProvider and HmacSha1SigningProvider.
The resulting code looks like something like this:
var container = new Container();
container.Configure(a => a.For<INonceProvider>().Use<GuidNonceProvider>());
container.Configure(a => a.For<ISigningProvider>()
.Use<HmacSha1SigningProvider>()
.Named("signing.provider:HMAC-SHA1"));
var locator = new StructureMapAdapter(container);
ServiceLocator.SetLocatorProvider(delegate { return locator; });
I realize this isn't the final solution to your original question (I'm still working on getting it working myself), but I hope it gets you a few steps further. And if you've long abandoned this implementation altogether... well, happy coding anyway!
For OAuth 2.0:
I learned that it's easiest to just put up the authentication page in an HTML window then trap the returned access_token. You can then do that using in client-side web browser.
For example, in MonoTouch it would be:
//
// Present the authentication page to the user
//
var authUrl = "http://www.example.com/authenticate";
_borwser.LoadRequest (new NSUrlRequest (new NSUrl (authUrl)));
//
// The user logged in an we have gotten an access_token
//
void Success(string access_token) {
_web.RemoveFromSuperview();
var url = "http://www.example.com/data?access_token=" + access_token;
// FETCH the URL as needed
}
//
// Watch for the login
//
class Del : UIWebViewDelegate
{
public override void LoadingFinished (UIWebView webView)
{
try {
var url = webView.Request.Url.AbsoluteString;
var ci = url.LastIndexOf ("access_token=");
if (ci > 0) {
var code = url.Substring (ci + "access_token=".Length);
_ui.Success (code);
}
} catch (Exception error) {
Log.Error (error);
}
}
}

Categories