Example #1
0
        private static PowerShellResults <T> GetProgressImpl <T>(string progressId, out AsyncServiceManager.WorkItem workItem)
        {
            PowerShellResults <T> powerShellResults = new PowerShellResults <T>();

            workItem = null;
            if (!string.IsNullOrEmpty(progressId) && AsyncServiceManager.workItems.TryGetValue(progressId, out workItem))
            {
                lock (workItem)
                {
                    if (workItem.Results != null)
                    {
                        PowerShellResults <T> powerShellResults2 = workItem.Results as PowerShellResults <T>;
                        if (powerShellResults2 != null)
                        {
                            powerShellResults = powerShellResults2;
                        }
                        else
                        {
                            powerShellResults.MergeErrors(workItem.Results);
                        }
                        AsyncServiceManager.workItems.Remove(progressId);
                        workItem.FinishedEvent.Close();
                    }
                    else
                    {
                        ProgressRecord progressRecord = null;
                        if (workItem.LegacyProgressRecord != null)
                        {
                            progressRecord = workItem.LegacyProgressRecord;
                        }
                        else
                        {
                            ProgressRecord progressRecord2 = (workItem.ProgressCalculator == null) ? new ProgressRecord() : workItem.ProgressCalculator.ProgressRecord;
                            lock (progressRecord2.SyncRoot)
                            {
                                progressRecord = new ProgressRecord
                                {
                                    Errors         = progressRecord2.Errors,
                                    FailedCount    = progressRecord2.FailedCount,
                                    MaxCount       = progressRecord2.MaxCount,
                                    Percent        = progressRecord2.Percent,
                                    Status         = progressRecord2.Status,
                                    SucceededCount = progressRecord2.SucceededCount,
                                    HasCompleted   = progressRecord2.HasCompleted,
                                    IsCancelled    = progressRecord2.IsCancelled
                                };
                                progressRecord2.Errors = null;
                            }
                        }
                        powerShellResults.ProgressRecord = progressRecord;
                    }
                }
            }
            DDIHelper.Trace("GetProgress: {0}, Results: {1}", new object[]
            {
                progressId,
                powerShellResults
            });
            return(powerShellResults);
        }
Example #2
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            StaticBinding staticBinding = new StaticBinding();

            staticBinding.Name = "IsCrossPremise";
            if (string.IsNullOrEmpty(base.Request.QueryString["xprs"]))
            {
                foreach (ColumnHeader columnHeader in this.pickerContent.Columns)
                {
                    if (columnHeader.Name == "RecipientTypeName")
                    {
                        this.pickerContent.Columns.Remove(columnHeader);
                        break;
                    }
                }
                staticBinding.Value = "false";
            }
            else
            {
                staticBinding.Value = "true";
            }
            this.pickerContent.FilterParameters.Add(staticBinding);
            if (DDIHelper.IsFFO())
            {
                base.Title = Strings.MasterAccountPickerTitle;
            }
        }
        protected void ResolveServiceUrl()
        {
            string name = "sn";
            string text = this.Context.Request.QueryString[name];

            if (!string.IsNullOrWhiteSpace(text))
            {
                DDIHelper.CheckSchemaName(text);
                base.ServiceUrl = new WebServiceReference(EcpUrl.EcpVDirForStaticResource + "DDI/DDIService.svc?schema=" + text);
            }
        }
