What is the difference between CurrentDomain and UserDomainName? - c#

Recently, a customer complained that our product was not populating the domain name.
Our code uses the Username and the User's Domain Name to query their membership rolls in Active Directory.
In our code, we use Environment.UserDomainName:
var domain = Environment.UserDomainName;
When I looked at this simple line of code, I discovered it could raise the PlatformNotSupportedException and the InvalidOperationException.
Looking for an alternative method of reading the domain name, I came across AppDomain.CurrentDomain:
var domain = AppDomain.CurrentDomain.FriendlyName.Split(".".ToArray())[0];
That is nice, but it also appears to have an AppDomainUnloadedException that could be triggered.
First Question:
Will these 2 methods always return the same information for a given user who is running our program on a local PC?
Second Question:
Is one method less "exception prone" than the other (again, for a given user who is running our program on a local PC)?
Last Question:
Is there a method of getting the local domain name of the user running our application that will not cause an exception to be thrown?
EDIT: For Tyler Lee

Did you even try to see what the value of AppDomain.CurrentDomain.FriendlyName was?
To Answer question 1: No, they will not.
Question 2 does not seem to apply considering question 1
Question 3: probably not. Environment.UserDomainName seems to be the source for getting a network domain name, and as you found, it has the potential to generate exceptions. The MSDN page gives details on when those exceptions are thrown, and you should write your code to be able to deal with it if they happen.

The AppDomain.CurrentDomain Property is the domain of the current application and the current thread.
In other words, this is the domain of a project.
In Visual Studio, under a Project's Properties page, this would be referred to as the Project's Assembly Name.
By contrast, Environment.UserDomainName Property is the name of the network that the current user is logged in through.
The two are not related.

Related

ExchangeService FindAppointments returns 'This property was requested, but it wasn't returned by the server' error

I'm using Microsoft.Exchange.WebServices.dll version 15.0.847.30 to interact with functions in Outlook. I am using this call:
EWSData = CurrentEmail.FindAppointments(WellKnownFolderName.Calendar, new CalendarView(t, t.AddDays(1)));
(where t is today +/- however many days the user has clicked from today) which passes the WellKnownFolderName and the CalendarView directly through to a call to ExchangeService.FindAppointments.
I have a couple clients who each have a single user who is getting the 'This property was requested, but it wasn't returned by the server' error on some days and not others. Sometimes it pulls in the first few appointments for a day and leaves off the rest. My email, creating appointments, and add/remove contacts functions are all working for them.
I've traced through the ews-managed-api code from github and found the error is thrown when a property is requested but is null. I'm assuming the code on github is much newer than the version I'm using, but if the error is still caused by that code is in my version, I do not know how to find out what properties are causing the issue.
Since I'm not requesting anything specific but using the generic call with the folder name and a date, I'm quite confused as to what properties would be null and why.
What can I do, without re-compiling my application, to track down the problem properties?
Just a thought: do you have a way of tracing the XML flow between your app and Exchange, e.g. Fiddler? On the error response, you may be able to plow into the XML and see the name of the property causing the issue. Not 100% sure on this, but about the only tactic you can try without rebuilding you app with more diagnostic code in there.

ASP.NET mvc 5 - Returning user exception

I am totally new to ASP.NET MVC 5 and I need some help.
Background:
I am building my own web site because I would like to productise it eventually.
It's a form of eating your own dog food.
I have created a default application (you know, the one with all the MS links) and am modifying it for my own needs.
The first thing I did is what you should NEVER do :) i.e. modify the database tables manually to add roles and give my spanking new user the admin role. I did google but either I asked it the wrong question or
missed the link totally. Either way, I modified them manually and it
seemed to "work" (i.e. no db integrity errors were raised in Visual Studio).
I then added a "Products" table and did the scaffolding from the model to the controller, views, etc (thanks Mr Google). I also found how to stop
showing links in the Index view for the data manipulation if you're not an
admin.
Now, as I implied, I had registered a user, so I was curious to see what
would happen when I returned and tried to call (from URL) my brand new toy.
That's when a very useful "Object reference not set..." came up.
I have therefore a few questions:
Did I do anything stupid (likely)?
If I did, what is it?
The stack trace does not mention anything to do with login or
errors in the db, except for the following lines:
Microsoft.Owin.Security.Cookies.CookieAuthenticationProvider.Exception(CookieExceptionContext context) +49
Microsoft.Owin.Security.Cookies.<AuthenticateCoreAsync>d__2.MoveNext() +3698
which are just below the main line detailing the error.
So, if I am correct, it tried to access a cookie it didn't find.
What do you think is the most likely cause of this issue?
Suggestions?
[UPDATE]
Ok, so I have tried digging a bit to see whether I could find something interesting... and eventually I did.
Buried in one of the many files, I found this comment:
Note the authenticationType must match the one defined in
CookieAuthenticationOptions.AuthenticationType
Which seems to match with the stack trace outlined above.
I did check and it seems to me that they are the same(thanks to Google I found where to look).
I am stuck.
Please help!

Use of Forest.GetCurrentForest in RODC environment

I've got a problem with using Forest.GetCurrentForest() method when communicating with a Read-only domain controller.
The exception thrown is:
System.DirectoryServices.ActiveDirectory.ActiveDirectoryServerDownException: The server is not operational.
Note: Everything works fine when communicating with a RWDC.
Previously, to fix other issues when communicating with a RODC, we had to modify the way we created DirectoryEntry objects, making use of the AuthenticationType.ReadOnlyServer flag. However I've seen (using reflector) that the GetCurrentForest() method creates its own DirectoryEntry object using a Utils class, which in turn uses a DefaultAuthType.
So, my question is: Does anyone know how to set/modify the DefaultAuthType so that it can return the required authentication type? Is there a better way to do this? The aim of this piece of code is simply to get the list of available domains visible to the server.
Thanks,
Ben
Well, doesn't seem like there's an easy answer to this. In the end we rewrote the code to not use the Domain/Forest objects...
What I do to "overcome" this issue was, I first try to get the Forest.GetCurrentForest(), and if exception thrown, I then use Domain.GetComputerDomain() for last solution, of cause, the list now only contain the domain that the web server joined.

