Exemple #1
0
 private static void StartPerfmonCollectionLoop()
 {
     var counters = new PerformanceCounters("");
     var syslogForwarder = new UdpClient();
     syslogForwarder.Connect(ConfigurationManager.AppSettings["forward_host"], int.Parse(ConfigurationManager.AppSettings["forward_port"]));
     var sw = Stopwatch.StartNew();
     while (true)
     {
         sw.Restart();
         foreach (var counter in counters)
         {
             var nextValue = counter.NextValue();
             var timestamp = DateTime.Now;
             var datagram = GetSyslogDatagram(counter, nextValue, timestamp);
             var bytesSend = syslogForwarder.Send(datagram, datagram.Length);
             log.Debug("Sending " + datagram.Length + " bytes");
             if (bytesSend != datagram.Length)
             {
                 log.ErrorFormat("bytes sent " + bytesSend + " does not equal datagram length " + datagram.Length);
             }
         }
         sw.Stop();
         log.Info(string.Format("Queried {0} counters in {1} ms", counters.Count, sw.Elapsed.TotalMilliseconds));
         Thread.Sleep(10 * 1000);
     }
 }
        internal EvalOperation(OnlineTrainerSettingsInternal settings, PerformanceCounters performanceCounters)
        {
            this.performanceCounters = performanceCounters;

            this.telemetry = new TelemetryClient();

            // evaluation pipeline
            this.evalEventHubClient = EventHubClient.CreateFromConnectionString(settings.EvalEventHubConnectionString);

            this.evalBlock = new TransformManyBlock<object, EvalData>(
                (Func<object, IEnumerable<EvalData>>)this.OfflineEvaluate,
                new ExecutionDataflowBlockOptions
                {
                    MaxDegreeOfParallelism = 4,
                    BoundedCapacity = 1024
                });

            this.evalBlock.Completion.Trace(this.telemetry, "Stage 4 - Evaluation pipeline");

            // batch output together to match EventHub throughput by maintaining maximum latency of 1 seconds
            this.evalBlockDisposable = this.evalBlock.AsObservable()
                .GroupBy(k => k.PolicyName)
                   .Select(g =>
                        g.Window(TimeSpan.FromSeconds(1))
                         .Select(w => w.Buffer(245 * 1024, e => Encoding.UTF8.GetByteCount(e.JSON)))
                         .SelectMany(w => w)
                         .Subscribe(this.UploadEvaluation))
                   .Publish()
                   .Connect();
        }
        public PerfMonitorForm( IAppServer server )
        {
            InitializeComponent();

            var couners = new PerformanceCounters( server );
            couners.StatUpdated += StatUpdated;
            Presenter = new PerfMonitorFormPresenter( couners );
            perfMonitorFormPresenterBindingSource.DataSource = Presenter;
        }
        private void StandardPage_Loaded(object sender, RoutedEventArgs e)
        {
            sw.Stop();

            long counter = sw.ElapsedMilliseconds;

            string pageName = this.ToString().Substring(this.ToString().LastIndexOf(".") + 1);

            PerformanceCounters.AddPerformanceCounter(new PagePerformanceCounter(pageName, GameObject.GetInstance().GameTime, counter));
        }
 protected override void OnFaulted()
 {
     this.session.OnFaulted();
     this.UnblockClose();
     base.OnFaulted();
     if (PerformanceCounters.PerformanceCountersEnabled)
     {
         PerformanceCounters.SessionFaulted(this.perfCounterId);
     }
 }
Exemple #6
0
 public static void PoisonMessageMoved(string messageId, bool poisonQueue, string uri)
 {
     if (DiagnosticUtility.ShouldTraceWarning)
     {
         TraceUtility.TraceEvent(TraceEventType.Warning, poisonQueue ? 0x40060 : 0x40061, poisonQueue ? System.ServiceModel.SR.GetString("TraceCodeMsmqPoisonMessageMovedPoison") : System.ServiceModel.SR.GetString("TraceCodeMsmqPoisonMessageMovedRetry"), new StringTraceRecord("MSMQMessageId", messageId), null, null);
     }
     if (poisonQueue && PerformanceCounters.PerformanceCountersEnabled)
     {
         PerformanceCounters.MsmqPoisonMessage(uri);
     }
 }
Exemple #7
0
 public static void PoisonMessageRejected(string messageId, string uri)
 {
     if (DiagnosticUtility.ShouldTraceWarning)
     {
         TraceUtility.TraceEvent(TraceEventType.Warning, 0x40062, System.ServiceModel.SR.GetString("TraceCodeMsmqPoisonMessageRejected"), new StringTraceRecord("MSMQMessageId", messageId), null, null);
     }
     if (PerformanceCounters.PerformanceCountersEnabled)
     {
         PerformanceCounters.MsmqPoisonMessage(uri);
     }
 }
            /// <summary>
            /// Creates a new kernel accountant reporting its measurement to the specified <paramref name="parent"/>.
            /// </summary>
            /// <param name="parent">The parent performance counters object to report the measurement to.</param>
            public KernelAccountant(PerformanceCounters parent)
            {
                _parent = parent;

                if (!NativeMethods.TryGetThreadCycleTime(out _cycles))
                {
                    _cycles = 0UL;
                }

                _start = Stopwatch.GetTimestamp();
            }