Example #4
0
        public static void RegisterPowerShellToActivity(PowerShell powerShell, CmdletActivity activity, IEnumerable pipelineInput, out List <PSObject> psDataCollection, bool isGetListAsync)
        {
            psDataCollection = null;
            int managedThreadId = Thread.CurrentThread.ManagedThreadId;

            if (AsyncServiceManager.workerThreads.Contains(managedThreadId))
            {
                AsyncServiceManager.WorkItem workItem = (AsyncServiceManager.WorkItem)AsyncServiceManager.workerThreads[managedThreadId];
                lock (workItem)
                {
                    workItem.ProgressCalculator.SetPipelineInput(pipelineInput);
                    workItem.PowerShell = powerShell;
                    if (isGetListAsync && workItem.AsyncGetListContext.PsObjectCollection == null)
                    {
                        psDataCollection = new List <PSObject>(DDIHelper.GetListDefaultResultSize * 2);
                        workItem.AsyncGetListContext.PsObjectCollection = psDataCollection;
                    }
                }
                if (powerShell != null)
                {
                    powerShell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e)
                    {
                        ProgressRecord progressRecord = ((PSDataCollection <ProgressRecord>)sender)[e.Index];
                        if (isGetListAsync)
                        {
                            AsyncServiceManager.OnProgress(workItem, progressRecord);
                            return;
                        }
                        List <ErrorRecord> list = new List <ErrorRecord>();
                        if (AsyncServiceManager.IsCurrentWorkBulkEdit())
                        {
                            Collection <ErrorRecord> collection = powerShell.Streams.Error.ReadAll();
                            foreach (ErrorRecord errorRecord in collection)
                            {
                                list.Add(new ErrorRecord(errorRecord));
                            }
                        }
                        string status = (progressRecord.RecordType != ProgressRecordType.Completed) ? progressRecord.StatusDescription : string.Empty;
                        ProgressReportEventArgs progressReportEventArgs = new ProgressReportEventArgs(list, progressRecord.PercentComplete, status);
                        DDIHelper.Trace("Async Progress Id: {0},  ProgressReportEventArgs: {1}", new object[]
                        {
                            workItem.Id,
                            progressReportEventArgs
                        });
                        activity.OnPSProgressReport(progressReportEventArgs);
                    };
                }
            }
        }
        void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            string value = DiagnosticsBehavior.GetErrorCause(error) ?? error.GetType().FullName;

            EcpPerfCounters.WebServiceErrors.Increment();
            EcpEventLogConstants.Tuple_WebServiceFailed.LogPeriodicFailure(EcpEventLogExtensions.GetUserNameToLog(), HttpContext.Current.GetRequestUrlForLog(), error, EcpEventLogExtensions.GetFlightInfoForLog());
            ExTraceGlobals.EventLogTracer.TraceError <string, EcpTraceFormatter <Exception> >(0, 0L, "{0}'s webservice request failed with exception: {1}", EcpEventLogExtensions.GetUserNameToLog(), error.GetTraceFormatter());
            HttpContext.Current.Response.AddHeader("X-ECP-ERROR", value);
            DDIHelper.Trace("Webservice request failed with exception: {0}", new object[]
            {
                error.GetTraceFormatter()
            });
            if (fault != null && version == MessageVersion.None)
            {
                MessageProperties properties = fault.Properties;
                fault = Message.CreateMessage(version, string.Empty, new JsonFaultDetail(error), new DataContractJsonSerializer(typeof(JsonFaultDetail)));
                fault.Properties.CopyProperties(properties);
            }
        }
        private static void Application_Error(object sender, EventArgs e)
        {
            HttpContext httpContext = HttpContext.Current;
            Exception   ex          = httpContext.GetError();

            ExTraceGlobals.EventLogTracer.TraceError <EcpTraceFormatter <Exception> >(0, 0L, "Application Error: {0}", ex.GetTraceFormatter());
            DDIHelper.Trace("Application Error: {0}", new object[]
            {
                ex.GetTraceFormatter()
            });
            EcpPerfCounters.AspNetErrors.Increment();
            EcpEventLogConstants.Tuple_RequestFailed.LogPeriodicFailure(EcpEventLogExtensions.GetUserNameToLog(), httpContext.GetRequestUrlForLog(), ex, EcpEventLogExtensions.GetFlightInfoForLog());
            RbacPrincipal current    = RbacPrincipal.GetCurrent(false);
            string        tenantName = string.Empty;

            if (current != null)
            {
                OrganizationId organizationId = current.RbacConfiguration.OrganizationId;
                if (organizationId != null && organizationId.OrganizationalUnit != null)
                {
                    tenantName = organizationId.OrganizationalUnit.Name;
                }
            }
            ActivityContextLogger.Instance.LogEvent(new PeriodicFailureEvent(ActivityContext.ActivityId.FormatForLog(), tenantName, httpContext.GetRequestUrlForLog(), ex, EcpEventLogExtensions.GetFlightInfoForLog()));
            ActivityContextManager.CleanupActivityContext(httpContext);
            if (ex is DelegatedSecurityTokenExpiredException)
            {
                ErrorHandlingModule.HandleDelegatedSecurityTokenExpire(httpContext);
                return;
            }
            if (httpContext.IsWebServiceRequest())
            {
                string errorCause = DiagnosticsBehavior.GetErrorCause(ex);
                ErrorHandlingUtil.SendReportForCriticalException(httpContext, ex);
                ErrorHandlingModule.SendJsonError(httpContext, ex, errorCause);
                return;
            }
            if (httpContext.IsUploadRequest())
            {
                ErrorHandlingUtil.SendReportForCriticalException(httpContext, ex);
                ErrorHandlingModule.SendJsonErrorForUpload(httpContext, ex);
                return;
            }
            if (ex is HttpException && ex.InnerException != null)
            {
                ex = ex.InnerException;
            }
            httpContext.Request.ServerVariables["X-ECP-ERROR"] = ex.GetType().FullName;
            string text  = null;
            string text2 = null;

            if (ex is OverBudgetException)
            {
                text = "overbudget";
            }
            else if (ex is IdentityNotMappedException || ex is TransientException)
            {
                text = "transientserviceerror";
            }
            else if (ex is ObjectNotFoundException)
            {
                if (ex.InnerException is NonUniqueRecipientException)
                {
                    text = "nonuniquerecipient";
                }
                else
                {
                    text = "nonmailbox";
                }
            }
            else if (ex is ServerNotInSiteException || ex is LowVersionUserDeniedException)
            {
                text = "lowversion";
            }
            else if (ex is CmdletAccessDeniedException || ex is DelegatedAccessDeniedException)
            {
                text = "noroles";
            }
            else if (ex is UrlNotFoundOrNoAccessException)
            {
                text = "urlnotfoundornoaccess";
            }
            else if (ex is BadRequestException)
            {
                text = "badrequest";
            }
            else if (ex is BadQueryParameterException)
            {
                text = "badqueryparameter";
            }
            else if (ex is ProxyFailureException)
            {
                text = "transientserviceerror";
            }
            else if (ex is ProxyCantFindCasServerException)
            {
                text = "proxy";
            }
            else if (ex is CasServerNotSupportEsoException)
            {
                text = "noeso";
            }
            else if (ex is RegionalSettingsNotConfiguredException)
            {
                text = "regionalsettingsnotconfigured";
            }
            else if (ex is SecurityException || (ErrorHandlingUtil.KnownReflectedExceptions.Value.ContainsKey("Microsoft.Exchange.Hygiene.Security.Authorization.NoValidRolesAssociatedToUserException, Microsoft.Exchange.Hygiene.Security.Authorization") && ex.GetType() == ErrorHandlingUtil.KnownReflectedExceptions.Value["Microsoft.Exchange.Hygiene.Security.Authorization.NoValidRolesAssociatedToUserException, Microsoft.Exchange.Hygiene.Security.Authorization"]))
            {
                text = "noroles";
            }
            else if (ex is ExchangeConfigurationException)
            {
                text = "anonymousauthenticationdisabled";
            }
            else if (ex is CannotAccessOptionsWithBEParamOrCookieException)
            {
                text = "cannotaccessoptionswithbeparamorcookie";
            }
            else if (ex.IsMaxRequestLengthExceededException())
            {
                EcpPerfCounters.RedirectToError.Increment();
                text2 = httpContext.Request.AppRelativeCurrentExecutionFilePath;
            }
            else
            {
                ErrorHandlingUtil.SendReportForCriticalException(httpContext, ex);
                if (!ErrorHandlingUtil.ShowIisNativeErrorPage && !ex.IsInterestingHttpException())
                {
                    text = "unexpected";
                }
            }
            if (text2 != null)
            {
                httpContext.Server.Transfer(text2, true);
                return;
            }
            if (text != null)
            {
                ErrorHandlingModule.TransferToErrorPage(text, ErrorHandlingUtil.CanShowDebugInfo(ex));
            }
        }