Performance Monitor .NET CLR Networking 4.0.0.0 Instance naming

I'm trying to use a Performance Counter do determine how many bytes my application has sent or received. I followed the suggested solution found here: Calculating Bandwidth, but the instance of my application doesn’t show up in the “.NET CLR Networking” category. Exception message:
"Instance 'ApplicationName[8824]' does not exist in the specified
Category"
(I have added <performanceCounters enabled="true"/> in my App.config and it still it cannot be found after some networking activities)
So I started Performance Monitor so see the error with my own eyes. As expected, my application doesn't show up in the .NET CLR Networking category, but it can luckily be found in the .NET CLR Networking 4.0.0.0 category.
However, my problem is that I cannot figure out how instance name is generated. Here is the name of the instance I see in the Performance Monitor: ApplicationName.exe_p4952_r15_ad1.
So far I have figured out that the first parts must be made of ProcessName and PID, but I
have no clue what the last two ("r15" and "ad1") pieces come from.
Does somebody have a clue what the last two pieces could be?
One solution would be to enumerate all the instances found in the “.NET CLR Networking 4.0.0.0” category and search for ApplicationName.exe_PID*, but would prefer to look for the correct name directly (if possible).
Check this link for more information on how the name is built. In short the "rXX" is the runtime ID of the common language runtime (instance) that executes your code.
This new naming convention was established so that in side-by-side scenarios (where you have more than one CLR instance in a process; which is a new feature starting with .NET 4.0) you can actually differentiate the performance counters.
The "adXX" is not described on the page above, but from the acronym I'd suppose it stands for Application Domain. The number could possibly be the AppDomain.Id of the application domain.
See this answer on how to get the correct name. In short, use
var processFileName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
var instanceName = VersioningHelper.MakeVersionSafeName(processFileName, ResourceScope.Machine, ResourceScope.AppDomain);
It should be:
string appDomain = AppDomain.CurrentDomain.FriendlyName.ToLower();
string a = VersioningHelper.MakeVersionSafeName(appDomain, ResourceScope.Machine, ResourceScope.AppDomain);
I've had problems with version with process name when writing unit tests. Version with app domain works for tests and for applications result was the same as with process name.

Report Viewer - Request for the permission of type SqlClientPermission failed

I am using the ReportViewer control from Visual Studio 2008 in Local Mode with objects as the data source. My classes are mapped to data tables in my database. In the objects, it loads related objects as needed. So it leaves the reference null until you try to use the property, then it tries to load it from the database automatically. The classes use the System.Data.SqlClient namespace.
When I interact with the objects in my Windows Forms application, everything works as expected. But when I pass the object to be used as a Report Data Source and it tries to automatically load the related object, it fails. The code creates a SqlConnection object and when I call GetCommand() on it, the following exception is thrown:
[System.Security.SecurityException] {
"Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."
} System.Security.SecurityException
I've tried searching for the error, but all the results that show up are for CLR assemblies running on a SQL Server or ASP.Net. I've tried adding the following call in my code (as suggested in the search results) before creating the SqlConnection objects, but it didn't apparently do anything:
System.Data.SqlClient.SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
Any ideas?
In addition to the answer of CuppM.
The ExecuteReportInCurrentAppDomain method is deprecated since .NET4, and LocalReport.SetBasePermissionsForSandboxAppDomain should be used instead, as ReportViewer is now always executed in sandboxed domain:
PermissionSet permissions = new PermissionSet(PermissionState.None);
permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
ReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions);
See details here.
I've found the solution. You specify System.Security.Policy.Evidence of you executing assembly (or one that has sufficient rights) to the LocalReport for use during execution.
reportViewer.LocalReport.ExecuteReportInCurrentAppDomain(System.Reflection.Assembly.GetExecutingAssembly().Evidence);
Just in case someone stumbles upon this like I did while searching for this Permission-Error.
I got this error using a Windows-Forms-Application because the customer had linked a shortcut to my Application-Exe on his machine with "\COMPUTERNAME\C$\Application.exe" instead of "C:\Application.exe." - This caused the failure of the System.Security.Permission because of the untrusted intranet use.
See http://www.duelec.de/blog/?p=236 for more Information.
A footnote to Artem's answer above...
I had this problem when adding Windows Authentication to my asp.net app. Targeting Framework 4.5 and using Reporting components 11. When I was allowing anonymous users (in early dev) I had no problems using the ReportViewer. As soon as I enabled Windows auth I would either get "#Error" on Grouping expressions, or not be able to run the report at all, giving the exception listed above.
I was able to work around the problem but with a slightly modified version of what Artem posted. I am not completely sure what the code does other than a general sense that it allows CAS to trust the sandboxed ReportViewer code. Any comments with a little explanation would be appreciated.
Dim permissions As PermissionSet = New PermissionSet(PermissionState.Unrestricted)
myReportViewer.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions)
One quick thought, although this isn't an error I've seen, make sure that your Assert is in the same method as the code that is setting the resource data source:
System.Data.SqlClient.SqlClientPermission mPermission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
try
{
mPermission.Assert();
//rest of your code
}
//Handle Exceptions
Permission Asserts don't hang around for long, they can be a security issue, so doing them as near as possible to the code that needs them is most likely to work.

Categories

Resources