C# run piece of code under different credential - c#

Referring to THIS QUESTION I was able to execute some code as different user.
Now I'm trying to execute a piece of code as a user with administrator privileges and I get a missing file error. The code is this:
using (new Impersonator("domainAdmin", "DOMAIN", "myStup1dPa$$w0rd"))
{
GetXAApplicationByName apps = new GetXAApplicationByName();
apps.BrowserName = new string[] { "*" };
IEnumerable<XAApplication> result = CitrixRunspaceFactory.DefaultRunspace.ExecuteCommand(apps);
// other code...
}
The error is thrown at last reported line, the one starting with IEnumerable<XAApplication> and is:
FileNotFoundException not handled C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll
I don't report code for Impersonator class, the basic schema is reported on linked question (and it worked also in other applications).
Am I missing something?

Looks like there is no problem with impersonating but your code somehow tries to load the assembly System.Management.Automation.dll which is not in GAC , can you try registering this assembly in GAC and try it out again .

Related

How to save data to network path on .NET?

I'm really struggling with saving data to my local network NAS (a Synology DS214 if that matters).
I need to store some files in my network folders after creating them in another part of my program, but I haven't been able to handle the authentication/permissions properly.
My code atm is this:
WrapperImpersonationContext WIContext =
new WrapperImpersonationContext("\\\\DiskStation", "admin", "admin");
try
{
WIContext.Enter();
// code to select the final path simplified.
string fileName = "file.txt";
string originalPath = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
originalPath= Path.Combine(new string[] {originalPath, fileName});
string finalPath = "\\\\DiskStation\\Virtual\\DestFolder";
if (!Directory.Exists(finalPath))
{
// This goes well for whatever reason
Directory.CreateDirectory(finalPath);
}
finalPath = Path.Combine(new string[] {finalPath, fileName});
// This fails for wrong username/password
File.Move(originalPath, finalPath);
} catch (Exception ex)
{
// Exception showing simplified here
MessageBox.Show(ex.ToString());
throw;
} finally
{
WIContext.Leave();
}
The code used for the WrapperImpersonationContext I found here:
WindowsImpersonationContext made easy
As written in my code when I try to move the file I get an UnauthorizedAccessException: Access to the path is denied. I also tried to create a new file in the network folder with the same results.
While looking at the Michiel Vanotegem's code linked above, I discovered that I get an authentication error calling the LogonUser function (error code 1326 that gets me a Win32Exception (0x80004005): The user name or password is incorrect).
I tried to use the WNetUseConnection function looking at this and this pages but while I get no error from the function (after substituting it in the Michiel code), when I try to move the file I get the same UnauthorizedAccessException: Access to the path is denied.
I also tried to fiddle with the domain passed to the Impersonation Wrapper but I couldn't seem to make it work. I feel like I'm missing something... Can someone kindly point me to the right direction or help me with this issue?
Ty all who contributes in advance.
Edit 15/12/2017 11:52: I discovered that if I try to rerun the LogonUser function immediately after the first error I get a different exception (error 87 Win32Exception (0x80004005): The parameter is incorrect)
I followed on #LennartStoop suggestion, so I enclosed my code in a using block instead of a try finally using the code I borrowed from this answer:
using (NetworkConnection netConn =
new NetworkConnection("\\\\DiskStation", new NetworkCredential("admin", "admin")))
{
// My code here
}
Using this I've been able to establish a connection the network folder and perform all the IO operation I needed so ty very much for the tip Lennart :)

WF4.5- Expression Activity type 'CSharpValue`1' requires compilation in order to run