Exemple #9
0
 // Token: 0x060002C7 RID: 711 RVA: 0x00012830 File Offset: 0x00010A30
 public override void Validate(X509Certificate2 certificate)
 {
     try
     {
         X509CertificateValidator.ChainTrust.Validate(certificate);
     }
     catch (SecurityTokenValidationException)
     {
         PerformanceCounters.UpdateCertAuthRequestsFailed(HttpContext.Current.Request.UserAgent);
         throw;
     }
 }
 public override void Rollback(Enlistment enlistment)
 {
     if (PerformanceCounters.PerformanceCountersEnabled)
     {
         PerformanceCounters.TxAborted(this.endpointDispatcher, this.CallCount);
     }
     if (DiagnosticUtility.ShouldTraceInformation)
     {
         TraceUtility.TraceEvent(TraceEventType.Information, 0xe000d, System.ServiceModel.SR.GetString("TraceCodeTxAsyncAbort", new object[] { base.Transaction.TransactionInformation.LocalIdentifier }));
     }
     base.Rollback(enlistment);
 }
        static PerformanceHandler()
        {
            List <CounterConfig> pCounterInfos = new List <CounterConfig>
            {
                new CounterConfig("Network Interface", "Bytes Received/sec", CustomType.Download, NetFunc),
                new CounterConfig("Network Interface", "Bytes Sent/sec", CustomType.Upload, NetFunc),
            };

            pCounters             = new PerformanceCounters(pCounterInfos, 1000);
            pCounters.ReciveData += PCounters_ReciveData;
            pCounters.Start();
        }
 internal RemoveReferenceRM(InstanceContext instanceContext, Transaction tx, string operation) : base(instanceContext, tx)
 {
     this.operation = operation;
     if (PerformanceCounters.PerformanceCountersEnabled)
     {
         this.endpointDispatcher = PerformanceCounters.GetEndpointDispatcher();
     }
     AspNetEnvironment.Current.IncrementBusyCount();
     if (AspNetEnvironment.Current.TraceIncrementBusyCountIsEnabled())
     {
         AspNetEnvironment.Current.TraceIncrementBusyCount(base.GetType().FullName);
     }
 }
        //Sending messages to the IoT hub

        private async Task SendDeviceToCloudMessagesAsync()
        {
            information = new PerformanceCounters();
            //Loop for sending messages
            while (!kill)
            {
                //Creating a telemetry object, setting data, sending over Iot Azure
                telemetry = new TelemetryDatapoint(device);
                //Cpu
                telemetry.Cpu       = information.GetCPU();
                telemetry.Cpu2      = information.GetFrequency();
                telemetry.Percent   = information.GetPercent();
                telemetry.Thread    = information.GetThreadCount();
                telemetry.CpuTem    = information.GetTemp();
                telemetry.Processes = information.GetProcesesCount();
                //Ram
                telemetry.Ram          = information.GetRamAvailable();
                telemetry.RamInUse     = information.GetRamInUse();
                telemetry.RamCache     = information.GetRamCache();
                telemetry.RamCommitted = information.GetRamCommitted();
                telemetry.PagedPool    = information.GetPagedPool();
                telemetry.NonPagedPool = information.GetNonPagedPool();
                //Disk
                telemetry.DiskReadTime   = information.GetDiskReadTime();
                telemetry.DiskWriteTime  = information.GetDiskWriteTime();
                telemetry.DiskReadBytes  = information.GetReadBytes();
                telemetry.DiskWriteBytes = information.GetWriteBytes();
                telemetry.FreeMB         = information.GetFreeMB();
                telemetry.FreeSpace      = information.GetFreeSpace();
                telemetry.IdleTime       = information.GetIdleTime();
                telemetry.DiskTime       = information.GetDiskTime();
                //Wifi
                telemetry.DownloadRate    = information.GetDownload();
                telemetry.UploadRate      = information.GetUpload();
                telemetry.Bandwidth       = information.GetBandwidth();
                telemetry.PacketsReceived = information.GetPacketsReceived();
                telemetry.PacketsSent     = information.GetPacketsSent();
                telemetry.Packets         = information.GetPackets();
                telemetry.ListTest        = information.GetProcesses();

                var     messageString = JsonConvert.SerializeObject(telemetry);
                Message message       = new Message(Encoding.ASCII.GetBytes(messageString));
                await deviceClient.SendEventAsync(message);

                //Printing out message
                Console.WriteLine(messageString);

                Task.Delay(650).Wait();
            }
        }