Example #7
0
        private static PowerShellResults InvokeAsyncCore(Func <PowerShellResults> callback, Action <PowerShellResults> onCompleted, string uniqueUserIdentity, AsyncServiceManager.AsyncTaskBudgetManager asyncTaskBudget, string commandStringForTrace, ThrottlingType throttlingType)
        {
            if (string.IsNullOrEmpty(uniqueUserIdentity))
            {
                throw new ArgumentNullException("uniqueUserIdentity cannot be null.");
            }
            AsyncServiceManager.AsyncTaskThrottlingStatus asyncTaskThrottlingStatus = asyncTaskBudget.RegisterAsyncTask(uniqueUserIdentity, commandStringForTrace, throttlingType);
            if (asyncTaskThrottlingStatus != AsyncServiceManager.AsyncTaskThrottlingStatus.None)
            {
                LocalizedString value = (asyncTaskThrottlingStatus == AsyncServiceManager.AsyncTaskThrottlingStatus.PerAppThrottlingHit) ? Strings.LongRunPerAppThrottlingHit : Strings.LongRunPerUserThrottlingHit;
                asyncTaskBudget.UnregisterAsyncTask(uniqueUserIdentity, throttlingType);
                return(new PowerShellResults
                {
                    ErrorRecords = new ErrorRecord[]
                    {
                        new ErrorRecord(new InvalidOperationException(value))
                    }
                });
            }
            AsyncServiceManager.WorkItem workItem = new AsyncServiceManager.WorkItem(Guid.NewGuid().ToString());
            AsyncServiceManager.workItems[workItem.Id] = workItem;
            CultureInfo      currentCulture          = CultureInfo.CurrentCulture;
            IPrincipal       currentPrincipal        = Thread.CurrentPrincipal;
            OperationContext currentOperationContext = OperationContext.Current;
            HttpContext      currentHttpContext      = HttpContext.Current;

            commandStringForTrace = ((commandStringForTrace == null) ? string.Empty : commandStringForTrace);
            RbacPrincipal rbacSession = RbacPrincipal.GetCurrent(false);

            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                int managedThreadId = Thread.CurrentThread.ManagedThreadId;
                AsyncServiceManager.WorkItem workItem;
                AsyncServiceManager.workerThreads[managedThreadId] = workItem;
                CultureInfo currentCulture          = CultureInfo.CurrentCulture;
                IPrincipal currentPrincipal         = Thread.CurrentPrincipal;
                OperationContext value2             = OperationContext.Current;
                HttpContext value3                  = HttpContext.Current;
                Thread.CurrentThread.CurrentCulture = (Thread.CurrentThread.CurrentUICulture = currentCulture);
                Thread.CurrentPrincipal             = currentPrincipal;
                OperationContext.Current            = currentOperationContext;
                HttpContext.Current                 = AsyncServiceManager.CloneHttpContextForLongRunningThread(currentHttpContext);
                ActivityContextManager.InitializeActivityContext(HttpContext.Current, ActivityContextLoggerId.LongRunning);
                PowerShellResults powerShellResults = null;
                try
                {
                    EcpEventLogConstants.Tuple_AsyncWebRequestStarted.LogEvent(new object[]
                    {
                        uniqueUserIdentity,
                        managedThreadId,
                        commandStringForTrace
                    });
                    powerShellResults = callback();
                    object obj        = AsyncServiceManager.workerThreads[managedThreadId];
                }
                catch (Exception exception)
                {
                    powerShellResults = new PowerShellResults();
                    powerShellResults.ErrorRecords = new ErrorRecord[]
                    {
                        new ErrorRecord(exception)
                    };
                    EcpEventLogConstants.Tuple_AsyncWebRequestFailed.LogEvent(new object[]
                    {
                        uniqueUserIdentity,
                        managedThreadId,
                        exception.GetTraceFormatter(),
                        commandStringForTrace
                    });
                    ErrorHandlingUtil.SendReportForCriticalException(currentHttpContext, exception);
                    DDIHelper.Trace("Async work item {0}, Error: {1}", new object[]
                    {
                        workItem.Id,
                        exception.GetTraceFormatter()
                    });
                }
                finally
                {
                    AsyncServiceManager.workerThreads.Remove(managedThreadId);
                    lock (workItem)
                    {
                        workItem.Results = powerShellResults;
                        ProgressRecord progressRecord    = workItem.LegacyProgressRecord ?? ((workItem.ProgressCalculator == null) ? new ProgressRecord() : workItem.ProgressCalculator.ProgressRecord);
                        powerShellResults.ProgressRecord = progressRecord;
                        progressRecord.HasCompleted      = true;
                        progressRecord.IsCancelled       = workItem.Cancelled;
                        workItem.FinishedEvent.Set();
                    }
                    asyncTaskBudget.UnregisterAsyncTask(uniqueUserIdentity, throttlingType);
                    if (onCompleted != null)
                    {
                        onCompleted(powerShellResults);
                    }
                    EcpEventLogConstants.Tuple_AsyncWebRequestEnded.LogEvent(new object[]
                    {
                        uniqueUserIdentity,
                        managedThreadId,
                        commandStringForTrace
                    });
                    ActivityContextManager.CleanupActivityContext(HttpContext.Current);
                    Thread.CurrentThread.CurrentCulture = (Thread.CurrentThread.CurrentUICulture = currentCulture);
                    Thread.CurrentPrincipal             = currentPrincipal;
                    OperationContext.Current            = value2;
                    HttpContext.Current = value3;
                    GC.KeepAlive(rbacSession);
                }
            });
            return(new PowerShellResults
            {
                ProgressId = workItem.Id
            });
        }