Background
What I'm trying to do is to have a scoped variable of one of my models in the xaml.
In my workflow project "MyProject.Workflows" I have created model classes, code activities and Xaml files. They are all under same namespace. In another project ("Engine"), I load and execute these workflows.
To load the workflows in the "Engine", I use ActivityXamlServices with ActivityXamlServicesSettings including CompileExpressions = true.
When loading the ActivityXamlServices, I use a XamlXmlReader with XamlXmlReaderSettings where I actually point to the "MyProject.Workflows" dll.
Since Both these projects are in the same solution I actually referred MyProject.Workflows in the "Engine".
Because Earlier, they were in different solutions, So when I tried to do this It gave me It cant find the "MyProject.Workflows" dll even though I point it in the XamlXmlReaderSettings.
Then I tried to load the dll to the app domain and then it worked.But I did not want to deal with App Domains so I decided to get both projects under one solution so I can refer the "MyProject.Workflows" in the "Engine".
Issue:
If I use one of those models inside of the Xaml as an expression like "Assign Activity" the Workflow isn't getting compiled when I try to execute this.
For example if I use this in an "Assign" activity having a scoped variable of type MyObject
Newtonsoft.Json.JsonConvert.DeserializeObject<MyProject.Workflows.Models.MyObject>(inputString);
I will get the below error message when I run the workflow.
NotSupportedException:'Expression Activity type 'CSharpValue`1' requires compilation in order to run. Please ensure that the workflow has been compiled.
If I remove these objects and just deal with strings or ints, it works fine.
Things I found in my research:
I found this was a bug in .Net Framework 4.5. But Im using 4.6
Even though I used CompileExpressions = true , I tried this compile method I found. But did not change a thing.
private static void Compile(DynamicActivity dynamicActivity)
{
TextExpressionCompilerSettings settings = new TextExpressionCompilerSettings
{
Activity = dynamicActivity,
Language = "C#",
ActivityName = dynamicActivity.Name.Split('.').Last() + "_CompiledExpressionRoot",
ActivityNamespace = string.Join(".", dynamicActivity.Name.Split('.').Reverse().Skip(1).Reverse()),
RootNamespace = null,
GenerateAsPartialClass = false,
AlwaysGenerateSource = true,
};
TextExpressionCompilerResults results =
new TextExpressionCompiler(settings).Compile();
if (results.HasErrors)
{
throw new Exception("Compilation failed.");
}
ICompiledExpressionRoot compiledExpressionRoot =
Activator.CreateInstance(results.ResultType,
new object[] { dynamicActivity }) as ICompiledExpressionRoot;
CompiledExpressionInvoker.SetCompiledExpressionRootForImplementation(
dynamicActivity, compiledExpressionRoot);
}
I read that some people faced this problem and they had to actually move the models to a diffrent namespace. I did that too. Didn't fix the problem.
My Xaml file has this entry added at the top.
xmlns:local="clr-namespace:MyProject.Workflows.Models"
Can someone please help me to get through this?

Unity-Mono throwing PlatformNotSupportedException while checking for Directory Permission

I am using below code to check Permission on Directories in Windows.
I am using in Unity 3.5.7f6 with "PC & Mac" Platforms in BuildSettings.
I am getting following exception:
PlatformNotSupportedException
UnauthorizedAccessException
string l_userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
DirectorySecurity folderSecurity;
//Way 1: Getting **PlatformNotSupportedException** with below line.
folderSecurity = new DirectorySecurity(a_directoryPath, AccessControlSections.Audit);
//Way 1---ENDS HERE
//Way 2: Getting **UnauthorizedAccessException** in last line of Way 2 block.
DirectoryInfo l_directory = new DirectoryInfo(a_directoryPath);
folderSecurity = l_directory.GetAccessControl(AccessControlSections.Audit);
//Way 2---ENDS HERE
foreach (FileSystemAccessRule fileSystemAccessRule in folderSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
{
string l_domain_userName = fileSystemAccessRule.IdentityReference.Value;
if (l_domain_userName.Equals(l_userName))
{
string l_userRights = fileSystemAccessRule.FileSystemRights.ToString();
Debug.Log(l_domain_userName + ":" + l_userRights);
if (fileSystemAccessRule.FileSystemRights.HasFlag(a_rightToCheck))
{
Debug.Log("-----have Accesss:" + a_rightToCheck);
l_isGranted = true;
break;
}
}
}
I have tried printing OS version:
Environment.OSVersion.Platform
it prints:
WindowsNT 5.1.2600 (which is XP)
All i am trying above, is to get whether a folder has Permission (Read OR write).
Help me to resolve this.
Short answer: At the moment this feature is simply not implemented by Unity.
Unity is using a pretty old version of Mono. There seems to be some licensing issues regarding mobile platforms and consoles, so that they are not able to simple use the newest version of Mono.
As you can see in the Mono source code for Unity 4.3, the constructor for DirectorySecurity simply raises an PlatformNotSupportedException. And because GetAccessControl depends on DirectorySecurity it will also just raise an exception.
If you explain why you need the permissions or what your ultimate goal is, we may be able to find another solution for your problem.
It appears that some of the directory security code is not implemented in a platform independent way in Mono, even in 4.8.
I came here with a similar problem when trying to edit a folder's permissions when running Mono on a Unix box. That raised a PlatformNotSupportedException from the NativeObjectSecurity class Hopefully this helps anyone else in a similar boat...

NUnit is not failing test with dynamic keyword of .Net 4.0

I am using NUnit with Visual Studio Express Edition 2010 for C#, Now, normally test works fine. But whenever I try to use Massive.cs, which is open source api to access database. Test fails from that file only. Now, if I run the application, api is working fine. I have created a different library file to access data base.
I seriously don't understand the error. It is just giving error that object reference is not set to an object. But if I run the code, it works fine. I am using dynamic keyword as shown in link of api above. Does that making problem with NUnit ?
Is there any other way to test in this type of Scenarios?
Here are the further details of the code,
Test class is like this
dynamic item = new Item();
item.Insert(new { Name = "Maggi", Description = "Its 2 Min Nuddles", IsDelete = false });
var items = item.All();
Assert.AreEqual("Maggi", items.FirstOrDefault().Name);
Now, I have put test here. Which gives error like shown in image,
Now if I run code in console application, then code is working fine, code snippet is given below
dynamic item = new Item();
item.Insert(new { Name = "Maggi", Description = "Its 2 Min Nuddles", IsDelete = false });
var result = item.All();
foreach (var i in result)
{
Console.WriteLine(i.Name + i.Description);
}
Console.Read();
Here, code is working and same thing is not working with NUnit Test. Please have a look and help me out. Please let me know if any further information is needed from my side.
Most probable explanation is that you haven't set up your connection string in the test project.
If you are using NUnit, just put it in app.config of your test project.
Solved... There is a issue with NUnit Testing. It was not taking config file pefectly. So, I made two changes. Changes I have done in Project setting.
First change is to change Application Base to bin\debug just give application base as this and then config file to .config to .exe.config and things are up and running. :)

ExchangeServiceBinding namespace error

Summary: application will not accept the ExchangeServiceBinding command.
Details:
I am trying to loop through a very large mailbox, so I am using an index to break the inbox into 200 email chunks. The only example I could find (shown below) keeps returning
the type or namespace name “ExchangeServiceBinding” could not be found (are you missing a using directive or an assembly reference? )
Which I find strange, because I am using it using Microsoft.Exchange.WebServices;. Any ideas or help is greatly appreciated. I am running Windows 7 and Visual Studio 2010 and trying to access Exchange 2007 mailboxes.
Things I've tried:
searching Google
searching Stack Overflow
searching MSDN
slamming my head on my desk
trial and error
Code:
// Create binding variable to be used for GetItemsFromInbox().
// Set up the binding with credentials and URL.
ExchangeServiceBinding binding = new ExchangeServiceBinding();
binding.Credentials = new NetworkCredential(dUser, dPassword, dDomain);
binding.Url = new Uri("https://" + ExchangeServerName + "/EWS/Exchange.asmx");
// Set up the binding for Exchange impersonation.
binding.ExchangeImpersonation = new ExchangeImpersonationType();
binding.ExchangeImpersonation.ConnectingSID = new ConnectingSIDType();
binding.ExchangeImpersonation.ConnectingSID.PrimarySmtpAddress = "mailboxnamehere”;
// Call GetItemsFromInbox()
int index = 0;
bool looping = true;
while (looping)
{
List<ItemType> items = GetItemsFromInbox(binding, index, 200, index);
if (items == null || items.count == 0)
{
looping = false;
break;
}
// Do your work here
}
Instead of the Exchange Web Services, use the Exchange Managed API.
SDK: http://msdn.microsoft.com/en-us/library/dd633710(v=exchg.80).aspx
Download: http://www.microsoft.com/download/en/details.aspx?id=13480
It's much easier to use than the WebServices.
I found my error. This methodology only works for Exchange 2010. Since I am running Exchange 2007 I will have to figure out a completely different way to make this work.
Thank you everyone for you help, I really appreciate it.
You should add a WebReference to your solution to the exchange WebService.
https://exchaneServerName/EWS/Exchange.asmx
ExchangeServiceBinding is contained into the ews.dll. According to your error, you didn't add a reference to this DLL file.
More information about Generating Exchange Web Services Proxy Classes:
So now you have a code file with the autogenerated proxies. Next, you compile your code file into an assembly for use in your Exchange Web Services projects. The C# compiler is available with the Visual Studio 2005 Command Prompt. Assuming that you named your code file EWS.cs, you can run the following command at the command prompt to compile your code into an assembly:
csc /target:library /out:EWS.dll EWS.cs
Notice that EWS.dll is the name of the compiled assembly. This is how EWS.dll is created.

Categories

Resources