Exemple #14
0
 private void SetPerformanceCounters(List <SyncChange> changes)
 {
     try
     {
         var inserts = changes.Count(c => c.Operation == Operation.insert);
         var deletes = changes.Count(c => c.Operation == Operation.delete);
         var updates = changes.Count(c => c.Operation == Operation.update);
         PerformanceCounters.AddRowsInserted(inserts);
         PerformanceCounters.AddRowsDeleted(deletes);
         PerformanceCounters.AddRowsUpdated(updates);
     }
     catch (Exception exception)
     {
         exception.WriteToApplicationLog();
     }
 }
            public override void Rollback(Enlistment enlistment)
            {
                if (PerformanceCounters.PerformanceCountersEnabled)
                {
                    PerformanceCounters.TxAborted(this.endpointDispatcher, CallCount);
                }

                if (DiagnosticUtility.ShouldTraceInformation)
                {
                    TraceUtility.TraceEvent(TraceEventType.Information,
                                            TraceCode.TxAsyncAbort,
                                            SR.GetString(SR.TraceCodeTxAsyncAbort,
                                                         this.Transaction.TransactionInformation.LocalIdentifier)
                                            );
                }
                base.Rollback(enlistment);
            }
 public static void PoisonMessageMoved(string messageId, bool poisonQueue, string uri)
 {
     if (DiagnosticUtility.ShouldTraceWarning)
     {
         TraceUtility.TraceEvent(
             TraceEventType.Warning,
             poisonQueue ? TraceCode.MsmqPoisonMessageMovedPoison : TraceCode.MsmqPoisonMessageMovedRetry,
             poisonQueue ? SR.GetString(SR.TraceCodeMsmqPoisonMessageMovedPoison) : SR.GetString(SR.TraceCodeMsmqPoisonMessageMovedRetry),
             new StringTraceRecord("MSMQMessageId", messageId),
             null,
             null);
     }
     if (poisonQueue && PerformanceCounters.PerformanceCountersEnabled)
     {
         PerformanceCounters.MsmqPoisonMessage(uri);
     }
 }
 internal static void StopOperationInvokePerformanceCounters(bool callFailed, bool callFaulted, string methodName)
 {
     if (PerformanceCounters.PerformanceCountersEnabled)
     {
         if (callFailed)
         {
             PerformanceCounters.MethodReturnedError(methodName);
         }
         else if (callFaulted)
         {
             PerformanceCounters.MethodReturnedFault(methodName);
         }
         else
         {
             PerformanceCounters.MethodReturnedSuccess(methodName);
         }
     }
 }
Exemple #18
0
 public static void MessageConsumed(string uri, string messageId, bool rejected)
 {
     if (DiagnosticUtility.ShouldTraceWarning)
     {
         TraceUtility.TraceEvent(TraceEventType.Warning, rejected ? 0x4005e : 0x4005c, rejected ? System.ServiceModel.SR.GetString("TraceCodeMsmqMessageRejected") : System.ServiceModel.SR.GetString("TraceCodeMsmqMessageDropped"), new StringTraceRecord("MSMQMessageId", messageId), null, null);
     }
     if (PerformanceCounters.PerformanceCountersEnabled)
     {
         if (rejected)
         {
             PerformanceCounters.MsmqRejectedMessage(uri);
         }
         else
         {
             PerformanceCounters.MsmqDroppedMessage(uri);
         }
     }
 }
 private void TrackMethodSucceeded()
 {
     if (this.performanceCountersEnabled)
     {
         long duration = this.GetDuration();
         using (new OperationContextScopeHelper(this.OperationContext))
         {
             PerformanceCounters.MethodReturnedSuccess(this.operationName, duration);
         }
     }
     if (System.ServiceModel.Diagnostics.Application.TD.OperationCompletedIsEnabled())
     {
         using (new OperationContextScopeHelper(this.OperationContext))
         {
             System.ServiceModel.Diagnostics.Application.TD.OperationCompleted(this.operationName, TraceUtility.GetUtcBasedDurationForTrace(this.beginOperation));
         }
     }
 }
Exemple #20
0
        static void Main(string[] args)
        {
            PerformanceCounters.CreateSentinelCostPerformanceCounters(categoryName, categoryHelp);

            //_logName = args[0];
            //Enum.TryParse(args[1], out dataType);

            ConfigHelperObject = new ConfigHelper();
            bool resetListener = true;

            ///  Run the console app
            ConsoleKeyInfo cki;

            Console.WriteLine("Press any combination of CTL.");
            Console.WriteLine("Press the Escape (Esc) key to quit: \n");
            Task runTask = null;

            cancellationTokenSource = new CancellationTokenSource();
            cancellationToken       = cancellationTokenSource.Token;

            do
            {
                // Run importing in background
                if (runTask == null)
                {
                    logName         = GetEventLogSelection();
                    dataType        = GetDataTypeSelection();
                    CompressionType = GetCompressionSelection();
                    Console.WriteLine("Press any CTL+B to make a different selection.");
                    runTask = Task.Run(() => Subscribe(logName), cancellationToken);
                }

                cki = Console.ReadKey();

                if ((cki.Modifiers & ConsoleModifiers.Control) != 0 && cki.Key == ConsoleKey.B)
                {
                    Console.Write("CTL+");
                    Console.WriteLine($"Stop reading {logName}  task...");

                    cancellationTokenSource.Cancel();
                    runTask = null;
                }
            }while (cki.Key != ConsoleKey.Escape);
        }
Exemple #21
0
        /// <summary>
        /// Primary entry point for the program
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            const string ComponentName = @"Front End Setup";

            var  logger  = new StartupLogger("Protocol Gateway Setup");
            Guid traceId = Guid.NewGuid();

            try
            {
                logger.Informational(traceId, ComponentName, "Launched.");
                PerformanceCounters.RegisterCountersIfRequired();
                logger.Informational(traceId, ComponentName, "Completed without exceptions.");
            }
            catch (Exception e)
            {
                logger.Critical(traceId, ComponentName, "Could not prepare the environment due to an error.", null, e);
                throw;
            }
        }
