public void Enter() { if (this.IsInContext) { return; } this.token = new IntPtr(0); try { this.token = IntPtr.Zero; bool logonSuccessfull = NativeMethods.LogonUser( this.username, this.domain, this.password, Logon32LogonInteractive, Logon32ProviderDefault, ref this.token); if (logonSuccessfull == false) { int error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } var identity = new WindowsIdentity(this.token); this.context = identity.Impersonate(); } catch { // Catch exceptions here } }
public ImpersonationData(IntPtr TokenHandle, IntPtr DupeTokenHandle, WindowsIdentity Identity, WindowsImpersonationContext ImpersonatedUser) { this.TokenHandle = TokenHandle; this.DupeTokenHandle = DupeTokenHandle; this.Identity = Identity; this.ImpersonatedUser = ImpersonatedUser; }
public static void RevertToImpersonatedUser(WindowsImpersonationContext _serviceAccountContext) { if (_serviceAccountContext != null) { _serviceAccountContext.Undo(); } }
public void Impersonate() { Authenticated = false; // Remove the current impersonation by calling RevertToSelf() if (RevertToSelf()) { Authenticated = LogonUserA(_username, _domain, _password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out _handle) != 0; if (!Authenticated) { ErrorCode = Marshal.GetLastWin32Error(); } // Make a copy of the token for the windows identity private member. if (DuplicateToken(this._handle, 2, out this._handleDuplicate) != 0) { // set the private member for the current impersonation context. this._context = WindowsIdentity.Impersonate(this._handleDuplicate.DangerousGetHandle()); } } }
public bool ImpersonateValidUser(String userName, String domain, String password) { System.Security.Principal.WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new System.Security.Principal.WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); return(true); } } } } if (token != IntPtr.Zero) { CloseHandle(token); } if (tokenDuplicate != IntPtr.Zero) { CloseHandle(tokenDuplicate); } _Token = token; return(false); }
public void Enter() { if (this.IsInContext) return; m_Token = new IntPtr(0); try { m_Token = IntPtr.Zero; bool logonSuccessfull = LogonUser( m_Username, m_Domain, m_Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref m_Token); if (logonSuccessfull == false) { int error = Marshal.GetLastWin32Error(); throw new Win32Exception(error); } WindowsIdentity identity = new WindowsIdentity(m_Token); m_Context = identity.Impersonate(); } catch (Exception exception) { // Catch exceptions here } }
public bool ImpersonateAUser(string userName, string domain, string password) { _log.InfoFormat("Impersonating User {0}.", userName); var token = IntPtr.Zero; var duplicateToken = IntPtr.Zero; if (RevertToSelf()) { if (LogonUserA(userName, domain, password, Logon32LogonInteractive, Logon32ProviderDefault, ref token) != 0) { if (DuplicateToken(token, 2, ref duplicateToken) != 0) { _impersonationContext = new WindowsIdentity(duplicateToken).Impersonate(); if (_impersonationContext != null) { CloseHandle(token); CloseHandle(duplicateToken); return true; } } } } if (token != IntPtr.Zero) CloseHandle(token); if (duplicateToken != IntPtr.Zero) CloseHandle(duplicateToken); _log.ErrorFormat("Impersonation for User {0} failed.", userName); return false; }
public bool Impersonate(string userName, string domain, string password) { var token = IntPtr.Zero; var tokenDuplicate = IntPtr.Zero; if(RevertToSelf()) { if(LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out token)) { if(DuplicateToken(token, 2, out tokenDuplicate) != 0) { var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); _impersonationContext = tempWindowsIdentity.Impersonate(); if(_impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); return true; } } } } if(token != IntPtr.Zero) { CloseHandle(token); } if(tokenDuplicate != IntPtr.Zero) { CloseHandle(tokenDuplicate); } return false; }
//public void Page_Load(Object s, EventArgs e) //{ // if (impersonateValidUser("username", "domain", "password")) // { // //Insert your code that runs under the security context of a specific user here. // undoImpersonation(); // } // else // { // //Your impersonation failed. Therefore, include a fail-safe mechanism here. // } //} /// <summary> /// 模擬使用者 /// </summary> /// <param name="userName">使用者名稱</param> /// <param name="domain">網域名稱</param> /// <param name="password">密碼</param> /// <returns>True:模擬成功;False:模擬失敗</returns> public static bool impersonateValidUser(String userName, String domain, String password ) { WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); return true; } } } } if (token != IntPtr.Zero) CloseHandle(token); if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate); return false; }
public void UndoImpersonation(System.Security.Principal.WindowsImpersonationContext user) { if (user != null) { user.Undo(); } }
public PerformanceCounterRetriever(string server, string domain, string user, string password) { if (string.IsNullOrWhiteSpace(server)) throw new ArgumentException($"Null/blank {nameof(server)} specified"); if (string.IsNullOrWhiteSpace(domain)) throw new ArgumentException($"Null/blank {nameof(domain)} specified"); if (string.IsNullOrWhiteSpace(user)) throw new ArgumentException($"Null/blank {nameof(user)} specified"); if (password == null) throw new ArgumentNullException(nameof(password)); try { var userHandle = new IntPtr(0); var logonSuccess = LogonUser(user, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref userHandle); if (!logonSuccess) throw new Exception("LogonUser failed"); _identity = new WindowsIdentity(userHandle); _context = _identity.Impersonate(); _server = server; _disposed = false; } finally { Dispose(); } }
public void Impersonate() { //create identity WindowsIdentity newId = new WindowsIdentity(this.tokenHandle); //start impersonating this.impersonatedUser = newId.Impersonate(); }
/// <summary> /// Constructor. Starts the impersonation with the given credentials. Please note that the account that instantiates the Impersonator class needs to have the 'Act as part of operating system' privilege set. /// </summary> /// <param name="userName"> The name of the user to act as. </param> /// <param name="domainName"> The domain name of the user to act as. </param> /// <param name="password"> The password of the user to act as. </param> public WindowsImpersonatedIdentity(string userName, string domainName, string password) { var token = IntPtr.Zero; var tokenDuplicate = IntPtr.Zero; try { if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(domainName) && string.IsNullOrEmpty(password)) { identity = WindowsIdentity.GetCurrent(); } else { if (LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { identity = new WindowsIdentity(tokenDuplicate); impersonationContext = identity.Impersonate(); } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } finally { if (token != IntPtr.Zero) { CloseHandle(token); } if (tokenDuplicate != IntPtr.Zero) { CloseHandle(tokenDuplicate); } } }
public void Impersonate(string domainName, string userName, string password){ //try { // Use the unmanaged LogonUser function to get the user token for // the specified user, domain, and password. const int LOGON32_PROVIDER_DEFAULT = 0; // Passing this parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; tokenHandle = IntPtr.Zero; // ---- Step - 1 // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser( userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); // tokenHandle - new security token if (false == returnValue){ int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); } // ---- Step - 2 WindowsIdentity newId = new WindowsIdentity(tokenHandle); // ---- Step - 3 { impersonatedUser = newId.Impersonate(); } } }
private Impersonation(string domain, string username, string password, LogonType logonType) { IntPtr handle; var ok = NativeMethods.LogonUser(username, domain, password, (int)logonType, 0, out handle); if (!ok) { var errorCode = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); } var profileInfo = new ProfileInfo(); profileInfo.dwSize = Marshal.SizeOf(profileInfo); profileInfo.lpUserName = username; profileInfo.dwFlags = 1; ok = NativeMethods.LoadUserProfile(handle, ref profileInfo); if (ok == false) { var errorCode = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not load profile. Error code {0}.", errorCode)); } NativeMethods.UnloadUserProfile(handle, profileInfo.hProfile); _handle = new SafeTokenHandle(handle); _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle()); }
/// <summary> /// 사용자를 가장합니다. /// </summary> /// <param name="userName">사용자 이름 입니다.</param> /// <param name="domain">도메인 이름 입니다.</param> /// <param name="password">암호 입니다.</param> /// /// <exception cref="SecurityException">가장이 실패할 경우 <c>SecurityException</c>를 던집니다.</exception> public void Impersonate(string userName, string domain, string password) { WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if (impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); return; } } } } if (token != IntPtr.Zero) CloseHandle(token); if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate); throw new SecurityException("사용자를 가장하는데 실패했습니다."); }
public void Impersonate(string domainName, string userName, string password) { try { const int logon32ProviderDefault = 0; const int logon32LogonInteractive = 2; TokenHandle = IntPtr.Zero; var returnValue = LogonUser( userName, domainName, password, logon32LogonInteractive, logon32ProviderDefault, ref TokenHandle); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); Console.WriteLine("LogonUser call failed with error code : " + ret); throw new System.ComponentModel.Win32Exception(ret); } NewId = new WindowsIdentity(TokenHandle); ImpersonatedUser = NewId.Impersonate(); } catch (Exception ex) { Console.WriteLine("Exception occurred. " + ex.Message); } }
public ImpersonateUser(string userName, string password, string domain) { SecurityPermission secPerm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); secPerm.Assert(); IntPtr token = IntPtr.Zero; bool success = false; string error = "No specific information."; try { if (LogonUser(userName, domain, password, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, ref token)) { WindowsIdentity tempWindowsIdentity = new WindowsIdentity(token, "NTLM", WindowsAccountType.Normal, true); impersonationContext = tempWindowsIdentity.Impersonate(); // actually impersonate the user if (impersonationContext != null) { success = true; } } } catch (Exception e) { error = "ERROR: " + e.Message; } CodeAccessPermission.RevertAssert(); if (!success) { this.Dispose(); throw new Exception("The logon attempt as user " + domain + "\\" + userName + " with password " + password + " failed. " + error); } }
/// <summary> /// Constructor begins impersonation based on user credentials passed in. /// </summary> /// <param name="domain">Windows Domain</param> /// <param name="userName">Windows username</param> /// <param name="password">Windows password</param> public Impersonation(string domain, string userName, string password) { if (!string.IsNullOrEmpty(password)) { _wc = WindowsIdentity.GetCurrent().Impersonate(); ImpersonateValidUser(domain, userName, password); } }
/// <summary> /// Starts the impersonation. /// </summary> public void Impersonate() { // Create Identity. WindowsIdentity newId = new WindowsIdentity(this.tokenHandle); // Start impersonating. this.impersonatedUser = newId.Impersonate(); }
/// <summary> /// Ends impersonation of the WCF client's Windows credentials. /// </summary> public void Dispose() { if (_windowsImpersonationContext != null) { _windowsImpersonationContext.Dispose(); _windowsImpersonationContext = null; } }
public void Impersonate() { // Create the new Identity from the token WindowsIdentity impersonatedID = new WindowsIdentity(this._tokenHandle); // Start impersonating as the new ID this._impersonatedUser = impersonatedID.Impersonate(); }
public void Impersonate() { // authenticates the domain user account and begins impersonating it WindowsIdentity temp = this.Logon(); if (temp != null) { this.impersonationContext = temp.Impersonate(); } }
/// <summary> /// Initializes a new instance of the <see cref="Impersonation"/> class. /// </summary> /// <param name="windowsId">The Windows ID.</param> /// <exception cref="ArgumentNullException" /> public Impersonation(WindowsIdentity windowsId) { if (windowsId == null) { throw new ArgumentNullException("windowsId"); } this.windowsImpersonationContext = windowsId.Impersonate(); }
/// <summary> /// Initializes a new instance of the <see cref="Impersonation"/> class. /// </summary> /// <param name="user">The username.</param> /// <param name="domain">The domain.</param> /// <param name="password">The password.</param> /// <exception cref="BclExtensionsException" /> public Impersonation(string user, string domain, string password) { WindowsIdentity windowsIdentity = MySafeLogonHandle.Logon(user, domain, password); if (windowsIdentity == null) { throw new BclExtensionsException("Logon failed with the given credentials."); } this.windowsImpersonationContext = windowsIdentity.Impersonate(); }
public ImpersonateUser(string userAndDomanName, string password) { string userName = string.Empty; string domainName = string.Empty; if (userAndDomanName.Contains("\\") == true) { domainName = userAndDomanName.Split('\\')[0]; userName = userAndDomanName.Split('\\')[1]; } else { userName = userAndDomanName; } // Use the unmanaged LogonUser function to get the user token for // the specified user, domain, and password. // To impersonate a user on this machine, use the local machine // name for the domain name. const int LOGON32_PROVIDER_DEFAULT = 0; // Passing this parameter causes LogonUser to create a primary // token. const int LOGON32_LOGON_INTERACTIVE = 2; _tokenHandle = IntPtr.Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser( userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref _tokenHandle); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); } _duplicateTokenHandle = IntPtr.Zero; returnValue = DuplicateToken(_tokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref _duplicateTokenHandle); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); } WindowsIdentity newId = new WindowsIdentity(_duplicateTokenHandle); _impersonatedUser = newId.Impersonate(); _isImpersonating = true; }
public bool ImpersonateValidUser(String userName, String domain, String password) { if (!Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["isImpersonate"])) { return true; } bool isImpersonated = false; WindowsIdentity tempWindowsIdentity; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; try { if (RevertToSelf()) { if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); _impersonationContext = tempWindowsIdentity.Impersonate(); if (_impersonationContext != null) { CloseHandle(token); CloseHandle(tokenDuplicate); isImpersonated = true; return isImpersonated; } } } else { //TODO - log on error //int ret = Marshal.GetLastWin32Error(); //Console.WriteLine("LogonUser failed with error code : {0}", ret); } } } catch (Exception ex) { ErrorCode = Marshal.GetLastWin32Error(); this.Exception = ex; } finally { if (token != IntPtr.Zero) CloseHandle(token); if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate); } return isImpersonated; }
private void UseAppPoolIdentity() { try { if (!WindowsIdentity.GetCurrent().IsSystem) { _ctx = WindowsIdentity.Impersonate(IntPtr.Zero); } } catch { } }
/// <summary> /// Initializes impersonation of the WCF client's Windows credentials, if possible. /// </summary> public ServiceClientImpersonationContext() { try { var securityContext = ServiceSecurityContext.Current; _windowsImpersonationContext = securityContext != null && securityContext.WindowsIdentity != null ? securityContext.WindowsIdentity.Impersonate() : null; } catch (Exception ex) { Platform.Log(LogLevel.Warn, ex, "Exception thrown when accessing the security context of the service call for identity impersonation."); } }
public void Dispose() { if (_impersonationContext != null) { Debug.Assert(!string.IsNullOrEmpty(_impersonatedUser), "if we were impersonating, there should have been a user name"); _impersonationContext.Undo(); _impersonationContext = null; } GC.SuppressFinalize(this); }
private void Impersonate() { Authenticated = LogonUser(_username, _domain, _password, LOGON32_LOGON_NETWORK/*LOGON32_LOGON_NEW_CREDENTIALS*/, LOGON32_PROVIDER_DEFAULT, out this._handle); if (!Authenticated) { ErrorCode = Marshal.GetLastWin32Error(); } this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle()); }
public Impersonation(string domain, string username, string password) { var ok = LogonUser(username, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle); if (!ok) { var errorCode = Marshal.GetLastWin32Error(); throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode)); } this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle()); }
public void Authenticate() { // this might use new WindowsIdentity(upn) or LogonUser WindowsIdentity identity = WindowsIdentity.GetCurrent(); context = identity.Impersonate(); // simulate a WindowsPrincipal GenericPrincipal principal = new GenericPrincipal(new GenericIdentity(Identity), new string[] {}); Thread.CurrentPrincipal = principal; }
public void UndoImpersonation() { if (this.context != null) { this.context.Undo(); this.context = null; } if (this.selfContext != null) { this.selfContext.Undo(); this.selfContext = null; } }
//public Boolean isImpersonated() //{ return (impersonationContext != null); } private void Leave() { _isImpersonated = false; if (impersonationContext != null) { impersonationContext.Undo(); } if (_Token != IntPtr.Zero) { CloseHandle(_Token); } impersonationContext = null; }
protected bool impersonate_valid_user(string userName, string domain, string password) { WindowsIdentity tempWindowsIdentity; System.IntPtr token = System.IntPtr.Zero; System.IntPtr tokenDuplicate = System.IntPtr.Zero; if (NativeMethods.RevertToSelf()) { if (NativeMethods.LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token ) != 0) { if (NativeMethods.DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); m_impersonation_context = tempWindowsIdentity.Impersonate(); if (m_impersonation_context != null) { NativeMethods.CloseHandle(token); NativeMethods.CloseHandle(tokenDuplicate); return(true); } } } } if (token != System.IntPtr.Zero) { NativeMethods.CloseHandle(token); } if (tokenDuplicate != System.IntPtr.Zero) { NativeMethods.CloseHandle(tokenDuplicate); } return(false); }
public static void ErrorLog(string LogStr, EventLogEntryType Type) { try { System.Security.Principal.WindowsImpersonationContext wic = WindowsIdentity.Impersonate(IntPtr.Zero); var El = new EventLog(); if (EventLog.SourceExists("ITXProjectGovernanceReport") == false) { EventLog.CreateEventSource("ITXProjectGovernanceReport", "ITXProjectGovernanceReport"); } El.Source = "ITXProjectGovernanceReport"; El.WriteEntry(LogStr, Type); El.Close(); wic.Undo(); } catch (Exception Ex87) { WriteTextLog(Ex87.Message + "\r" + LogStr); } }
void HTTPListener() { Console.WriteLine($"[+] Starting HTTP listener on port http://{host}:{port}"); HttpListener listener = new HttpListener(); listener.Prefixes.Add($"http://{host}:{port}/"); listener.Start(); listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication; listener.UnsafeConnectionNtlmAuthentication = true; listener.IgnoreWriteExceptions = true; readyEvent.Set(); HttpListenerContext context = listener.GetContext(); Console.WriteLine("Request for: " + context.Request.Url.LocalPath); Console.WriteLine("Client: " + context.User.Identity.Name); var identity = (System.Security.Principal.WindowsIdentity)context.User.Identity; using (System.Security.Principal.WindowsImpersonationContext wic = identity.Impersonate()) { if (!ImpersonationToken.OpenThreadToken(ImpersonationToken.GetCurrentThread(), ImpersonationToken.TOKEN_ALL_ACCESS, false, out var tokenHandle)) { Console.WriteLine("[-] Failed to open thread token"); return; } if (!ImpersonationToken.DuplicateTokenEx(tokenHandle, ImpersonationToken.TOKEN_ALL_ACCESS, IntPtr.Zero, ImpersonationToken.SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ImpersonationToken.TOKEN_TYPE.TokenPrimary, out systemImpersonationToken)) { Console.WriteLine("[-] Failed to duplicate impersonation token"); return; } Console.WriteLine("[+] Duplicated impersonation token ready for process creation"); } readyEvent.Set(); }
public static Boolean isImpersonated(System.Security.Principal.WindowsImpersonationContext Context) { return(Context != null); }
public ComparerResult DoComparison(IPrincipal principal, ComparerArguments arguments) { ComparerResult cResult = new ComparerResult(); try { /* Impersonation for connect to WCF using ASP.net Authenticated User */ System.Security.Principal.WindowsImpersonationContext impersonationContext = ((System.Security.Principal.WindowsIdentity)principal.Identity).Impersonate(); ComparerClient cc = GetComparerClient(); /* Uploaded files should be readed by ISS Application Pool User */ impersonationContext.Undo(); byte[] original = System.IO.File.ReadAllBytes(Path.Combine(UploadPath, arguments.OriginalDoc.ServerName)); // string resultPath = System.IO.Directory.GetParent(arguments.OriginalDoc.ServerName).FullName; foreach (ServerFile file in arguments.ModifiedDoc) { ComparisonResult result = new ComparisonResult(); CompareResults cr; try { result.File = file.ClientName; byte[] modified = System.IO.File.ReadAllBytes(Path.Combine(UploadPath, file.ServerName)); string sOptionSet = System.IO.File.ReadAllText(arguments.RenderingSet); Log.Write(TraceEventType.Information, "Comparing {0} and {1} files", arguments.OriginalDoc.ClientName, file.ClientName); var executeParams = new ExecuteParams() { CompareOptions = sOptionSet, Original = original, Modified = modified, ResponseOption = arguments.OutputFormat, OriginalDocumentInfo = CreateDocInfo(arguments.OriginalDoc.ClientName), ModifiedDocumentInfo = CreateDocInfo(file.ClientName) }; cr = cc.ExecuteEx(executeParams); if (cr != null) { string fileName = System.IO.Path.GetFileNameWithoutExtension(result.File); if (cr.Redline != null) { result.Redline = storeFileOnServer(cr.Redline, fileName + ".redline." + getExtension(arguments.OutputFormat)); } if (!string.IsNullOrEmpty(cr.RedlineMl)) { result.RedlineMl = storeFileOnServer(cr.RedlineMl, fileName + ".redlineml.xml"); } if (!string.IsNullOrEmpty(cr.Summary)) { result.Summary = storeFileOnServer(cr.Summary, fileName + ".summary.xml"); } } else { Log.Write(TraceEventType.Error, "Null result"); result.Error = "No results"; } } catch (System.Security.SecurityException ex) { Log.Write(TraceEventType.Error, "{0}", ex); result.Error = "Security Error: " + ex.Message; } catch (FileNotFoundException ex) { Log.Write(TraceEventType.Error, "{0}", ex); result.Error = "File not found on server"; } catch (Exception ex) { Log.Write(TraceEventType.Error, "{0}", ex); result.Error = ex.Message; } cResult.Comperisons.Add(result); } checkTimeOutFiles(); } catch (System.ServiceModel.ServerTooBusyException ex) { cResult.Errors.Add("Server Too Busy"); Log.Write(TraceEventType.Error, "{0}", ex); } catch (TimeoutException ex) { cResult.Errors.Add("Faild to connect to server (Timeout)"); Log.Write(TraceEventType.Error, "{0}", ex); } catch (System.ServiceModel.FaultException ex) { cResult.Errors.Add("FaultException: " + ex.Message); Log.Write(TraceEventType.Error, "{0}", ex); } catch (System.ServiceModel.CommunicationException ex) { if (ex.Message.Contains("request is unauthorized")) { cResult.Errors.Add(@"Unauthorized issue arised, please check User Name and/or Password and/or domain!"); } else { cResult.Errors.Add("CommunicationException: " + ex.Message); } Log.Write(TraceEventType.Error, "{0}", ex); } catch (FileNotFoundException ex) { Log.Write(TraceEventType.Error, "{0}", ex); throw new Exception("Original file not found on server"); } catch (Exception ex) { ComparerResult result = new ComparerResult(); cResult.Errors.Add(ex.Message); Log.Write(TraceEventType.Error, "{0}", ex); } return(cResult); }