Strange error while impersonating other user - c#

this is next step after
How to run wpf(c#) application by service account and integrated security
I created impersonation successfully, but i am getting some really strange error.
Let me explain situation:
My app is WPF
I have 2 users, my local account (localUser) and service account (saUser).
I am using Frame.Navigate() function to show diferent modules in my frame
I open app with localuser and then impersonate saUser
When i run my app with localUser it works OK (with local admin rights and without)
When i run my app with saUser i am getting this error, no mather if saUser is local admin or not, and the funniest thing is i get error when Navigate(...) is called 2nd time!, first time it works normal... :)
Requested registry access is not allowed.
stackTrace:
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at System.Windows.Application.GetSystemSound(String soundName)
at System.Windows.Application.PlaySound(String soundName)
at System.Windows.Application.FireNavigating(NavigatingCancelEventArgs e, Boolean isInitialNavigation)
at System.Windows.Navigation.NavigationService.FireNavigating(Uri source, Object bp, Object navState, WebRequest request)
at System.Windows.Navigation.NavigationService.HandleNavigating(Uri source, Object content, Object navState, WebRequest newRequest, Boolean navigateOnSourceChanged)
at System.Windows.Navigation.NavigationService.Navigate(Uri source, Object navigationState, Boolean sandboxExternalContent, Boolean navigateOnSourceChanged)
at System.Windows.Navigation.NavigationService.Refresh()
at MyApp.MyNavigation.Navigate(Module modul, Boolean reverse) -> my function
Guyz help, any suggestions? i don't know what is going on...
If i wasn't clear enough ask me...
EDIT:
I am adding some code like asked, just small peace of it where error happens:
I have public static class for navigation
MainWindow mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
current <- currentlly selected module
mainFrame <- frame that is showing all pages
// if current module if already selected refresh frame content
if (current.Link == mainWin.mainFrame.NavigationService.CurrentSource.ToString()) mainWin.mainFrame.Refresh();
// else show page content in frame
else mainWin.mainFrame.NavigationService.Navigate(new Uri(current.acLink, UriKind.Relative));
Error happens on Refresh() and Navigate().

I am facing same issue. Is there any solution to this?
There is an article related to how to access HKCU reg key, however it applies to code owned by us & not applicable to for WPF since its code is owned by Microsoft.
[Edit]
My observation is that if WPF user control/Window is initialized prior to impersonation then later on after impersonation there is no issue about how many times they get created; no error is thrown. Can this be done as a workaround?.

Related

Outlook Interop Exception HRESULT: 0xCA140115

I have some pretty basic code that seems to work for most people but there's at least one workstation that throws this HRESULT code when it runs these couple lines of code:
Outlook.Application _OutlookInstance = new Outlook.Application();
Outlook.Stores stores = _OutlookInstance.Session.Stores;
Any idea what HRESULT code 0xCA140115 is or what it means? I can't find it on MSDN anywhere...
The workstation that experiences the problem is at a remote call center location, so I can't do any immediate testing/debugging, or easily see what is specifically different about this workstation versus the others. I would imagine there might be more workstations at that same call center that could have the error, but this code is still in the testing phase.
Sorry for the delay, but I was able to get through several more iterations of testing and find out what the issue was. First off, my original post was incorrect. The code flow made it seem like the error was happening during those 2 initial lines, but it was actually happening a little later, when I was looping through the stores, like this:
Outlook.Stores stores = _OutlookInstance.Session.Stores;
foreach(Outlook.Store store in stores) // <----- THIS LINE
{
...
}
Each time the user ran this, he would get a different HRESULT error code:
0xCA140115
0xAF64011D
0xC1F4011D
0xC834011D
The only consistent factor was the "4011" in the middle.
When I upped the logging, I could see that the user had 18 mailboxes and the foreach() loop was getting through the first 3 but failing on the 4th. The 4th mailbox was a "Public Folders" store associated to another mailbox that was added in a different way than the rest of the mailboxes (it had something to do with it being an Outlook 365 mailbox that required different authentication).
So essentially it ended up being that any attempt to even touch that particular mailbox/store (including the "store" variable being set) would result in that COM exception.
I was able to work around it by looping through stores via numeric index so that the setting of "store" was inside my try/catch block, like this:
for(int i = 0; i < stores.Count; i++)
{
try
{
Outlook.Store store = stores[i];
...
}
catch(Exception)
{
...
}
}
Now when the loop hit that particular store, I could tell that it was Outlook saying that the server wasn't available, and the store was an online-only store, so the store couldn't be accessed.
I'm still not certain about why the error codes changed each time, but there you have it.