Exemple #22
0
 void TrackMethodSucceeded()
 {
     if (this.performanceCountersEnabled)
     {
         long duration = this.GetDuration();
         using (new OperationContextScopeHelper(this.OperationContext))
         {
             PerformanceCounters.MethodReturnedSuccess(this.operationName, duration);
         }
     }
     if (TD2.OperationCompletedIsEnabled())
     {
         using (new OperationContextScopeHelper(this.OperationContext))
         {
             TD2.OperationCompleted(this.eventTraceActivity, this.operationName,
                                    TraceUtility.GetUtcBasedDurationForTrace(this.beginOperation));
         }
     }
 }
Exemple #23
0
        protected virtual void OnVerifyIncomingMessageFailure(Message message, Exception exception)
        {
            SecurityTraceRecordHelper.TraceVerifyIncomingMessageFailure(this, message);
            if (PerformanceCounters.PerformanceCountersEnabled && null != this.factory.ListenUri) //service side
            {
                if ((exception.GetType() == typeof(MessageSecurityException) || exception.GetType().IsSubclassOf(typeof(MessageSecurityException))) ||
                    (exception.GetType() == typeof(SecurityTokenException) || exception.GetType().IsSubclassOf(typeof(SecurityTokenException))))
                {
                    PerformanceCounters.AuthenticationFailed(message, this.factory.ListenUri);
                }
            }

            if (AuditLevel.Failure == (this.factory.MessageAuthenticationAuditLevel & AuditLevel.Failure))
            {
                try
                {
                    SecurityMessageProperty security = message.Properties.Security;
                    string primaryIdentity;
                    if (security != null && security.ServiceSecurityContext != null)
                    {
                        primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(security.ServiceSecurityContext.AuthorizationContext);
                    }
                    else
                    {
                        primaryIdentity = SecurityUtils.AnonymousIdentity.Name;
                    }

                    SecurityAuditHelper.WriteMessageAuthenticationFailureEvent(this.factory.AuditLogLocation,
                                                                               this.factory.SuppressAuditFailure, message, message.Headers.To, message.Headers.Action, primaryIdentity, exception);
                }
#pragma warning suppress 56500
                catch (Exception auditException)
                {
                    if (Fx.IsFatal(auditException))
                    {
                        throw;
                    }

                    DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error);
                }
            }
        }
Exemple #24
0
 private void ProcessChangeSet(List <SyncChange> changes)
 {
     try
     {
         var queries = new List <SQLQuery>();
         foreach (var change in changes)
         {
             var data = GetDataFromSource(change);
             if (data.Count > 0)
             {
                 var query = GetQueryForChange(change, data);
                 queries.Add(query);
             }
         }
         if (queries.Count > 0)
         {
             destinationDB.RunQuery(queries, true);
         }
         else
         {
             //log???
         }
         SetPerformanceCounters(changes);
         syncChangesData.UpdateStatusOfChanges(changes, RowChangeStatus.complete);
     }
     catch (Exception ex)
     {
         try
         {
             MakeSureIdentityInsertIsOff(changes);
             ex.WriteToApplicationLog();
             PerformanceCounters.AddRowsErrored(changes.Count);
             syncChangesData.UpdateStatusOfChanges(changes, RowChangeStatus.error);
         }
         catch (Exception ex2)
         {
             ex2.WriteToApplicationLog();
         }
     }
 }
Exemple #25
0
        public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            long beginTime = 0;

            if (PerformanceCounters.PerformanceCountersEnabled)
            {
                PerformanceCounters.MethodCalled(this.operationDescription.Name);

                try
                {
                    if (UnsafeNativeMethods.QueryPerformanceCounter(out beginTime) == 0)
                    {
                        beginTime = -1;
                    }
                }
                catch (SecurityException exception)
                {
                    DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityException(SR.GetString("PartialTrustPerformanceCountersNotEnabled"), exception));
                }
            }

            Authorize();

            WorkflowDurableInstance durableInstance = (WorkflowDurableInstance)instance;

            Fx.Assert(durableInstance.CurrentOperationInvocation == null,
                      "At the time WorkflowOperationInvoker.InvokeBegin is called, the WorkflowDurableInstance.CurrentOperationInvocation is expected to be null given the ConcurrencyMode.Single.");

            durableInstance.CurrentOperationInvocation = new WorkflowOperationAsyncResult(
                this,
                durableInstance,
                inputs,
                callback,
                state,
                beginTime);

            return(durableInstance.CurrentOperationInvocation);
        }
Exemple #26
0
        public static void ChapterThree()
        {
            #region [ Symmetric and asymmetric encryption]
            SymmetricAndAsymmetricEncryption saae = new SymmetricAndAsymmetricEncryption();
            //saae.AesEncryption();
            //saae.AesDecryption();
            //saae.RSAEncryptionDecryption();
            //saae.KeyStorageLocal();
            //saae.KeyStorageMachine();
            saae.DoubleEncryption();
            #endregion

            #region [ Certificates ]
            Certificates certificates = new Certificates();
            //certificates.SignData();
            #endregion

            #region [ Hashing ]
            Hashing hashing = new Hashing();
            //hashing.CalculateCheckSum();
            //hashing.Sha256();
            #endregion

            #region [ Trace and debug ]
            TraceAndDebug tad = new TraceAndDebug();
            //tad.DebugMethod();
            //tad.TraceMethod();
            //tad.DebugAssertions();
            //tad.TraceListeners();
            //tad.TraceSources();
            PerformanceCounters pc = new PerformanceCounters();
            //pc.PerformanceCounterExample();
            //pc.RunCustomCounter();
            EventLogs eventLogs = new EventLogs();
            //eventLogs.WritingInAnEventLog();
            //eventLogs.ReadingFromAnEventLog();
            //eventLogs.EventLogBinder();
            #endregion
        }
Exemple #27
0
        public PagePerformance()
        {
            InitializeComponent();

            StackPanel panelContent = new StackPanel();

            panelContent.Margin = new Thickness(10, 0, 10, 0);
            panelContent.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;

            ContentControl txtHeader = new ContentControl();

            txtHeader.ContentTemplate     = this.Resources["PerformanceHeader"] as DataTemplate;
            txtHeader.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;

            panelContent.Children.Add(txtHeader);

            ListBox lbCounters = new ListBox();

            lbCounters.ItemTemplate = this.Resources["PerformanceItem"] as DataTemplate;
            lbCounters.MaxHeight    = GraphicsHelpers.GetContentHeight() - 50;
            lbCounters.ItemContainerStyleSelector = new ListBoxItemStyleSelector();

            foreach (string pageCounter in PerformanceCounters.GetPages())
            {
                lbCounters.Items.Add(pageCounter);
            }



            panelContent.Children.Add(lbCounters);


            base.setContent(panelContent);

            base.setHeaderContent("Performance Counters");

            showPage(this);
        }
Exemple #28
0
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            List <PagePerformanceCounter> counters = PerformanceCounters.GetPerformanceCounters(value.ToString());
            string type = parameter.ToString();

            if (type == "A")
            {
                return(counters.Average(c => c.Counter));
            }
            if (type == "H")
            {
                return(counters.Max(c => c.Counter));
            }
            if (type == "L")
            {
                return(counters.Min(c => c.Counter));
            }
            if (type == "C")
            {
                return(counters.Count);
            }
            return(0);
        }
Exemple #29
0
        //public readonly ActiveDirectoryService ActiveDirectoryService;

        public ApplicationSettings(
            //IConnectionStringMap connectionStringMap,
            IAppSettings appSettings,
            IConfigurationContainerFactory configurationContainerFactory,
            IUnhandledExceptionLogging unhandledExceptionLogger,
            AdminkaStorageConfiguration adminkaStorageConfiguration
            )
        {
            UnhandledExceptionLogger      = unhandledExceptionLogger;
            UseAdAuthorization            = bool.Parse(appSettings.GetValue("UseAdAuthorization") ?? "false");
            UseStandardDeveloperErrorPage = bool.Parse(appSettings.GetValue("UseStandardDeveloperErrorPage") ?? "false");
            ForceDetailsOnCustomErrorPage = bool.Parse(appSettings.GetValue("ForceDetailsOnCustomErrorPage") ?? "false");
            InternalUsersDomain           = appSettings.GetValue("InternalUsersDomain");
            //ActiveDirectoryService = new ActiveDirectoryService(appSettings.GetValue("InternalUsersAdGroup"));
            AdminkaStorageConfiguration   = adminkaStorageConfiguration;
            ConfigurationContainerFactory = configurationContainerFactory;

            //AuthenticationLogging = new NLogAuthenticationLogging();
            var instanceName = appSettings.GetValue("InstanceName");

            if (!string.IsNullOrEmpty(instanceName))
            {
                try
                {
                    PerformanceCounters = new PerformanceCounters("DashboardCode Adminka", instanceName);
                }
                catch
                {
                    PerformanceCounters = new PerformanceCountersStub();
                }
            }
            else
            {
                PerformanceCounters = new PerformanceCountersStub();
            }
        }