C# Launching another WPF program from a byte array [duplicate]

This question already has answers here:
Load WPF application from the memory
(2 answers)
Closed 6 years ago.
First of all, let me say that I've looked through this, and i still haven't been able to find a great solution to my problem. (I will elaborate in post)
Now to the point.
I have a program which I want to secure with a login.
My setup is as follows:
Login.exe
Application.exe (Gathered from server into byte[])
The user should login, and when successfully logged in, get the server file (Application.exe) and run it, however this file must not be stored locally on the users machine. Instead, this file, which is stored as a byte array, should be launched as a program, but, if possible, not with a location on the harddrive.
Here's how the user would see it:
First they'd get the login application, login and the application
would download the file from server, and execute it.
Now the main problem i've been struggling with is, that whenever i load this byte array, i get the following Exception:
System.Reflection.TargetInvocationException: The destination of an activation triggered an exception. ---> System.InvalidOperationException: Can not create more than one instance of System.Windows.Application in the same AppDomain.
I've tried with multiple ways, but I've always ended up with the following code:
Assembly a = Assembly.Load(tmpbytearray);
MethodInfo method = a.EntryPoint;
if (method != null)
{
object o = a.CreateInstance(method.Name);
method.Invoke(o, null);
}
I've also tried with
Assembly assembly = Assembly.Load(tmpsrc);
//entrypoint: MyMainApplication.App.Main
Type type = assembly.GetType("MyMainApplication.App");
var obj = Activator.CreateInstance(type);
type.InvokeMember("Main",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
But still stuck with the same Exception.
As I've read through the reference (Section B and C) from the top I've also seen the usage of CreateInstanceFromAndUnwrap, but as I can't find a way to supply it with a byte array, instead of a file path, I've decided not to go that way.
Now I'm back to square one, and therefore asking here in my last hopes to sum up a solution to this project.
If i've made some misunderstandings throughout the post, feel free to ask, as I will do my best to be as clear and understandable as possible.
Thanks in advance!
UPDATE (Maybe another approach)
I've now thought of making a small console based application, which would act as a "launcher" for this application. However this also gives an exception:
System.Reflection.TargetInvocationException: The destination of an activation triggered an exception. ---> System.IO.IOException: The resource mainwindow.xaml was not found.
This exception is really weird, as the application itself works when ran. So the following:
Assembly a = Assembly.Load(tmpsrc);
MethodInfo method = a.EntryPoint;
if (method != null)
{
object o = a.CreateInstance(method.Name);
method.Invoke(o, null); //Exception.
}
Depending on what might be the most easy solution, what would you prefer, and how would you think of a possible solution to any of the approaches (The second, or first approach)?
(I cannot mark this as complete, but this question has now been solved)
So, some struggles later, I've finally managed to get this working.
I ended up trying many things, but the solution for me was based on this question.
I took the loader class in my Login Application and added the rest after the login has been authorized successfully:
var domain = AppDomain.CreateDomain("test");
domain.Load("Login");
var loader = (Loader)domain.CreateInstanceAndUnwrap("Login", "Login.Loader");
loader.Load(tmpsrc);
After that it somehow worked, which i'm quite surprised for. But anyways, thanks for the help and pinpoints into the proper subjects!

0xC000027B exception in store UWP app (Windows.UI.XAML)

I've an C#/UWP-app in beta-release in the Microsoft App-Store. Most of the users have no problems with the App, but for one user the app is crashing on startup. You can't even see the Splash-Screen (it should be displaying a logo or color, however it is white).
In the eventlog this genreic event is logged:
0xc000027b (Windows.UI.XAML)
The only difference is, that his Windows-10 Build differs from the other users (10.0.10240 vs 10.0.10586). However, I've collected the crashdumps ("minidumps") and tried to follow this tutorial.
If i try this command:
dt <Parameter[0]> combase!_STOWED_EXCEPTION_INFORMATION_HEADER*
Windbg gives me this:
Memory read error (at Parameter[0])
Actually I've integrated the hockey-sdk for automatic crash-reports, but it doesn't report me that specific crash in the dashboard.
How can I trace down this crash?
Update:
I've managed to get the Call-Stack with PDE:
Windows_UI_Xaml!DirectUI::PropertyPathListener::GetValue+0x3e
Windows_UI_Xaml!DirectUI::BindingExpression::GetValue+0xbb
Windows_UI_Xaml!DirectUI::DependencyObject::SetValueExpression+0x24b
Windows_UI_Xaml!DirectUI::DependencyObject::SetBindingCore+0x56
Windows_UI_Xaml!DirectUI::DependencyObject::SetBindingCallback+0x146
Windows_UI_Xaml!CBinding::SetBinding+0x48
Windows_UI_Xaml!XamlNativeRuntime::SetValue+0x4c2
Windows_UI_Xaml!BinaryFormatObjectWriter::SetValueOnCurrentInstance+0x1ad
Windows_UI_Xaml!BinaryFormatObjectWriter::WriteNode+0x144a
Windows_UI_Xaml!CTemplateContent::LoadXbfVersion2+0xd1
Windows_UI_Xaml!CTemplateContent::Load+0x4d
Windows_UI_Xaml!CFrameworkTemplate::LoadContent+0x270
Windows_UI_Xaml!CControlTemplate::LoadContent+0x18
Windows_UI_Xaml!CFrameworkElement::ApplyTemplate+0x30a
Windows_UI_Xaml!CContentControl::ApplyTemplate+0x20
Windows_UI_Xaml!CFrameworkElement::InvokeApplyTemplate+0x17f
Windows_UI_Xaml!CFrameworkElement::MeasureCore+0x2a3
Windows_UI_Xaml!CUIElement::MeasureInternal+0x1cb
Windows_UI_Xaml!CUIElement::Measure+0x598
Windows_UI_Xaml!CGrid::MeasureOverride+0x307
Windows_UI_Xaml!CFrameworkElement::MeasureCore+0x707
Windows_UI_Xaml!CUIElement::MeasureInternal+0x1cb
Windows_UI_Xaml!CUIElement::Measure+0x598
Windows_UI_Xaml!CGrid::MeasureOverride+0x307
Windows_UI_Xaml!CFrameworkElement::MeasureCore+0x707
This would mean, that I've somewhere an incorrect binding?

Why is PictureBox.Load locking image on some systems?

(Please see the edit on the bottom of the question, if you do not want to read the whole story.)
Hi,
I am new to stackoverflow. Don’t get me wrong, I use it quite often. But up until now I never actually posted something. This is because I did not have something new/useful to say and my English is not that good. The first thing (might have) changed, the latter did not.
I ran into a problem at a customer's Windows 7 system quite recently. I was shipping a C# .Net 4.0 Windows Forms application via ClickOnce. Basically, it is an application that creates a bitmap file and shows it to the user. If the bitmap exists prior to the creation, the existing file gets deleted first. After that the new file is created and loaded by a PictureBox.
The following thing occurred at the customer’s system: After starting the application the first creation succeeds – the second and all following ones do not. The file cannot be deleted, because some process is blocking it. This process is the application itself.
System.IO.IOException: The process cannot access the file “filename” because it is being used by another process.
Well, of course that is nothing unusual. The thing is I tested the application on several systems. None showed this exception. And until now I am unable to see an code error.
So I looked a little bit closer on the customer’s system: The only difference I could find is, that they changed the users folder so that they are not located on the windows partition, but on a different one (C:\Users --> D:\Users). I searched for an instruction on the internet and did the same thing on one of my test systems. To my surprise I got the same exception when I ran my application on it.
With that I could change my code so that the exception does not occur anymore. But I do not understand why that is. So maybe there is something wrong with my code and the error just reveals itself under that special circumstances. Or maybe the code is okay and the reason lies somewhere else. I just hoped that you might be able to help me.
So here is some code I put together, that shows the same behavior. I used 3 buttons, an OpenFileDialog and a PictureBox on a Form. First thing to do is to choose an image file. By pressing one of the two remaining buttons it gets copied into the main folder of the application. After being copied it is shown by the PictureBox. By the way, it does not seem to matter if it is a ClickOnce-application or a “normal” one.
String m_FileName;
private void btnChooseFile_Click(object sender, EventArgs e) {
if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { // If file was chosen, set file name for later use and activate buttons.
m_FileName = "Test" + Path.GetExtension(openFileDialog1.FileName);
}
}
private void button1_Click(object sender, EventArgs e) {
// This is not working.
if(this.pictureBox1.Image != null) {
//Image img = this.pictureBox1.Image; // I was not sure, if maybe the pictureBox somehow prevents the disposing of the image, as long as it's assigned to it.
//this.pictureBox1.ImageLocation = null; // So I set them null, both the image and the image location.
//this.pictureBox1.Image = null;
//img.Dispose(); // Then I disposed the image.
this.pictureBox1.Image.Dispose(); // The short version. It is not working either way.
this.pictureBox1.Image = null;
}
(new FileInfo(openFileDialog1.FileName)).CopyTo(m_FileName, true); // But still this is where the Exception occurs.
this.pictureBox1.Load(m_FileName);
}
private void button2_Click(object sender, EventArgs e) {
//This is working.
if(this.pictureBox1.Image != null) {
//Image img = this.pictureBox1.Image;
//this.pictureBox1.Image = null;
//img.Dispose();
this.pictureBox1.Image.Dispose();
this.pictureBox1.Image = null;
}
(new FileInfo(openFileDialog1.FileName)).CopyTo(m_FileName, true);
pictureBox1.Image = Image.FromFile(m_FileName);
}
What happens now is the following: If I start the application and click button1 twice, I will get the exception (on the second click). If I start it and click button2 twice, I will not. If I start the application and click buttons1 first and after that button2, I will get the exception. So, the Picture.Load-Function somehow blocks the file, even if I dispose it.
When I searched on the internet, I found an article from microsoft: http://support.microsoft.com/kb/309482/en-us. But it does not hit the bull's eye.
Take into account, that both versions are working on all my test machines. I just get the exception when I change the users folder to a non-windows-partition.
Why is that? And where is the difference in the presented versions?
Edit
Okay, because of the first and only reaction so far, it seems to me, that it is still not clear, what really happens: If I take the above code, put it in a Windows Forms application, compile it and run it on different computers (at work, at home, does not matter) it works - both button1 and button2 (with the Click-functions linked to them) can be used as often as I like - no exception thrown. If I run the application on a computer, where I changed the users folder, and click button1 the second time - bam - IOException, file locked by process. Button2 works as long as I do not press button1.
The first answer implies, that I should get the locking on every system. But I DO NOT (as long as I do not change the users folder)! I tested it on every single computer I could get my hands on - no IOException. I set up a new system, just to rule out some special changes to the systems in my company - both buttonx_Click functions worked - no exception either. I even compiled the program on another computer - same behavior. The only three systems to throw that exception were the ones with the changed users folder.
So far I have no clue, why this difference in behavior occurs. Can somebody help me?
Anybody?
Yes, this is normal. Happens on any operating system, doesn't have anything to do with the Users folder location. The PictureBox.Load() method was intented to be used to load images from locations other than the file system. Like a web site. Which is slow, it avoids freezing the UI while the download is taking place.
It internally uses a FileStream when it discovers that the url you pass is actually a file and not a website name. This FileStream does not get disposed until the PictureBox itself is disposed or you call the Load() method again. A requirement because Image.FromStream() requires the stream to remain readable until the image is no longer used. It is this FileStream that keeps a lock on the file. Disposing the PictureBox.Image is not enough to also dispose the FileStream, the Image object doesn't know that it is being displayed inside a picture box.
There are several ways to solve this problem:
Use the Image property instead of Load(), assign it from Image.FromFile(). Disposing the Image now also releases the lock on the file. As you found out
Keep a dummy image around, one that perhaps displays a "Loading..." bitmap. Load() it first to release the lock on the file
Dispose the PictureBox and recreate it.
This works and unlocks the file
Image img= Image.FromFile(mypath);
Graphics g = pictureBox1.CreateGraphics();
g.DrawImage(img,0,0);
img.Dispose();

session value lost in asp.net in c#

hai..
Am doing wepsite for show images from local drive using asp.net.am using session object for Transfer image path from first page to second page
its running nice in vs 2003 .but i converted this website to vs 2005.but session value does't pass to next page.i got null value in session object.
am using inproc session mode
kindly help me
thanks
Your application will probably encounter an error and therefore the session will end. Afterwards a new Session is started. Accessing that value in the new value will return null.
Steps to find your error:
Create the global.asax in your Rootdirectory. Set Breakpoints for Session_OnStart, Session_OnEnd and Application_OnError and try to find where the error lies.
How you are storing the path of images.
See i am doing like this and everything goes file for me.
Session["Path"] = #"D:\Images\PNEUMATIX_MR_CardiovascularHeart Cardiac Function_6\img.jpeg";
on another page i am taking like this.
Label1.Text = Session["Path"].ToString();
And i am using sessionState mode="inProc".
My be you have some problem with path.
http://markmail.org/message/emd3swpsembfplis#query:+page:1+mid:dfdchaihfj7c46j7+state:results
Thanks god this post save my life! IE bugs with _ in the domain name .. they flush all session variable

Categories