Exemple #30
0
        // Token: 0x060003B7 RID: 951 RVA: 0x0001721C File Offset: 0x0001541C
        private void ExecuteCommand(IIdentity callerIdentity, CallContext callContext)
        {
            ADRecipient adrecipient = HttpContext.Current.Items["CallerRecipient"] as ADRecipient;

            if (adrecipient == null && (Common.IsPartnerHostedOnly || VariantConfiguration.InvariantNoFlightingSnapshot.Autodiscover.NoCrossForestDiscover.Enabled))
            {
                string identityNameForTrace = Common.GetIdentityNameForTrace(callerIdentity);
                ExTraceGlobals.FrameworkTracer.TraceError <string>(0L, "ExecuteCommand -- IRecipientSession.FindBySid user for {0} returned null.", identityNameForTrace);
                callContext.Response.ErrorCode    = ErrorCode.InvalidUser;
                callContext.Response.ErrorMessage = string.Format(Strings.InvalidUser, identityNameForTrace);
                return;
            }
            PartnerInfo partnerInfo  = null;
            string      targetTenant = null;
            bool        flag         = false;
            string      text         = null;

            byte[] binarySecret = null;
            GetUserSettingsCommandBase getUserSettingsCommandBase;

            if (VariantConfiguration.InvariantNoFlightingSnapshot.Autodiscover.ParseBinarySecretHeader.Enabled && AutodiscoverRequestMessage.HasBinarySecretHeader(out text))
            {
                PerformanceCounters.UpdatePartnerTokenRequests(callContext.UserAgent);
                bool flag2 = false;
                if (!string.IsNullOrEmpty(text))
                {
                    try
                    {
                        binarySecret = Convert.FromBase64String(text);
                        flag2        = true;
                    }
                    catch (FormatException)
                    {
                        ExTraceGlobals.FrameworkTracer.TraceDebug <string>((long)this.GetHashCode(), "[GetUserSettingsRequestMessage::ExecuteCommand] the binary secret header {0} has invalid format", text);
                    }
                }
                if (!flag2)
                {
                    PerformanceCounters.UpdatePartnerTokenRequestsFailed(callContext.UserAgent);
                    callContext.Response.ErrorCode    = ErrorCode.InvalidRequest;
                    callContext.Response.ErrorMessage = Strings.InvalidBinarySecretHeader;
                    return;
                }
                if (!this.TryGetMailboxAccessPartnerInfo(callContext, adrecipient, out partnerInfo, out targetTenant))
                {
                    ExTraceGlobals.FrameworkTracer.TraceDebug((long)this.GetHashCode(), "[GetUserSettingsRequestMessage::ExecuteCommand] TryGetMailboxAccessPartnerInfo returns false.");
                    PerformanceCounters.UpdatePartnerTokenRequestsFailed(callContext.UserAgent);
                    callContext.Response.ErrorCode    = ErrorCode.InvalidRequest;
                    callContext.Response.ErrorMessage = Strings.InvalidPartnerTokenRequest;
                    return;
                }
                flag = true;
                ExTraceGlobals.FrameworkTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "GetUserSettingsForPartner created for the '{0}'. The caller is FPO partner.", adrecipient);
                getUserSettingsCommandBase = new GetUserSettingsForPartner(callerIdentity.GetSecurityIdentifier(), callContext);
            }
            else if (adrecipient == null)
            {
                ExTraceGlobals.FrameworkTracer.TraceDebug <string>((long)this.GetHashCode(), "GetUserSettingsForUserWithUnscopedCaller created for '{0}'.", Common.GetIdentityNameForTrace(callerIdentity));
                getUserSettingsCommandBase = new GetUserSettingsForUserWithUnscopedCaller(callerIdentity.GetSecurityIdentifier(), callContext);
            }
            else if (ExchangeRunspaceConfiguration.IsAllowedOrganizationForPartnerAccounts(adrecipient.OrganizationId))
            {
                ExTraceGlobals.FrameworkTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "GetUserSettingsForPartner created for '{0}'.", adrecipient);
                getUserSettingsCommandBase = new GetUserSettingsForPartner(callerIdentity.GetSecurityIdentifier(), callContext);
            }
            else
            {
                ExTraceGlobals.FrameworkTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "GetUserSettingsForUser created for '{0}'.", adrecipient);
                getUserSettingsCommandBase = new GetUserSettingsForUser(adrecipient, callerIdentity.GetSecurityIdentifier(), callContext);
            }
            getUserSettingsCommandBase.Execute();
            if (flag)
            {
                UserResponse userResponse = callContext.Response.UserResponses[0];
                if (userResponse.ErrorCode == ErrorCode.NoError || userResponse.ErrorCode == ErrorCode.RedirectUrl)
                {
                    string        assertionId = SecurityTokenService.CreateSamlAssertionId();
                    MessageHeader header      = MessageHeader.CreateHeader("PartnerToken", "http://schemas.microsoft.com/exchange/2010/Autodiscover", partnerInfo.CreateSamlToken(assertionId, targetTenant, binarySecret, GetUserSettingsRequestMessage.tokenLifetime.Value));
                    MessageHeader header2     = MessageHeader.CreateHeader("PartnerTokenReference", "http://schemas.microsoft.com/exchange/2010/Autodiscover", PartnerInfo.GetTokenReference(assertionId));
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header2);
                    return;
                }
                PerformanceCounters.UpdatePartnerTokenRequestsFailed(callContext.UserAgent);
                ExTraceGlobals.FrameworkTracer.TraceDebug <ErrorCode, string>((long)this.GetHashCode(), "No partner token header added since the user response error code is {0}, error message is '{1}'", userResponse.ErrorCode, userResponse.ErrorMessage);
            }
        }
Exemple #31
0
        public object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            EnsureIsInitialized();

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxNoServiceObject)));
            }
            if (inputs == null)
            {
                if (this.inputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceNull, this.inputParameterCount)));
                }
            }
            else if (inputs.Length != this.inputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInputParametersToServiceInvalid, this.inputParameterCount, inputs.Length)));
            }

            outputs = EmptyArray.Allocate(this.outputParameterCount);

            long startCounter   = 0;
            long stopCounter    = 0;
            long beginOperation = 0;
            bool callSucceeded  = false;
            bool callFaulted    = false;

            if (PerformanceCounters.PerformanceCountersEnabled)
            {
                PerformanceCounters.MethodCalled(this.MethodName);
                try
                {
                    if (System.ServiceModel.Channels.UnsafeNativeMethods.QueryPerformanceCounter(out startCounter) == 0)
                    {
                        startCounter = -1;
                    }
                }
                catch (SecurityException securityException)
                {
                    DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new SecurityException(SR.GetString(
                                                        SR.PartialTrustPerformanceCountersNotEnabled), securityException));
                }
            }

            EventTraceActivity eventTraceActivity = null;

            if (TD.OperationCompletedIsEnabled() ||
                TD.OperationFaultedIsEnabled() ||
                TD.OperationFailedIsEnabled())
            {
                beginOperation = DateTime.UtcNow.Ticks;
                OperationContext context = OperationContext.Current;
                if (context != null && context.IncomingMessage != null)
                {
                    eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(context.IncomingMessage);
                }
            }

            object returnValue;

            try
            {
                ServiceModelActivity activity      = null;
                IDisposable          boundActivity = null;
                if (DiagnosticUtility.ShouldUseActivity)
                {
                    activity      = ServiceModelActivity.CreateBoundedActivity(true);
                    boundActivity = activity;
                }
                else if (TraceUtility.MessageFlowTracingOnly)
                {
                    Guid activityId = TraceUtility.GetReceivedActivityId(OperationContext.Current);
                    if (activityId != Guid.Empty)
                    {
                        DiagnosticTraceBase.ActivityId = activityId;
                    }
                }
                else if (TraceUtility.ShouldPropagateActivity)
                {
                    //Message flow tracing only scenarios use a light-weight ActivityID management logic
                    Guid activityId = ActivityIdHeader.ExtractActivityId(OperationContext.Current.IncomingMessage);
                    if (activityId != Guid.Empty)
                    {
                        boundActivity = Activity.CreateActivity(activityId);
                    }
                }

                using (boundActivity)
                {
                    if (DiagnosticUtility.ShouldUseActivity)
                    {
                        ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityExecuteMethod, this.method.DeclaringType.FullName, this.method.Name), ActivityType.ExecuteUserCode);
                    }
                    if (TD.OperationInvokedIsEnabled())
                    {
                        TD.OperationInvoked(eventTraceActivity, this.MethodName, TraceUtility.GetCallerInfo(OperationContext.Current));
                    }
                    returnValue   = this.invokeDelegate(instance, inputs, outputs);
                    callSucceeded = true;
                }
            }
            catch (System.ServiceModel.FaultException)
            {
                callFaulted = true;
                throw;
            }
            catch (System.Security.SecurityException e)
            {
                DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(AuthorizationBehavior.CreateAccessDeniedFaultException());
            }
            finally
            {
                if (PerformanceCounters.PerformanceCountersEnabled)
                {
                    long elapsedTime = 0;
                    if (startCounter >= 0 && System.ServiceModel.Channels.UnsafeNativeMethods.QueryPerformanceCounter(out stopCounter) != 0)
                    {
                        elapsedTime = stopCounter - startCounter;
                    }

                    if (callSucceeded) // call succeeded
                    {
                        PerformanceCounters.MethodReturnedSuccess(this.MethodName, elapsedTime);
                    }
                    else if (callFaulted) // call faulted
                    {
                        PerformanceCounters.MethodReturnedFault(this.MethodName, elapsedTime);
                    }
                    else // call failed
                    {
                        PerformanceCounters.MethodReturnedError(this.MethodName, elapsedTime);
                    }
                }

                if (beginOperation != 0)
                {
                    if (callSucceeded)
                    {
                        if (TD.OperationCompletedIsEnabled())
                        {
                            TD.OperationCompleted(eventTraceActivity, this.methodName,
                                                  TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
                        }
                    }
                    else if (callFaulted)
                    {
                        if (TD.OperationFaultedIsEnabled())
                        {
                            TD.OperationFaulted(eventTraceActivity, this.methodName,
                                                TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
                        }
                    }
                    else
                    {
                        if (TD.OperationFailedIsEnabled())
                        {
                            TD.OperationFailed(eventTraceActivity, this.methodName,
                                               TraceUtility.GetUtcBasedDurationForTrace(beginOperation));
                        }
                    }
                }
            }

            return(returnValue);
        }
        public void Authorize(ref MessageRpc rpc)
        {
            if (TD.DispatchMessageBeforeAuthorizationIsEnabled())
            {
                TD.DispatchMessageBeforeAuthorization(rpc.EventTraceActivity);
            }

            SecurityMessageProperty security = SecurityMessageProperty.GetOrCreate(rpc.Request);

            security.ExternalAuthorizationPolicies = this.externalAuthorizationPolicies;

            ServiceAuthorizationManager serviceAuthorizationManager = this.serviceAuthorizationManager ?? DefaultServiceAuthorizationManager;

            try
            {
                if (!serviceAuthorizationManager.CheckAccess(rpc.OperationContext, ref rpc.Request))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateAccessDeniedFaultException());
                }
            }
            catch (Exception ex)
            {
                if (Fx.IsFatal(ex))
                {
                    throw;
                }
                if (PerformanceCounters.PerformanceCountersEnabled)
                {
                    PerformanceCounters.AuthorizationFailed(rpc.Operation.Name);
                }
                if (AuditLevel.Failure == (this.serviceAuthorizationAuditLevel & AuditLevel.Failure))
                {
                    try
                    {
                        string primaryIdentity;
                        string authContextId             = null;
                        AuthorizationContext authContext = security.ServiceSecurityContext.AuthorizationContext;
                        if (authContext != null)
                        {
                            primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(authContext);
                            authContextId   = authContext.Id;
                        }
                        else
                        {
                            primaryIdentity = SecurityUtils.AnonymousIdentity.Name;
                            authContextId   = "<null>";
                        }

                        SecurityAuditHelper.WriteServiceAuthorizationFailureEvent(this.auditLogLocation,
                                                                                  this.suppressAuditFailure, rpc.Request, rpc.Request.Headers.To, rpc.Request.Headers.Action,
                                                                                  primaryIdentity, authContextId,
                                                                                  serviceAuthorizationManager == DefaultServiceAuthorizationManager ? "<default>" : serviceAuthorizationManager.GetType().Name,
                                                                                  ex);
                    }
#pragma warning suppress 56500
                    catch (Exception auditException)
                    {
                        if (Fx.IsFatal(auditException))
                        {
                            throw;
                        }

                        DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error);
                    }
                }
                throw;
            }

            if (AuditLevel.Success == (this.serviceAuthorizationAuditLevel & AuditLevel.Success))
            {
                string primaryIdentity;
                string authContextId;
                AuthorizationContext authContext = security.ServiceSecurityContext.AuthorizationContext;
                if (authContext != null)
                {
                    primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(authContext);
                    authContextId   = authContext.Id;
                }
                else
                {
                    primaryIdentity = SecurityUtils.AnonymousIdentity.Name;
                    authContextId   = "<null>";
                }

                SecurityAuditHelper.WriteServiceAuthorizationSuccessEvent(this.auditLogLocation,
                                                                          this.suppressAuditFailure, rpc.Request, rpc.Request.Headers.To, rpc.Request.Headers.Action,
                                                                          primaryIdentity, authContextId,
                                                                          serviceAuthorizationManager == DefaultServiceAuthorizationManager ? "<default>" : serviceAuthorizationManager.GetType().Name);
            }
        }
        public void Authenticate(ref MessageRpc rpc)
        {
            SecurityMessageProperty orCreate = SecurityMessageProperty.GetOrCreate(rpc.Request);
            ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = orCreate.ServiceSecurityContext.AuthorizationPolicies;

            try
            {
                authorizationPolicies = this.serviceAuthenticationManager.Authenticate(orCreate.ServiceSecurityContext.AuthorizationPolicies, rpc.Channel.ListenUri, ref rpc.Request);
                if (authorizationPolicies == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("AuthenticationManagerShouldNotReturnNull")));
                }
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                if (PerformanceCounters.PerformanceCountersEnabled)
                {
                    PerformanceCounters.AuthenticationFailed(rpc.Request, rpc.Channel.ListenUri);
                }
                if (AuditLevel.Failure == (this.messageAuthenticationAuditLevel & AuditLevel.Failure))
                {
                    try
                    {
                        string identityNamesFromContext;
                        AuthorizationContext authorizationContext = orCreate.ServiceSecurityContext.AuthorizationContext;
                        if (authorizationContext != null)
                        {
                            identityNamesFromContext = System.ServiceModel.Security.SecurityUtils.GetIdentityNamesFromContext(authorizationContext);
                        }
                        else
                        {
                            identityNamesFromContext = System.ServiceModel.Security.SecurityUtils.AnonymousIdentity.Name;
                        }
                        SecurityAuditHelper.WriteMessageAuthenticationFailureEvent(this.auditLogLocation, this.suppressAuditFailure, rpc.Request, rpc.Channel.ListenUri, rpc.Request.Headers.Action, identityNamesFromContext, exception);
                    }
                    catch (Exception exception2)
                    {
                        if (Fx.IsFatal(exception2))
                        {
                            throw;
                        }
                        DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Error);
                    }
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateFailedAuthenticationFaultException());
            }
            rpc.Request.Properties.Security.ServiceSecurityContext.AuthorizationPolicies = authorizationPolicies;
            if (AuditLevel.Success == (this.messageAuthenticationAuditLevel & AuditLevel.Success))
            {
                string name;
                AuthorizationContext authContext = orCreate.ServiceSecurityContext.AuthorizationContext;
                if (authContext != null)
                {
                    name = System.ServiceModel.Security.SecurityUtils.GetIdentityNamesFromContext(authContext);
                }
                else
                {
                    name = System.ServiceModel.Security.SecurityUtils.AnonymousIdentity.Name;
                }
                SecurityAuditHelper.WriteMessageAuthenticationSuccessEvent(this.auditLogLocation, this.suppressAuditFailure, rpc.Request, rpc.Channel.ListenUri, rpc.Request.Headers.Action, name);
            }
        }