コード例 #1
0
 public override Task OnActivateAsync()
 {
     logger = TraceLogger.GetLogger("GrainBasedMembershipTable", TraceLogger.LoggerType.Runtime);
     logger.Info(ErrorCode.MembershipGrainBasedTable1, "GrainBasedMembershipTable Activated.");
     table = new InMemoryMembershipTable();
     return TaskDone.Done;
 }
コード例 #2
0
        /// <summary>
        /// Load this configuratin from xml element.
        /// </summary>
        /// <param name="xmlElement"></param>
        /// <param name="logger"></param>
        public void Load(XmlElement xmlElement, TraceLogger logger)
        {
            bool found = false;
            foreach (XmlNode node in xmlElement.ChildNodes)
            {
                found = true;
                var config = GrainTypeConfiguration.Load((XmlElement)node, logger);
                if (null == config) continue;

                if (config.AreDefaults)
                {
                    defaults = config;
                }
                else
                {
                    if (classSpecific.ContainsKey(config.FullTypeName))
                    {
                        throw new InvalidOperationException(string.Format("duplicate type {0} in configuration", config.FullTypeName));
                    }
                    classSpecific.Add(config.FullTypeName, config);
                }
            }

            if (!found)
            {
                throw new InvalidOperationException("empty GrainTypeConfiguration element");
            }
        }
コード例 #3
0
 public MultipleStreamsTestRunner(string streamProvider, int testNum = 0, bool fullTest = true)
 {
     this.streamProviderName = streamProvider;
     this.logger = TraceLogger.GetLogger("MultipleStreamsTestRunner", TraceLogger.LoggerType.Application);
     this.testNumber = testNum;
     this.runFullTest = fullTest;
 }
コード例 #4
0
        public async Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitTableVersion, TraceLogger traceLogger)
        {
            logger = traceLogger;
            deploymentId = config.DeploymentId;

            if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.InitializeMembershipTable called.");

            database = RelationalStorageUtilities.CreateGenericStorageInstance(config.AdoInvariant, config.DataConnectionString);

            //This initializes all of Orleans operational queries from the database using a well known view
            //and assumes the database with appropriate defintions exists already.
            queryConstants = await database.InitializeOrleansQueriesAsync();

            // even if I am not the one who created the table, 
            // try to insert an initial table version if it is not already there,
            // so we always have a first table version row, before this silo starts working.
            if(tryInitTableVersion)
            {
                var wasCreated = await InitTableAsync();
                if(wasCreated)
                {
                    logger.Info("Created new table version row.");
                }
            }
        }
コード例 #5
0
        static void StartSimulator()
        {
            // Dependencies to inject into the Bulk Device Tester
            var logger = new TraceLogger();
            var configProvider = new ConfigurationProvider();
            var telemetryFactory = new EngineTelemetryFactory(logger, configProvider);

            var serializer = new JsonSerialize();
            var transportFactory = new IotHubTransportFactory(serializer, logger, configProvider);

            IVirtualDeviceStorage deviceStorage = null;
            var useConfigforDeviceList = Convert.ToBoolean(configProvider.GetConfigurationSettingValueOrDefault("UseConfigForDeviceList", "False"), CultureInfo.InvariantCulture);

            if (useConfigforDeviceList)
            {
                deviceStorage = new AppConfigRepository(configProvider, logger);
            }
            else
            {
                deviceStorage = new VirtualDeviceTableStorage(configProvider);
            }

            IDeviceFactory deviceFactory = new EngineDeviceFactory();

            // Start Simulator
            Trace.TraceInformation("Starting Simulator");
            var tester = new BulkDeviceTester(transportFactory, logger, configProvider, telemetryFactory, deviceFactory, deviceStorage);
            Task.Run(() => tester.ProcessDevicesAsync(cancellationTokenSource.Token), cancellationTokenSource.Token);
        }
コード例 #6
0
 public Task InitializeGatewayListProvider(ClientConfiguration config, TraceLogger traceLogger)
 {
     deploymentId = config.DeploymentId;
     connectionString = config.DataConnectionString;
     maxStaleness = config.GatewayListRefreshPeriod;
     return TaskDone.Done;
 }
コード例 #7
0
ファイル: LogWriters.cs プロジェクト: stanroze/orleans
        public void Log(            
            Logger.Severity severity,
            TraceLogger.LoggerType loggerType,
            string caller,
            string message,
            IPEndPoint myIPEndPoint,
            Exception exception,
            int errorCode)    
        {
            var now = DateTime.UtcNow;

            var msg = FormatLogMessage(
                now,
                severity,
                loggerType,
                caller,
                message,
                myIPEndPoint,
                exception,
                errorCode);

            try
            {
                WriteLogMessage(msg, severity);
            }
            catch (Exception exc)
            {
                Trace.TraceError("Error writing log message {0} -- Exception={1}", msg, exc);
            }
        }
コード例 #8
0
ファイル: AsynchAgent.cs プロジェクト: sbambach/orleans
        protected AsynchAgent(string nameSuffix)
        {
            Cts = new CancellationTokenSource();
            var thisType = GetType();
            
            type = thisType.Namespace + "." + thisType.Name;
            if (type.StartsWith("Orleans.", StringComparison.Ordinal))
            {
                type = type.Substring(8);
            }
            if (!string.IsNullOrEmpty(nameSuffix))
            {
                Name = type + "/" + nameSuffix;
            }
            else
            {
                Name = type;
            }

            Lockable = new object();
            State = ThreadState.Unstarted;
            OnFault = FaultBehavior.IgnoreFault;
            Log = TraceLogger.GetLogger(Name, TraceLogger.LoggerType.Runtime);
            AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;

#if TRACK_DETAILED_STATS
            if (StatisticsCollector.CollectThreadTimeTrackingStats)
            {
                threadTracking = new ThreadTrackingStatistic(Name);
            }
#endif
            t = new Thread(AgentThreadProc) { IsBackground = true, Name = this.Name };
        }
コード例 #9
0
        private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(5); // Pause 5 seconds between forwards to let the membership directory settle down

        internal RemoteGrainDirectory(LocalGrainDirectory r, GrainId id)
            : base(id, r.MyAddress)
        {
            router = r;
            partition = r.DirectoryPartition;
            logger = TraceLogger.GetLogger("Orleans.GrainDirectory.CacheValidator", TraceLogger.LoggerType.Runtime);
        }
コード例 #10
0
        internal VirtualBucketsRingProvider(SiloAddress siloAddr, int nBucketsPerSilo)
        {
            if (nBucketsPerSilo <= 0 )
                throw new IndexOutOfRangeException("numBucketsPerSilo is out of the range. numBucketsPerSilo = " + nBucketsPerSilo);

            logger = TraceLogger.GetLogger(typeof(VirtualBucketsRingProvider).Name);
                        
            statusListeners = new List<IRingRangeListener>();
            bucketsMap = new SortedDictionary<uint, SiloAddress>();
            sortedBucketsList = new List<Tuple<uint, SiloAddress>>();
            myAddress = siloAddr;
            numBucketsPerSilo = nBucketsPerSilo;
            lockable = new object();
            running = true;
            myRange = RangeFactory.CreateFullRange();

            logger.Info("Starting {0} on silo {1}.", typeof(VirtualBucketsRingProvider).Name, siloAddr.ToStringWithHashCode());

            StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RING, ToString);
            IntValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RINGSIZE, () => GetRingSize());
            StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGDISTANCE, () => String.Format("x{0,8:X8}", ((IRingRangeInternal)myRange).RangeSize()));
            FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGPERCENTAGE, () => (float)((IRingRangeInternal)myRange).RangePercentage());
            FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_AVERAGERINGPERCENTAGE, () =>
            {
                int size = GetRingSize();
                return size == 0 ? 0 : ((float)100.0/(float) size);
            });           

            // add myself to the list of members
            AddServer(myAddress);
        }
コード例 #11
0
ファイル: Watchdog.cs プロジェクト: stanroze/orleans
 public Watchdog(TimeSpan watchdogPeriod, List<IHealthCheckParticipant> watchables)
 {
     logger = TraceLogger.GetLogger("Watchdog");
     healthCheckPeriod = watchdogPeriod;
     participants = watchables;
     watchdogChecks = CounterStatistic.FindOrCreate(StatisticNames.WATCHDOG_NUM_HEALTH_CHECKS);
 }
コード例 #12
0
 public AzureQueueDataManagerTests()
 {
     ClientConfiguration config = new ClientConfiguration();
     config.TraceFilePattern = null;
     TraceLogger.Initialize(config);
     logger = TraceLogger.GetLogger("AzureQueueDataManagerTests", TraceLogger.LoggerType.Application);
 }
コード例 #13
0
        private AzureTableBasedGossipChannel gossipTable; // This type is internal

        public AzureGossipTableTests()
        {
            logger = TraceLogger.GetLogger("AzureGossipTableTests", TraceLogger.LoggerType.Application);
        
            globalServiceId = Guid.NewGuid();
            deploymentId = "test-" + globalServiceId;

            IPAddress ip;
            if (!IPAddress.TryParse("127.0.0.1", out ip))
            {
                logger.Error(-1, "Could not parse ip address");
                return;
            }
            IPEndPoint ep1 = new IPEndPoint(ip, 21111);
            siloAddress1 = SiloAddress.New(ep1, 0);
            IPEndPoint ep2 = new IPEndPoint(ip, 21112);
            siloAddress2 = SiloAddress.New(ep2, 0);

            logger.Info("DeploymentId={0}", deploymentId);

            GlobalConfiguration config = new GlobalConfiguration
            {
                ServiceId = globalServiceId,
                ClusterId = "0",
                DeploymentId = deploymentId,
                DataConnectionString = StorageTestConstants.DataConnectionString
            };

            gossipTable = new AzureTableBasedGossipChannel();
            var done = gossipTable.Initialize(config.ServiceId, config.DataConnectionString);
            if (!done.Wait(timeout))
            {
                throw new TimeoutException("Could not create/read table.");
            }
        }
コード例 #14
0
ファイル: Driver.cs プロジェクト: vakulenko/CAM8_software
 public TECControl(string comPort, bool traceEnabled)
 {
     tecComPort = new SerialPort(comPort, baudrate, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
     rxBuf = new byte[rxBufferSize];
     tectl = new TraceLogger("", "tec_cam85_v02");
     tectl.Enabled = traceEnabled;
     tectl.LogMessage("TECControl", "Initialization finished");
 }
コード例 #15
0
 internal GrainDirectoryHandoffManager(LocalGrainDirectory localDirectory, GlobalConfiguration config)
 {
     logger = TraceLogger.GetLogger(this.GetType().FullName);
     this.localDirectory = localDirectory;
     directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>();
     silosHoldingMyPartition = new List<SiloAddress>();
     lastPromise = new Dictionary<SiloAddress, Task>();
 }
コード例 #16
0
 public SingleStreamTestRunner(string streamProvider, int testNum = 0, bool fullTest = true)
 {
     this.streamProviderName = streamProvider;
     this.logger = TraceLogger.GetLogger("SingleStreamTestRunner", TraceLogger.LoggerType.Application);
     this.testNumber = testNum;
     this.runFullTest = fullTest;
     this.random = TestConstants.random;
 }
コード例 #17
0
 public override Task OnActivateAsync()
 {
     logger = TraceLogger.GetLogger(String.Format("GrainBasedReminderTable_{0}", Data.Address.ToString()), TraceLogger.LoggerType.Runtime);
     logger.Info("GrainBasedReminderTable {0} Activated. Full identity: {1}", Identity, Data.Address.ToFullString());
     remTable = new InMemoryRemindersTable();
     base.DelayDeactivation(TimeSpan.FromDays(10 * 365)); // Delay Deactivation for GrainBasedReminderTable virtually indefinitely.
     return TaskDone.Done;
 }
コード例 #18
0
        public void TestInitialize()
        {
            log = TraceLogger.GetLogger(GetType().Name, TraceLogger.LoggerType.Application);

            ServiceId = Guid.NewGuid();

            UnitTestSiloHost.ConfigureClientThreadPoolSettingsForStorageTests(1000);
        }
コード例 #19
0
 public async Task Init(GlobalConfiguration config, TraceLogger logger)
 {
     serviceId = config.ServiceId.ToString();
     deploymentId = config.DeploymentId;
     database = RelationalStorageUtilities.CreateGenericStorageInstance(config.AdoInvariantForReminders,
         config.DataConnectionStringForReminders);
     queryConstants = await database.InitializeOrleansQueriesAsync();
 }
コード例 #20
0
ファイル: TimerGrain.cs プロジェクト: sbambach/orleans
 public override Task OnActivateAsync()
 {
     logger = (TraceLogger)this.GetLogger("TimerGrain_" + base.Data.Address.ToString());
     context = RuntimeContext.Current.ActivationContext;
     defaultTimer = this.RegisterTimer(Tick, DefaultTimerName, TimeSpan.Zero, period);
     allTimers = new Dictionary<string, IDisposable>();
     return TaskDone.Done;
 }
コード例 #21
0
        public async Task InitializeGatewayListProvider(ClientConfiguration config, TraceLogger traceLogger)
        {
            logger = traceLogger;
            if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.InitializeGatewayListProvider called.");

            deploymentId = config.DeploymentId;            
            maxStaleness = config.GatewayListRefreshPeriod;
            orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString);
        }
コード例 #22
0
 private AzureQueueAdapterReceiver(QueueId queueId, AzureQueueDataManager queue)
 {
     if (queueId == null) throw new ArgumentNullException("queueId");
     if (queue == null) throw new ArgumentNullException("queue");
     
     Id = queueId;
     this.queue = queue;
     logger = TraceLogger.GetLogger(GetType().Name, TraceLogger.LoggerType.Provider);
 }
コード例 #23
0
        public ReminderTests_Azure_Standalone(ITestOutputHelper output)
        {
            this.output = output;
            log = TraceLogger.GetLogger(GetType().Name, TraceLogger.LoggerType.Application);

            ServiceId = Guid.NewGuid();

            TestUtils.ConfigureClientThreadPoolSettingsForStorageTests(1000);
        }
コード例 #24
0
        public async Task Initialize(Guid serviceid, string connectionstring)
        {
            Name = "AzureTableBasedGossipChannel-" + ++sequenceNumber;
            logger = TraceLogger.GetLogger(Name, TraceLogger.LoggerType.Runtime);

            logger.Info("Initializing Gossip Channel for ServiceId={0} using connection: {1}, SeverityLevel={2}",
                serviceid, ConfigUtilities.RedactConnectionStringInfo(connectionstring), logger.SeverityLevel);

            tableManager = await GossipTableInstanceManager.GetManager(serviceid, connectionstring, logger);
        }
コード例 #25
0
ファイル: AAF2.cs プロジェクト: tekkydave/AAF2
        public AAF2(bool traceState)
        {
            string traceDir = getTraceDir();   // Get the trace dir from registry.
            if (traceDir == "")                // if no value set it to C:\
                traceDir = "c:\\";

            tl = new TraceLogger(traceDir + "\\AAF2" + DateTime.Now.ToString("yyyyMMddHHmmss"), "AAF2_aaf2");      // Trace Logger
            tl.Enabled = traceState;
            tl.LogMessage("AAF2", "Constructed");
        }
コード例 #26
0
 internal ClientObserverRegistrar(SiloAddress myAddr, ISiloMessageCenter mc, ILocalGrainDirectory dir, OrleansTaskScheduler scheduler, ClusterConfiguration config)
     : base(Constants.ClientObserverRegistrarId, myAddr)
 {
     grainDirectory = dir;
     messageCenter = mc;
     myAddress = myAddr;
     this.scheduler = scheduler;
     orleansConfig = config;
     logger = TraceLogger.GetLogger(typeof(ClientObserverRegistrar).Name);
 }
コード例 #27
0
 /// <summary>
 /// Build an AxisPositionController object.
 /// 
 /// </summary>
 /// <param name="axis">Axis controlled by this object</param>
 /// <param name="deviceController">Actual hardware controller</param>
 /// <param name="minusSlewRate">Slew rate to use when moving in the MINUS orientation</param>
 /// <param name="plusSlewRate">Slew rate to use when moving in the PLUS orientation</param>
 public AxisController(Axis axis, DeviceController deviceController, double minusSlewRate, double plusSlewRate)
 {
     this.traceLogger = new TraceLogger("", "ArduinoST4 AxisPositionController " + axis.ToString());
     this.traceLogger.Enabled = true;
     this.axis = axis;
     this.deviceController = deviceController;
     this.minusSlewRate = minusSlewRate;
     this.plusSlewRate = plusSlewRate;
     this.axisMovementTracker = new AxisMovementTracker();
 }
コード例 #28
0
ファイル: AzureSilo.cs プロジェクト: kucheruk/orleans
        /// <summary>
        /// Constructor
        /// </summary>
        public AzureSilo()
        {
            DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
            SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
            ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;

            StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
            MaxRetries = AzureConstants.MAX_RETRIES;  // 120 x 5s = Total: 10 minutes

            logger = TraceLogger.GetLogger("OrleansAzureSilo", TraceLogger.LoggerType.Runtime);
        }
コード例 #29
0
        public void DoTestInitialize()
        {
            ClientConfiguration cfg = ClientConfiguration.LoadFromFile("ClientConfigurationForTesting.xml");
            TraceLogger.Initialize(cfg);
#if DEBUG
            TraceLogger.AddTraceLevelOverride("Storage", Severity.Verbose3);
            TraceLogger.AddTraceLevelOverride("Reminder", Severity.Verbose3);
#endif
            log = TraceLogger.GetLogger(this.GetType().Name, TraceLogger.LoggerType.Application);
            Console.WriteLine("base.DoTestInitialize completed");
        }
コード例 #30
0
 internal EquallyDevidedRangeRingProvider(IConsistentRingProvider provider, int mySubRangeIndex, int numSubRanges)
 {
     if (mySubRangeIndex < 0 || mySubRangeIndex >= numSubRanges)
         throw new IndexOutOfRangeException("mySubRangeIndex is out of the range. mySubRangeIndex = " + mySubRangeIndex + " numSubRanges = " + numSubRanges);
     
     ringProvider = provider;
     this.numSubRanges = numSubRanges;
     this.mySubRangeIndex = mySubRangeIndex;
     grainStatusListeners = new List<IAsyncRingRangeListener>();
     ringProvider.SubscribeToRangeChangeEvents(this);
     logger = TraceLogger.GetLogger(typeof(EquallyDevidedRangeRingProvider).Name);
 }
コード例 #31
0
        public virtual RpcResponse Execute()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(string.Format("Calling RPC, {0}, with Arguments:", this.RpcName));

            if (this.CommandArgs != null)
            {
                int count = 1;
                foreach (var arg in this.CommandArgs)
                {
                    if (arg != null)
                    {
                        if (arg is string[])
                        {
                            string[] stringArgs = arg as string[];
                            int      subCount   = 0;
                            if (stringArgs.Length == 0)
                            {
                                sb.AppendLine(string.Format("{0}:", count));
                            }
                            else
                            {
                                foreach (string subArg in stringArgs)
                                {
                                    if (string.IsNullOrWhiteSpace(subArg))
                                    {
                                        sb.AppendLine(string.Format("{0}[{1}]: {2}", count, subCount++, ""));
                                    }
                                    else
                                    {
                                        string noCommas = subArg.ToString();
                                        sb.AppendLine(string.Format("{0}[{1}]: {2}", count, subCount++, noCommas));
                                    }
                                }
                            }
                            count++;
                        }
                        else
                        {
                            string noCommas = arg.ToString();
                            sb.AppendLine(string.Format("{0}: {1}", count++, noCommas));
                        }
                    }
                    else
                    {
                        sb.AppendLine(string.Format("{0}: {1}", count++, ""));
                    }
                }
            }
            else
            {
                sb.AppendLine("None");
            }

            TraceLogger.Log(sb.ToString());

            this.Response = this.broker.CallRpc(this.Context, this.RpcName, this.Version, this.CommandArgs);

            // TODO: Remove this tracing...?
            TraceLogger.Log(string.Format("Result from '{0}':\n\r{1}", this.RpcName, this.Response.Data));

            if (this.Response.Status != RpcResponseStatus.Fail)
            {
                this.ProcessResponse();
            }

            LogIt();

            return(this.Response);
        }
コード例 #32
0
ファイル: VerseDisplay.xaml.cs プロジェクト: xhumiq/BibleLive
        public bool SelfAdjust(double height, bool force)
        {
            if (this.mIgnoreSize)
            {
                this.mIgnoreSize = false;
            }
            else
            {
                if (!this.IsLoaded)
                {
                    return(false);
                }
                this.CText.Visibility  = Visibility.Hidden;
                this.CText2.Visibility = Visibility.Hidden;
                try {
                    if (this.mCoef == 0.0 || Math.Abs(height - this.ContentHeight) > height * 0.45)
                    {
                        this.SetCoef(0.2, height);
                        force = true;
                    }
                    else
                    {
                        this.SetCoefTitle(0.2, height);
                    }
                    int num = 0;
                    var oh  = this.ContentHeight;
                    if (force)
                    {
                        for (int index = 0; index < 50; ++index)
                        {
                            if (num == 0)
                            {
                                num = height < this.ContentHeight ? -1 : 1;
                            }
                            double fontSize = this.CText.FontSize;
                            if (!this.SelfAdjustHeight(oh, height))
                            {
                                break;
                            }
                            if (this.CText.FontSize == fontSize || (height < this.ContentHeight ? -1 : 1) != num)
                            {
                                break;
                            }
                        }
                    }

                    for (int index = 0; index < 50 && height <= this.ContentHeight; ++index)
                    {
                        if (!this.SelfAdjustHeight(oh, height))
                        {
                            break;
                        }
                    }
                } catch (Exception ex) {
                    TraceLogger.Send(ex, "Size: {0} {1}", height.ToString(), this.CBox.RenderSize.Height.ToString());
                }
                this.CText.Visibility  = Visibility.Visible;
                this.CText2.Visibility = Visibility.Visible;
            }
            return(false);
        }
コード例 #33
0
ファイル: App.xaml.cs プロジェクト: zdmar/calculator
 private void OnSuspending(object sender, SuspendingEventArgs args)
 {
     TraceLogger.GetInstance().LogButtonUsage();
 }
コード例 #34
0
        public static void Main(string[] args)
        {
            ParseArgs(args, ToolName);

            InitializeLogger();

            PrintWelcome(ToolName);

            if (CreateContextMenuEntry)
            {
                // create context menu entry
                try
                {
                    TraceLogger.Info("Creating context menu entry for doc2x ...");
                    RegisterForContextMenu(GetContextMenuKey(ContextMenuInputExtension, ContextMenuText));
                    TraceLogger.Info("Succeeded.");
                }
                catch (Exception)
                {
                    TraceLogger.Info("Failed. Sorry :(");
                }
            }
            else
            {
                // convert
                try
                {
                    //copy processing file
                    ProcessingFile procFile = new ProcessingFile(InputFile);

                    //make output file name
                    if (ChoosenOutputFile == null)
                    {
                        if (InputFile.Contains("."))
                        {
                            ChoosenOutputFile = InputFile.Remove(InputFile.LastIndexOf(".")) + ".docx";
                        }
                        else
                        {
                            ChoosenOutputFile = InputFile + ".docx";
                        }
                    }

                    //open the reader
                    using (StructuredStorageReader reader = new StructuredStorageReader(procFile.File.FullName))
                    {
                        //parse the input document
                        WordDocument doc = new WordDocument(reader);

                        //prepare the output document
                        OpenXmlPackage.DocumentType outType = Converter.DetectOutputType(doc);
                        string conformOutputFile            = Converter.GetConformFilename(ChoosenOutputFile, outType);
                        WordprocessingDocument docx         = WordprocessingDocument.Create(conformOutputFile, outType);

                        //start time
                        DateTime start = DateTime.Now;
                        TraceLogger.Info("Converting file {0} into {1}", InputFile, conformOutputFile);

                        //convert the document
                        Converter.Convert(doc, docx);

                        DateTime end  = DateTime.Now;
                        TimeSpan diff = end.Subtract(start);
                        TraceLogger.Info("Conversion of file {0} finished in {1} seconds", InputFile, diff.TotalSeconds.ToString(CultureInfo.InvariantCulture));
                    }
                }
                catch (DirectoryNotFoundException ex)
                {
                    TraceLogger.Error(ex.Message);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (FileNotFoundException ex)
                {
                    TraceLogger.Error(ex.Message);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (ReadBytesAmountMismatchException ex)
                {
                    TraceLogger.Error("Input file {0} is not a valid Microsoft Word 97-2003 file.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (MagicNumberException ex)
                {
                    TraceLogger.Error("Input file {0} is not a valid Microsoft Word 97-2003 file.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (UnspportedFileVersionException ex)
                {
                    TraceLogger.Error("File {0} has been created with a Word version older than Word 97.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (ByteParseException ex)
                {
                    TraceLogger.Error("Input file {0} is not a valid Microsoft Word 97-2003 file.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (MappingException ex)
                {
                    TraceLogger.Error("There was an error while converting file {0}: {1}", InputFile, ex.Message);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (ZipCreationException ex)
                {
                    TraceLogger.Error("Could not create output file {0}.", ChoosenOutputFile);
                    //TraceLogger.Error("Perhaps the specified outputfile was a directory or contained invalid characters.");
                    TraceLogger.Debug(ex.ToString());
                }
                catch (Exception ex)
                {
                    TraceLogger.Error("Conversion of file {0} failed.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
            }
        }
コード例 #35
0
        public Task LongCall()
        {
            int count = 0;

            lock (allActivationIds)
            {
                if (!allActivationIds.Contains(activationGuid))
                {
                    allActivationIds.Add(activationGuid);
                }
                count = allActivationIds.Count;
            }
            DateTime start = DateTime.UtcNow;
            TaskCompletionSource <bool> resolver = new TaskCompletionSource <bool>();

            RegisterTimer(TimerCallback, resolver, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(-1));
            return(resolver.Task.ContinueWith(
                       (_) =>
            {
                DateTime stop = DateTime.UtcNow;
                calls.Add(new Tuple <DateTime, DateTime>(start, stop));
                logger.Info(((stop - start).TotalMilliseconds).ToString());
                logger.Info("Start {0}, stop {1}, duration {2}. #act {3}", TraceLogger.PrintDate(start), TraceLogger.PrintDate(stop), (stop - start), count);
            }));
        }
コード例 #36
0
        public async Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitTableVersion, TraceLogger traceLogger)
        {
            logger       = traceLogger;
            deploymentId = config.DeploymentId;

            if (logger.IsVerbose3)
            {
                logger.Verbose3("SqlMembershipTable.InitializeMembershipTable called.");
            }

            //This initializes all of Orleans operational queries from the database using a well known view
            //and assumes the database with appropriate defintions exists already.
            orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString);

            // even if I am not the one who created the table,
            // try to insert an initial table version if it is not already there,
            // so we always have a first table version row, before this silo starts working.
            if (tryInitTableVersion)
            {
                var wasCreated = await InitTableAsync();

                if (wasCreated)
                {
                    logger.Info("Created new table version row.");
                }
            }
        }
コード例 #37
0
ファイル: AzureSilo.cs プロジェクト: supwar/orleans
        /// <summary>
        /// Initialize this Orleans silo for execution with the specified Azure deploymentId and role instance
        /// </summary>
        /// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
        /// <returns><c>true</c> is the silo startup was successfull</returns>
        public bool Start(ClusterConfiguration config)
        {
            // Program ident
            Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);

            // Read endpoint info for this instance from Azure config
            string instanceName = serviceRuntimeWrapper.InstanceName;

            // Configure this Orleans silo instance

            if (config == null)
            {
                host = new SiloHost(instanceName);
                host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
            }
            else
            {
                host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
            }

            IPEndPoint myEndpoint    = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
            IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);

            host.SetSiloType(Silo.SiloType.Secondary);

            int generation = SiloAddress.AllocateNewGeneration();

            // Bootstrap this Orleans silo instance

            myEntry = new SiloInstanceTableEntry
            {
                DeploymentId = serviceRuntimeWrapper.DeploymentId,
                Address      = myEndpoint.Address.ToString(),
                Port         = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
                Generation   = generation.ToString(CultureInfo.InvariantCulture),

                HostName  = host.Config.GetConfigurationForNode(host.Name).DNSHostName,
                ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),

                RoleName     = serviceRuntimeWrapper.RoleName,
                InstanceName = instanceName,
                UpdateZone   = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
                FaultZone    = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
                StartTime    = TraceLogger.PrintDate(DateTime.UtcNow),

                PartitionKey = serviceRuntimeWrapper.DeploymentId,
                RowKey       = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
            };

            var connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);

            try
            {
                siloInstanceManager = OrleansSiloInstanceManager.GetManager(
                    serviceRuntimeWrapper.DeploymentId, connectionString).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
            }
            catch (Exception exc)
            {
                var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
                                          TraceLogger.PrintException(exc));
                Trace.TraceError(error);
                logger.Error(ErrorCode.AzureTable_34, error, exc);
                throw new OrleansException(error, exc);
            }

            // Always use Azure table for membership when running silo in Azure
            host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
            host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
            host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
            siloInstanceManager.RegisterSiloInstance(myEntry);

            // Initialise this Orleans silo instance
            host.SetDeploymentId(serviceRuntimeWrapper.DeploymentId, connectionString);
            host.SetSiloEndpoint(myEndpoint, generation);
            host.SetProxyEndpoint(proxyEndpoint);

            host.InitializeOrleansSilo();
            logger.Info(ErrorCode.Runtime_Error_100288, "Successfully initialized Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
            return(StartSilo());
        }
コード例 #38
0
 public void Initialize(TraceLogger logger)
 {
 }
コード例 #39
0
 public async Task InitializeGatewayListProvider(ClientConfiguration conf, TraceLogger traceLogger)
 {
     config = conf;
     siloInstanceManager = await OrleansSiloInstanceManager.GetManager(conf.DeploymentId, conf.DataConnectionString);
 }
コード例 #40
0
            public async Task <GrainStateRecord> Read(string partitionKey, string rowKey)
            {
                if (logger.IsVerbose3)
                {
                    logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName);
                }
                try
                {
                    Tuple <GrainStateEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey).ConfigureAwait(false);

                    if (data == null || data.Item1 == null)
                    {
                        if (logger.IsVerbose2)
                        {
                            logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName);
                        }
                        return(null);
                    }
                    GrainStateEntity stateEntity = data.Item1;
                    var record = new GrainStateRecord {
                        Entity = stateEntity, ETag = data.Item2
                    };
                    if (logger.IsVerbose3)
                    {
                        logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag);
                    }
                    return(record);
                }
                catch (Exception exc)
                {
                    if (AzureStorageUtils.TableStorageDataNotFound(exc))
                    {
                        if (logger.IsVerbose2)
                        {
                            logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, TraceLogger.PrintException(exc));
                        }
                        return(null);  // No data
                    }
                    throw;
                }
            }
コード例 #41
0
        internal void LoadProviders(HttpContextBase http)
        {
            // if there is no section found, then create one
            if (ConfigSection == null)
            {
                //create a new section with the default settings
                ConfigSection = new ClientDependencySection();
            }

            FileRegistrationProviderCollection        = new FileRegistrationProviderCollection();
            CompositeFileProcessingProviderCollection = new CompositeFileProcessingProviderCollection();
            MvcRendererCollection     = new RendererCollection();
            FileMapProviderCollection = new FileMapProviderCollection();

            var rootPath = HttpRuntime.AppDomainAppVirtualPath ?? "/";


            //need to check if it's an http path or a lambda path
            var path = ConfigSection.CompositeFileElement.CompositeFileHandlerPath;

            CompositeFileHandlerPath = path.StartsWith("~/")
                ? VirtualPathUtility.ToAbsolute(ConfigSection.CompositeFileElement.CompositeFileHandlerPath, rootPath)
                : ConfigSection.CompositeFileElement.CompositeFileHandlerPath;

            //load the providers from the config, if there isn't config sections then add default providers
            // and then load the defaults.

            LoadDefaultCompositeFileConfig(ConfigSection, http);

            ////Here we need to detect legacy settings
            //if (ConfigSection.CompositeFileElement.DefaultFileProcessingProviderLegacy != "CompositeFileProcessor"
            //    && ConfigSection.CompositeFileElement.DefaultFileProcessingProvider == "CompositeFileProcessor")
            //{
            //    //if the legacy section is not the default and the non-legacy section IS the default, then use the legacy section
            //    DefaultCompositeFileProcessingProvider = CompositeFileProcessingProviderCollection[ConfigSection.CompositeFileElement.DefaultFileProcessingProviderLegacy];
            //}
            //else
            //{
            //    DefaultCompositeFileProcessingProvider = CompositeFileProcessingProviderCollection[ConfigSection.CompositeFileElement.DefaultFileProcessingProvider];
            //}
            DefaultCompositeFileProcessingProvider = CompositeFileProcessingProviderCollection[ConfigSection.CompositeFileElement.DefaultFileProcessingProvider];
            if (DefaultCompositeFileProcessingProvider == null)
            {
                throw new ProviderException("Unable to load default composite file provider");
            }

            LoadDefaultFileMapConfig(ConfigSection, http);

            DefaultFileMapProvider = FileMapProviderCollection[ConfigSection.CompositeFileElement.DefaultFileMapProvider];
            if (DefaultFileMapProvider == null)
            {
                throw new ProviderException("Unable to load default file map provider");
            }

            LoadDefaultMvcFileConfig(ConfigSection);

            DefaultMvcRenderer = MvcRendererCollection[ConfigSection.MvcElement.DefaultRenderer];
            if (DefaultMvcRenderer == null)
            {
                throw new ProviderException("Unable to load default mvc renderer");
            }

            LoadDefaultFileRegConfig(ConfigSection);

            DefaultFileRegistrationProvider = FileRegistrationProviderCollection[ConfigSection.FileRegistrationElement.DefaultProvider];
            if (DefaultFileRegistrationProvider == null)
            {
                throw new ProviderException("Unable to load default file registration provider");
            }

            if (string.IsNullOrEmpty(ConfigSection.LoggerType))
            {
                Logger = new TraceLogger();
            }
            else
            {
                var t = Type.GetType(ConfigSection.LoggerType);
                if (!typeof(ILogger).IsAssignableFrom(t))
                {
                    throw new ArgumentException("The loggerType '" + ConfigSection.LoggerType + "' does not inherit from ClientDependency.Core.Logging.ILogger");
                }

                Logger = (ILogger)Activator.CreateInstance(t);
            }
        }
コード例 #42
0
 public SiloInstanceTableManagerTests()
 {
     logger = TraceLogger.GetLogger("SiloInstanceTableManagerTests", TraceLogger.LoggerType.Application);
 }
コード例 #43
0
 public static void ClassInitialize(TestContext testContext)
 {
     TraceLogger.Initialize(new NodeConfiguration());
 }
コード例 #44
0
        private void ImportCoreOuter(DataImporterContext ctx)
        {
            var customer = _services.WorkContext.CurrentCustomer;
            var profile  = ctx.Request.Profile;
            var logPath  = profile.GetImportLogPath();

            FileSystemHelper.DeleteFile(logPath);

            using (var logger = new TraceLogger(logPath))
            {
                var scopes = new List <IDisposable>();

                try
                {
                    var files        = profile.GetImportFiles(profile.ImportRelatedData);
                    var groupedFiles = files.GroupBy(x => x.RelatedType);

                    if (!files.Any())
                    {
                        throw new SmartException("No files to import.");
                    }

                    if (!HasPermission(ctx))
                    {
                        throw new SmartException("You do not have permission to perform the selected import.");
                    }

                    _dbCache.Enabled = false;
                    scopes.Add(_localizedEntityService.BeginScope());
                    scopes.Add(_urlRecordService.BeginScope());

                    ctx.Log      = logger;
                    ctx.Importer = _importerFactory(profile.EntityType);

                    ctx.ExecuteContext.Request = ctx.Request;
                    ctx.ExecuteContext.DataExchangeSettings = _dataExchangeSettings.Value;
                    ctx.ExecuteContext.Services             = _services;
                    ctx.ExecuteContext.Log           = logger;
                    ctx.ExecuteContext.Languages     = _languageService.GetAllLanguages(true);
                    ctx.ExecuteContext.UpdateOnly    = profile.UpdateOnly;
                    ctx.ExecuteContext.KeyFieldNames = profile.KeyFieldNames.SplitSafe(",");
                    ctx.ExecuteContext.ImportFolder  = profile.GetImportFolder();
                    ctx.ExecuteContext.ExtraData     = XmlHelper.Deserialize <ImportExtraData>(profile.ExtraData);

                    var sb = new StringBuilder();
                    sb.AppendLine();
                    sb.AppendLine(new string('-', 40));
                    sb.AppendLine("Smartstore: v." + SmartStoreVersion.CurrentFullVersion);
                    sb.AppendLine("Import profile: {0} {1}".FormatInvariant(profile.Name, profile.Id == 0 ? " (volatile)" : $" (Id {profile.Id})"));
                    foreach (var fileGroup in groupedFiles)
                    {
                        var entityName = fileGroup.Key.HasValue ? fileGroup.Key.Value.ToString() : profile.EntityType.ToString();
                        var fileNames  = string.Join(", ", fileGroup.Select(x => x.Name));
                        sb.AppendLine("{0} files: {1}".FormatInvariant(entityName, fileNames));
                    }
                    sb.Append("Executed by: " + customer.Email.NullEmpty() ?? customer.SystemName.NaIfEmpty());
                    ctx.Log.Info(sb.ToString());

                    _services.EventPublisher.Publish(new ImportExecutingEvent(ctx.ExecuteContext));

                    foreach (var fileGroup in groupedFiles)
                    {
                        ctx.ExecuteContext.Result = ctx.Results[fileGroup.Key.HasValue ? fileGroup.Key.Value.ToString() : string.Empty] = new ImportResult();

                        fileGroup.Each(x => ImportCoreInner(ctx, x));
                    }
                }
                catch (Exception ex)
                {
                    logger.ErrorsAll(ex);
                }
                finally
                {
                    try
                    {
                        _dbCache.Enabled = true;
                        scopes.Each(x => x.Dispose());

                        _services.EventPublisher.Publish(new ImportExecutedEvent(ctx.ExecuteContext));
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorsAll(ex);
                    }

                    try
                    {
                        // Database context sharing problem: if there are entities in modified state left by the provider due to SaveChanges failure,
                        // then all subsequent SaveChanges would fail too (e.g. IImportProfileService.UpdateImportProfile, IScheduledTaskService.UpdateTask...).
                        // so whatever it is, detach\dispose all what the tracker still has tracked.

                        _services.DbContext.DetachAll(false);
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorsAll(ex);
                    }

                    try
                    {
                        SendCompletionEmail(ctx);
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorsAll(ex);
                    }

                    try
                    {
                        LogResults(ctx);
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorsAll(ex);
                    }

                    try
                    {
                        if (ctx.Results.TryGetValue(string.Empty, out var result))
                        {
                            profile.ResultInfo = XmlHelper.Serialize(result.Clone());
                            _importProfileService.UpdateImportProfile(profile);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorsAll(ex);
                    }

                    try
                    {
                        ctx.Request.CustomData.Clear();
                        ctx.Results.Clear();
                        ctx.Log = null;
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorsAll(ex);
                    }
                }
            }
        }
コード例 #45
0
 public override Task OnActivateAsync()
 {
     logger = TraceLogger.GetLogger("ManagementGrain", TraceLogger.LoggerType.Runtime);
     return(TaskDone.Done);
 }
コード例 #46
0
        internal override void Load(XmlElement root)
        {
            var logger = TraceLogger.GetLogger("OrleansConfiguration", TraceLogger.LoggerType.Runtime);

            SeedNodes = new List <IPEndPoint>();

            XmlElement child;

            foreach (XmlNode c in root.ChildNodes)
            {
                child = c as XmlElement;
                if (child != null && child.LocalName == "Networking")
                {
                    Subnet = child.HasAttribute("Subnet")
                        ? ConfigUtilities.ParseSubnet(child.GetAttribute("Subnet"), "Invalid Subnet")
                        : null;
                }
            }
            foreach (XmlNode c in root.ChildNodes)
            {
                child = c as XmlElement;
                if (child == null)
                {
                    continue;                // Skip comment lines
                }
                switch (child.LocalName)
                {
                case "Liveness":
                    if (child.HasAttribute("LivenessEnabled"))
                    {
                        LivenessEnabled = ConfigUtilities.ParseBool(child.GetAttribute("LivenessEnabled"),
                                                                    "Invalid boolean value for the LivenessEnabled attribute on the Liveness element");
                    }
                    if (child.HasAttribute("ProbeTimeout"))
                    {
                        ProbeTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ProbeTimeout"),
                                                                     "Invalid time value for the ProbeTimeout attribute on the Liveness element");
                    }
                    if (child.HasAttribute("TableRefreshTimeout"))
                    {
                        TableRefreshTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TableRefreshTimeout"),
                                                                            "Invalid time value for the TableRefreshTimeout attribute on the Liveness element");
                    }
                    if (child.HasAttribute("DeathVoteExpirationTimeout"))
                    {
                        DeathVoteExpirationTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeathVoteExpirationTimeout"),
                                                                                   "Invalid time value for the DeathVoteExpirationTimeout attribute on the Liveness element");
                    }
                    if (child.HasAttribute("NumMissedProbesLimit"))
                    {
                        NumMissedProbesLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedProbesLimit"),
                                                                        "Invalid integer value for the NumMissedIAmAlive attribute on the Liveness element");
                    }
                    if (child.HasAttribute("NumProbedSilos"))
                    {
                        NumProbedSilos = ConfigUtilities.ParseInt(child.GetAttribute("NumProbedSilos"),
                                                                  "Invalid integer value for the NumProbedSilos attribute on the Liveness element");
                    }
                    if (child.HasAttribute("NumVotesForDeathDeclaration"))
                    {
                        NumVotesForDeathDeclaration = ConfigUtilities.ParseInt(child.GetAttribute("NumVotesForDeathDeclaration"),
                                                                               "Invalid integer value for the NumVotesForDeathDeclaration attribute on the Liveness element");
                    }
                    if (child.HasAttribute("UseLivenessGossip"))
                    {
                        UseLivenessGossip = ConfigUtilities.ParseBool(child.GetAttribute("UseLivenessGossip"),
                                                                      "Invalid boolean value for the UseLivenessGossip attribute on the Liveness element");
                    }
                    if (child.HasAttribute("IAmAliveTablePublishTimeout"))
                    {
                        IAmAliveTablePublishTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("IAmAliveTablePublishTimeout"),
                                                                                    "Invalid time value for the IAmAliveTablePublishTimeout attribute on the Liveness element");
                    }
                    if (child.HasAttribute("NumMissedTableIAmAliveLimit"))
                    {
                        NumMissedTableIAmAliveLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedTableIAmAliveLimit"),
                                                                               "Invalid integer value for the NumMissedTableIAmAliveLimit attribute on the Liveness element");
                    }
                    if (child.HasAttribute("MaxJoinAttemptTime"))
                    {
                        MaxJoinAttemptTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxJoinAttemptTime"),
                                                                           "Invalid time value for the MaxJoinAttemptTime attribute on the Liveness element");
                    }
                    if (child.HasAttribute("ExpectedClusterSize"))
                    {
                        int expectedClusterSize = ConfigUtilities.ParseInt(child.GetAttribute("ExpectedClusterSize"),
                                                                           "Invalid integer value for the ExpectedClusterSize attribute on the Liveness element");
                        ExpectedClusterSizeConfigValue = new ConfigValue <int>(expectedClusterSize, false);
                    }
                    break;

                case "Azure":
                case "SystemStore":
                    if (child.LocalName == "Azure")
                    {
                        // Log warning about deprecated <Azure> element, but then continue on to parse it for connection string info
                        logger.Warn(ErrorCode.SiloConfigDeprecated, "The Azure element has been deprecated -- use SystemStore element instead.");
                    }

                    if (child.HasAttribute("SystemStoreType"))
                    {
                        var sst = child.GetAttribute("SystemStoreType");
                        if (!"None".Equals(sst, StringComparison.InvariantCultureIgnoreCase))
                        {
                            LivenessType = (LivenessProviderType)Enum.Parse(typeof(LivenessProviderType), sst);
                            ReminderServiceProviderType reminderServiceProviderType;
                            SetReminderServiceType(Enum.TryParse(sst, out reminderServiceProviderType)
                                    ? reminderServiceProviderType
                                    : ReminderServiceProviderType.Disabled);
                        }
                    }
                    if (child.HasAttribute("MembershipTableAssembly"))
                    {
                        MembershipTableAssembly = child.GetAttribute("MembershipTableAssembly");
                        if (LivenessType != LivenessProviderType.Custom)
                        {
                            throw new FormatException("SystemStoreType should be \"Custom\" when MembershipTableAssembly is specified");
                        }
                        if (MembershipTableAssembly.EndsWith(".dll"))
                        {
                            throw new FormatException("Use fully qualified assembly name for \"MembershipTableAssembly\"");
                        }
                    }
                    if (child.HasAttribute("ReminderTableAssembly"))
                    {
                        ReminderTableAssembly = child.GetAttribute("ReminderTableAssembly");
                        if (ReminderServiceType != ReminderServiceProviderType.Custom)
                        {
                            throw new FormatException("ReminderServiceType should be \"Custom\" when ReminderTableAssembly is specified");
                        }
                        if (ReminderTableAssembly.EndsWith(".dll"))
                        {
                            throw new FormatException("Use fully qualified assembly name for \"ReminderTableAssembly\"");
                        }
                    }
                    if (LivenessType == LivenessProviderType.Custom && string.IsNullOrEmpty(MembershipTableAssembly))
                    {
                        throw new FormatException("MembershipTableAssembly should be set when SystemStoreType is \"Custom\"");
                    }
                    if (ReminderServiceType == ReminderServiceProviderType.Custom && String.IsNullOrEmpty(ReminderTableAssembly))
                    {
                        throw new FormatException("ReminderTableAssembly should be set when ReminderServiceType is \"Custom\"");
                    }

                    if (child.HasAttribute("ServiceId"))
                    {
                        ServiceId = ConfigUtilities.ParseGuid(child.GetAttribute("ServiceId"),
                                                              "Invalid Guid value for the ServiceId attribute on the Azure element");
                    }
                    if (child.HasAttribute("DeploymentId"))
                    {
                        DeploymentId = child.GetAttribute("DeploymentId");
                    }
                    if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME))
                    {
                        DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME);
                        if (String.IsNullOrWhiteSpace(DataConnectionString))
                        {
                            throw new FormatException("SystemStore.DataConnectionString cannot be blank");
                        }
                    }
                    if (child.HasAttribute("MaxStorageBusyRetries"))
                    {
                        MaxStorageBusyRetries = ConfigUtilities.ParseInt(child.GetAttribute("MaxStorageBusyRetries"),
                                                                         "Invalid integer value for the MaxStorageBusyRetries attribute on the SystemStore element");
                    }
                    if (child.HasAttribute("UseMockReminderTable"))
                    {
                        MockReminderTableTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("UseMockReminderTable"), "Invalid timeout value");
                        UseMockReminderTable     = true;
                    }
                    break;

                case "SeedNode":
                    SeedNodes.Add(ConfigUtilities.ParseIPEndPoint(child, Subnet));
                    break;

                case "Messaging":
                    base.Load(child);
                    break;

                case "Application":
                    Application.Load(child, logger);
                    break;

                case "PlacementStrategy":
                    if (child.HasAttribute("DefaultPlacementStrategy"))
                    {
                        DefaultPlacementStrategy = child.GetAttribute("DefaultPlacementStrategy");
                    }
                    if (child.HasAttribute("DeploymentLoadPublisherRefreshTime"))
                    {
                        DeploymentLoadPublisherRefreshTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeploymentLoadPublisherRefreshTime"),
                                                                                           "Invalid time span value for PlacementStrategy.DeploymentLoadPublisherRefreshTime");
                    }
                    if (child.HasAttribute("ActivationCountBasedPlacementChooseOutOf"))
                    {
                        ActivationCountBasedPlacementChooseOutOf = ConfigUtilities.ParseInt(child.GetAttribute("ActivationCountBasedPlacementChooseOutOf"),
                                                                                            "Invalid ActivationCountBasedPlacementChooseOutOf setting");
                    }
                    break;

                case "Caching":
                    if (child.HasAttribute("CacheSize"))
                    {
                        CacheSize = ConfigUtilities.ParseInt(child.GetAttribute("CacheSize"),
                                                             "Invalid integer value for Caching.CacheSize");
                    }

                    if (child.HasAttribute("InitialTTL"))
                    {
                        InitialCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("InitialTTL"),
                                                                        "Invalid time value for Caching.InitialTTL");
                    }

                    if (child.HasAttribute("MaximumTTL"))
                    {
                        MaximumCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaximumTTL"),
                                                                        "Invalid time value for Caching.MaximumTTL");
                    }

                    if (child.HasAttribute("TTLExtensionFactor"))
                    {
                        CacheTTLExtensionFactor = ConfigUtilities.ParseDouble(child.GetAttribute("TTLExtensionFactor"),
                                                                              "Invalid double value for Caching.TTLExtensionFactor");
                    }
                    if (CacheTTLExtensionFactor <= 1.0)
                    {
                        throw new FormatException("Caching.TTLExtensionFactor must be greater than 1.0");
                    }

                    if (child.HasAttribute("DirectoryCachingStrategy"))
                    {
                        DirectoryCachingStrategy = ConfigUtilities.ParseEnum <DirectoryCachingStrategyType>(child.GetAttribute("DirectoryCachingStrategy"),
                                                                                                            "Invalid value for Caching.Strategy");
                    }

                    break;

                case "Directory":
                    if (child.HasAttribute("DirectoryLazyDeregistrationDelay"))
                    {
                        DirectoryLazyDeregistrationDelay = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DirectoryLazyDeregistrationDelay"),
                                                                                         "Invalid time span value for Directory.DirectoryLazyDeregistrationDelay");
                    }
                    if (child.HasAttribute("ClientRegistrationRefresh"))
                    {
                        ClientRegistrationRefresh = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientRegistrationRefresh"),
                                                                                  "Invalid time span value for Directory.ClientRegistrationRefresh");
                    }
                    break;

                default:
                    if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal))
                    {
                        var providerCategory = ProviderCategoryConfiguration.Load(child);

                        if (ProviderConfigurations.ContainsKey(providerCategory.Name))
                        {
                            var existingCategory = ProviderConfigurations[providerCategory.Name];
                            existingCategory.Merge(providerCategory);
                        }
                        else
                        {
                            ProviderConfigurations.Add(providerCategory.Name, providerCategory);
                        }
                    }
                    break;
                }
            }
        }
コード例 #47
0
ファイル: Program.cs プロジェクト: resgroup/B2XTranslator
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            ParseArgs(args, ToolName);

            InitializeLogger();

            PrintWelcome(ToolName, RevisionResource);

            if (CreateContextMenuEntry)
            {
                // create context menu entry
                try
                {
                    TraceLogger.Info("Creating context menu entry for ppt2x ...");
                    RegisterForContextMenu(GetContextMenuKey(ContextMenuInputExtension, ContextMenuText));
                    TraceLogger.Info("Succeeded.");
                }
                catch (Exception)
                {
                    TraceLogger.Info("Failed. Sorry :(");
                }
            }
            else
            {
                try
                {
                    if (InputFile.Contains("*.ppt"))
                    {
                        string[] files = Directory.GetFiles(InputFile.Replace("*.ppt", ""), "*.ppt");

                        foreach (String file in files)
                        {
                            if (new FileInfo(file).Extension.ToLower().EndsWith("ppt"))
                            {
                                ChoosenOutputFile = null;
                                processFile(file);
                            }
                        }
                    }
                    else
                    {
                        processFile(InputFile);
                    }
                }
                catch (ZipCreationException ex)
                {
                    TraceLogger.Error("Could not create output file {0}.", ChoosenOutputFile);
                    //TraceLogger.Error("Perhaps the specified outputfile was a directory or contained invalid characters.");
                    TraceLogger.Debug(ex.ToString());
                }
                catch (FileNotFoundException ex)
                {
                    TraceLogger.Error("Could not read input file {0}.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
                catch (MagicNumberException)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (InvalidStreamException e)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (InvalidRecordException)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (StreamNotFoundException e)
                {
                    TraceLogger.Error("Input file {0} is not a valid PowerPoint 97-2007 file.", InputFile);
                }
                catch (Exception ex)
                {
                    TraceLogger.Error("Conversion of file {0} failed.", InputFile);
                    TraceLogger.Debug(ex.ToString());
                }
            }

            TraceLogger.Info("End of program");
        }
コード例 #48
0
ファイル: SiloHost.cs プロジェクト: asd1355215911/orleans
 private void InitializeLogger(NodeConfiguration nodeCfg)
 {
     TraceLogger.Initialize(nodeCfg);
     logger = TraceLogger.GetLogger("OrleansSiloHost", TraceLogger.LoggerType.Runtime);
 }
コード例 #49
0
        private static void Run(CommandLineArgs arguments)
        {
            try
            {
                if (arguments.Task.Length < 3)
                {
                    throw new CommandLineException("Invalid Command");
                }
                var trace = new TraceLogger();

                if (arguments.Connection == null)
                {
                    // No Connection is supplied to ask for connection on command line
                    ServerConnection serverConnect        = new ServerConnection();
                    ServerConnection.Configuration config = serverConnect.GetServerConfiguration(arguments.IgnoreLocalPrincipal);

                    arguments.Connection = BuildConnectionString(config);

                    using (var serviceProxy = new OrganizationServiceProxy(config.OrganizationUri, config.HomeRealmUri, config.Credentials, config.DeviceCredentials))
                    {
                        // This statement is required to enable early-bound type support.
                        serviceProxy.EnableProxyTypes();
                        serviceProxy.Timeout = new TimeSpan(1, 0, 0);
                        RunTask(arguments, serviceProxy, trace);
                    }
                }
                else if (arguments.Connection == "")
                {
                    // Support for tasks that require no connection string such as pack
                    RunTask(arguments, null, trace);
                }
                else
                {
                    // Does the connection contain a password prompt?
                    var passwordMatch = Regex.Match(arguments.Connection, "Password=[*]+", RegexOptions.IgnoreCase);
                    if (passwordMatch.Success)
                    {
                        // Prompt for password
                        Console.WriteLine("Password required for connection {0}", arguments.Connection);
                        Console.Write("Password:"******"Password="******"Error connecting to the Organization Service Proxy: {0}", serviceProxy.LastCrmError));
                        }

                        serviceProxy.OrganizationServiceProxy.Timeout = new TimeSpan(1, 0, 0);
                        if (!serviceProxy.IsReady)
                        {
                            trace.WriteLine("Not Ready {0} {1}", serviceProxy.LastCrmError, serviceProxy.LastCrmException);
                        }

                        RunTask(arguments, serviceProxy, trace);
                    }
                }
            }
            catch (CommandLineException exception)
            {
                Console.WriteLine(exception.ArgumentHelp.Message);
                Console.WriteLine(exception.ArgumentHelp.GetHelpText(Console.BufferWidth));
            }
        }
コード例 #50
0
ファイル: SiloHost.cs プロジェクト: asd1355215911/orleans
        /// <summary>
        /// Report an error during silo startup.
        /// </summary>
        /// <remarks>
        /// Information on the silo startup issue will be logged to any attached Loggers,
        /// then a timestamped StartupError text file will be written to
        /// the current working directory (if possible).
        /// </remarks>
        /// <param name="exc">Exception which caused the silo startup issue.</param>
        public void ReportStartupError(Exception exc)
        {
            if (string.IsNullOrWhiteSpace(Name))
            {
                Name = "Silo";
            }

            var errMsg = "ERROR starting Orleans silo name=" + Name + " Exception=" + TraceLogger.PrintException(exc);

            if (logger != null)
            {
                logger.Error(ErrorCode.Runtime_Error_100105, errMsg, exc);
            }

            // Dump Startup error to a log file
            var          now        = DateTime.UtcNow;
            const string dateFormat = "yyyy-MM-dd-HH.mm.ss.fffZ";
            var          dateString = now.ToString(dateFormat, CultureInfo.InvariantCulture);
            var          startupLog = Name + "-StartupError-" + dateString + ".txt";

            try
            {
                File.AppendAllText(startupLog, dateString + "Z" + Environment.NewLine + errMsg);
            }
            catch (Exception exc2)
            {
                if (logger != null)
                {
                    logger.Error(ErrorCode.Runtime_Error_100106, "Error writing log file " + startupLog, exc2);
                }
            }

            TraceLogger.Flush();
        }
コード例 #51
0
        /// <summary>
        /// Remove or rename tag from suggestions when user control is tapped.
        /// </summary>
        /// <param name="sender">user control emitting this event</param>
        /// <param name="e">     event details</param>
        private void Tag_Action(object sender, RoutedEventArgs e)
        {
            var rt     = sender as RemovableTag;
            var rt_mdl = rt.DataContext as RemovableTagModel;

            string[] toRemove = new string[] { rt_mdl.Key };
            if ("DeleteTag".Equals(rt.Tag))
            {
                _model.SuggestedTags.RemoveAll(toRemove);
                // schedule all pages with this tag for tag removal
                if (rt_mdl.Tag != null)
                {
                    foreach (var tp in rt_mdl.Tag.Pages)
                    {
                        _model.OneNoteApp.TaggingService.Add(new TaggingJob(tp.ID, toRemove, TagOperation.SUBTRACT));
                    }
                    suggestedTags.Notification = rt_mdl.Tag.Pages.Count == 0 ? Properties.Resources.TagEditor_Popup_NothingTagged : string.Format(Properties.Resources.TagEditor_Popup_TaggingInProgress, rt_mdl.Tag.Pages.Count);
                    TraceLogger.Log(TraceCategory.Info(), "{0} page(s) enqueued for background tagging; Operation SUBTRACT {1}", rt_mdl.Tag.Pages.Count, toRemove[0]);
                }
                else
                {
                    suggestedTags.Notification = Properties.Resources.TagEditor_Popup_NothingTagged;
                }
            }
            else if ("RenameTag".Equals(rt.Tag))
            {
                _model.SuggestedTags.RemoveAll(toRemove);

                string[] newTagNames = (from tn in OneNotePageProxy.ParseTags(rt_mdl.LocalName) select TagFormatter.Format(tn)).ToArray();

                // create new tag models unless they already exist
                List <RemovableTagModel> newTagModels = new List <RemovableTagModel>();
                foreach (var newName in newTagNames)
                {
                    RemovableTagModel tagmodel;
                    if (!_model.SuggestedTags.TryGetValue(newName, out tagmodel))
                    {
                        tagmodel = new RemovableTagModel()
                        {
                            Tag = new TagPageSet(newName)
                        };
                        newTagModels.Add(tagmodel);
                    }
                    else if (tagmodel.Tag == null && rt_mdl.Tag != null)
                    {
                        tagmodel.Tag = new TagPageSet(newName);
                    }

                    if (rt_mdl.Tag != null)
                    {
                        // copy the pages into the new tag and update the tag count
                        foreach (var pg in rt_mdl.Tag.Pages)
                        {
                            tagmodel.Tag.Pages.Add(pg);
                        }
                        tagmodel.UseCount = tagmodel.Tag.Pages.Count;
                    }
                }
                _model.SuggestedTags.AddAll(newTagModels);

                if (rt_mdl.Tag != null)
                {
                    // remove the old tag and add new tag to the pages
                    foreach (var tp in rt_mdl.Tag.Pages)
                    {
                        _model.OneNoteApp.TaggingService.Add(new TaggingJob(tp.ID, toRemove, TagOperation.SUBTRACT));
                        _model.OneNoteApp.TaggingService.Add(new TaggingJob(tp.ID, newTagNames, TagOperation.UNITE));
                    }
                    suggestedTags.Notification = rt_mdl.Tag.Pages.Count == 0 ? Properties.Resources.TagEditor_Popup_NothingTagged : string.Format(Properties.Resources.TagEditor_Popup_TaggingInProgress, rt_mdl.Tag.Pages.Count);
                    TraceLogger.Log(TraceCategory.Info(), "{0} page(s) enqueued for background tagging; Operation UNITE {1} SUBTRACT {2}", rt_mdl.Tag.Pages.Count, string.Join(",", newTagNames), toRemove[0]);
                }
                else
                {
                    suggestedTags.Notification = Properties.Resources.TagEditor_Popup_NothingTagged;
                }
            }
            TraceLogger.Flush();
            _model.SaveChanges();
        }
コード例 #52
0
        public async Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitTableVersion, TraceLogger traceLogger)
        {
            logger = traceLogger;
            AzureTableDefaultPolicies.MaxBusyRetries = config.MaxStorageBusyRetries;
            TraceLogger.SetExceptionDecoder(typeof(StorageException), AzureStorageUtils.PrintStorageException);

            tableManager = await OrleansSiloInstanceManager.GetManager(
                config.DeploymentId, config.DataConnectionString);

            // even if I am not the one who created the table,
            // try to insert an initial table version if it is not already there,
            // so we always have a first table version row, before this silo starts working.
            if (tryInitTableVersion)
            {
                // ignore return value, since we don't care if I inserted it or not, as long as it is in there.
                bool created = await tableManager.TryCreateTableVersionEntryAsync();

                if (created)
                {
                    logger.Info("Created new table version row.");
                }
            }
        }
コード例 #53
0
        public LocalGrainDirectory(Silo silo)
        {
            log = TraceLogger.GetLogger("Orleans.GrainDirectory.LocalGrainDirectory");

            MyAddress          = silo.LocalMessageCenter.MyAddress;
            Scheduler          = silo.LocalScheduler;
            membershipRingList = new List <SiloAddress>();
            membershipCache    = new HashSet <SiloAddress>();

            silo.OrleansConfig.OnConfigChange("Globals/Caching", () =>
            {
                lock (membershipCache)
                {
                    DirectoryCache = GrainDirectoryCacheFactory <List <Tuple <SiloAddress, ActivationId> > > .CreateGrainDirectoryCache(silo.GlobalConfig);
                }
            });
            maintainer = GrainDirectoryCacheFactory <List <Tuple <SiloAddress, ActivationId> > > .CreateGrainDirectoryCacheMaintainer(this, DirectoryCache);

            if (silo.GlobalConfig.SeedNodes.Count > 0)
            {
                seed = silo.GlobalConfig.SeedNodes.Contains(MyAddress.Endpoint) ? MyAddress : SiloAddress.New(silo.GlobalConfig.SeedNodes[0], 0);
            }

            stopPreparationResolver = new TaskCompletionSource <bool>();
            DirectoryPartition      = new GrainDirectoryPartition();
            HandoffManager          = new GrainDirectoryHandoffManager(this, silo.GlobalConfig);

            RemGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceId);
            CacheValidator    = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorId);

            // add myself to the list of members
            AddServer(MyAddress);

            Func <SiloAddress, string> siloAddressPrint = (SiloAddress addr) =>
                                                          String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode());

            localLookups   = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED);
            localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES);
            fullLookups    = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED);

            RemoteLookupsSent     = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT);
            RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED);

            LocalDirectoryLookups   = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED);
            LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES);

            cacheLookups   = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED);
            cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES);
            StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () =>
            {
                long delta1 = 0, delta2 = 0;
                long curr1  = cacheSuccesses.GetCurrentValueAndDelta(out delta1);
                long curr2  = cacheLookups.GetCurrentValueAndDelta(out delta2);
                return(String.Format("{0}, Delta={1}",
                                     (curr2 != 0 ? (float)curr1 / (float)curr2 : 0)
                                     , (delta2 != 0 ? (float)delta1 / (float)delta2 : 0)));
            });

            CacheValidationsSent     = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT);
            CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED);

            registrationsIssued                  = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED);
            RegistrationsLocal                   = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL);
            RegistrationsRemoteSent              = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT);
            RegistrationsRemoteReceived          = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED);
            registrationsSingleActIssued         = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED);
            RegistrationsSingleActLocal          = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL);
            RegistrationsSingleActRemoteSent     = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT);
            RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED);
            unregistrationsIssued                = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED);
            UnregistrationsLocal                 = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL);
            UnregistrationsRemoteSent            = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT);
            UnregistrationsRemoteReceived        = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED);
            unregistrationsManyIssued            = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED);
            UnregistrationsManyRemoteSent        = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT);
            UnregistrationsManyRemoteReceived    = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED);

            directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count);
            IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor());
            FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100);
            FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => membershipRingList.Count == 0 ? 0 : ((float)100 / (float)membershipRingList.Count));
            IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => membershipRingList.Count);
            StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () =>
            {
                lock (membershipCache)
                {
                    return(Utils.EnumerableToString(membershipRingList, siloAddressPrint));
                }
            });
            StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(FindPredecessors(MyAddress, 1), siloAddressPrint));
            StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(FindSuccessors(MyAddress, 1), siloAddressPrint));
        }
コード例 #54
0
        private static MembershipEntry Parse(SiloInstanceTableEntry tableEntry)
        {
            var parse = new MembershipEntry
            {
                HostName = tableEntry.HostName,
                Status   = (SiloStatus)Enum.Parse(typeof(SiloStatus), tableEntry.Status)
            };

            if (!string.IsNullOrEmpty(tableEntry.ProxyPort))
            {
                parse.ProxyPort = int.Parse(tableEntry.ProxyPort);
            }

            int port = 0;

            if (!string.IsNullOrEmpty(tableEntry.Port))
            {
                int.TryParse(tableEntry.Port, out port);
            }

            int gen = 0;

            if (!string.IsNullOrEmpty(tableEntry.Generation))
            {
                int.TryParse(tableEntry.Generation, out gen);
            }

            parse.SiloAddress = SiloAddress.New(new IPEndPoint(IPAddress.Parse(tableEntry.Address), port), gen);

            parse.RoleName     = tableEntry.RoleName;
            parse.InstanceName = tableEntry.InstanceName;
            if (!string.IsNullOrEmpty(tableEntry.UpdateZone))
            {
                parse.UpdateZone = int.Parse(tableEntry.UpdateZone);
            }

            if (!string.IsNullOrEmpty(tableEntry.FaultZone))
            {
                parse.FaultZone = int.Parse(tableEntry.FaultZone);
            }

            parse.StartTime = !string.IsNullOrEmpty(tableEntry.StartTime) ?
                              TraceLogger.ParseDate(tableEntry.StartTime) : default(DateTime);

            parse.IAmAliveTime = !string.IsNullOrEmpty(tableEntry.IAmAliveTime) ?
                                 TraceLogger.ParseDate(tableEntry.IAmAliveTime) : default(DateTime);

            var suspectingSilos = new List <SiloAddress>();
            var suspectingTimes = new List <DateTime>();

            if (!string.IsNullOrEmpty(tableEntry.SuspectingSilos))
            {
                string[] silos = tableEntry.SuspectingSilos.Split('|');
                foreach (string silo in silos)
                {
                    suspectingSilos.Add(SiloAddress.FromParsableString(silo));
                }
            }

            if (!string.IsNullOrEmpty(tableEntry.SuspectingTimes))
            {
                string[] times = tableEntry.SuspectingTimes.Split('|');
                foreach (string time in times)
                {
                    suspectingTimes.Add(TraceLogger.ParseDate(time));
                }
            }

            if (suspectingSilos.Count != suspectingTimes.Count)
            {
                throw new OrleansException(String.Format("SuspectingSilos.Length of {0} as read from Azure table is not eqaul to SuspectingTimes.Length of {1}", suspectingSilos.Count, suspectingTimes.Count));
            }

            for (int i = 0; i < suspectingSilos.Count; i++)
            {
                parse.AddSuspector(suspectingSilos[i], suspectingTimes[i]);
            }

            return(parse);
        }
コード例 #55
0
 public Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitTableVersion, TraceLogger traceLogger)
 {
     logger.Info("InitializeMembershipTable {0}.", tryInitTableVersion);
     return(TaskDone.Done);
 }
コード例 #56
0
ファイル: June.cs プロジェクト: drguthals/CodeSpells
    virtual public void javaCompileAndRun()
    {
        try{
            string class_name = java_file_name.Split('.')[0];

            File.Delete(JuneConfig.java_files_path + "/" + class_name + ".class");
            //ProgramLogger.LogKV("filedeleted", JuneConfig.java_files_path + "/" + class_name + ".class");
            Process compile_process = Shell.shell_no_start("javac", "-classpath \"" + JuneConfig.june_files_path + "\" " + JuneConfig.java_files_path + "/" + java_file_name);
            compile_process.Start();

            var output = compile_process.StandardOutput.ReadToEnd();
            var error  = compile_process.StandardError.ReadToEnd();

            // need to free the resources for the process
            compile_process.WaitForExit();
            compile_process.Close();

            //		Popup.mainPopup.popup(""  + output + " " + error);

            if (!error.Equals(""))
            {
                success = false;
                FileLogger.Log("error launching Java process: " + error);
            }
            //ProgramLogger.LogKV("compile", getSpellName()+", "+success);

            if (!success)
            {
                is_stopped = true;
                TraceLogger.LogKV("failedspell", getSpellName());
                return;
            }


//          Process test = Shell.shell_no_start("java", "-version");
//          test.Start();
//
//          var output2 = test.StandardOutput.ReadToEnd();
//          var error2 = test.StandardError.ReadToEnd();
//
//          UnityEngine.Debug.Log (output2 + " " + error2);


            if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor)
            {
                UnityEngine.Debug.Log("java " + "-classpath \"" + JuneConfig.june_files_path + ";" + JuneConfig.java_files_path + "\" june.Caster " + class_name + " \"" + object_id + "\"");
                java_process = Shell.shell_no_start("java", "-classpath \"" + JuneConfig.june_files_path + ";" + JuneConfig.java_files_path + "\" june.Caster " + class_name + " \"" + object_id + "\"");
            }
            else
            {
                UnityEngine.Debug.Log("java " + "-classpath \"" + JuneConfig.june_files_path + ":" + JuneConfig.java_files_path + "\" june.Caster " + class_name + " \"" + object_id + "\"");
                java_process = Shell.shell_no_start("java", "-classpath \"" + JuneConfig.june_files_path + ":" + JuneConfig.java_files_path + "\" june.Caster " + class_name + " \"" + object_id + "\"");
            }
            java_process.Start();

            var output3 = java_process.StandardOutput.ReadToEnd();
            var error3  = java_process.StandardError.ReadToEnd();

            UnityEngine.Debug.Log(output3 + " " + error3);


            Boolean has_exited = Convert.ToBoolean(java_process.GetType().GetProperty("HasExited").GetValue(java_process, new object[] {}));
            while (!has_exited)
            {
                if (!isPlaying)
                {
                    Stop();
                }

                //UnityEngine.Debug.Log("Waiting for Java process to exit: ");

                Thread.Sleep(500);

                has_exited = Convert.ToBoolean(java_process.GetType().GetProperty("HasExited").GetValue(java_process, new object[] {}));
            }


            if (java_process.ExitCode != 0)
            {
                success = false;
            }

            // free resources for this process
            java_process.WaitForExit();
            java_process.Close();

            TraceLogger.LogKV("endspell", getSpellName());

            is_stopped = true;
        }catch (Exception e) {
            UnityEngine.Debug.Log(e);
        }
    }
コード例 #57
0
ファイル: BondSerializer.cs プロジェクト: felipegtx/orleans
 /// <summary>
 /// Initializes the external serializer
 /// </summary>
 /// <param name="logger">The logger to use to capture any serialization events</param>
 public void Initialize(TraceLogger logger)
 {
     this.logger = logger;
 }
コード例 #58
0
        public void Util_Properties()
        {
            string sval  = "";
            string vName = "";

            debug.WriteLine("Starting Test: Util_Properties");
            Util u = new Util();

            TraceLogger.EnableDebug = true;

            sval  = u.Hostname;
            vName = nameof(u.Hostname);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.CurrentUser.Name;
            vName = nameof(u.CurrentUser);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.CurrentUserHome;
            vName = nameof(u.CurrentUserHome);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.JulianDate.ToString();
            vName = nameof(u.JulianDate);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.UTCDate.ToString();
            vName = nameof(u.UTCDate);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.TimeZoneName.ToString();
            vName = nameof(u.TimeZoneName);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.TimeZoneOffset.ToString();
            vName = nameof(u.TimeZoneOffset);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.PlatformVersion.ToString();
            vName = nameof(u.PlatformVersion);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.BuildNumber.ToString();
            vName = nameof(u.BuildNumber);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.MajorVersion.ToString();
            vName = nameof(u.MajorVersion);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.MinorVersion.ToString();
            vName = nameof(u.MinorVersion);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.ServicePack.ToString();
            vName = nameof(u.ServicePack);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.SerialTraceFile.ToString();
            vName = nameof(u.SerialTraceFile);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            sval  = u.SerialTrace.ToString();
            vName = nameof(u.SerialTrace);
            TraceLogger.Debug($"\t{vName}: {sval}");
            Assert.IsFalse(sval == "", $"{vName} check");

            TraceLogger.Debug("\tTest Complete");
            TraceLogger.Debug("");
        }
コード例 #59
0
        public static async Task <GossipTableInstanceManager> GetManager(Guid globalServiceId, string storageConnectionString, TraceLogger logger)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            var instance = new GossipTableInstanceManager(globalServiceId, storageConnectionString, logger);

            try
            {
                await instance.storage.InitTableAsync()
                .WithTimeout(initTimeout).ConfigureAwait(false);
            }
            catch (TimeoutException te)
            {
                string errorMsg = String.Format("Unable to create or connect to the Azure table {0} in {1}",
                                                instance.TableName, initTimeout);
                instance.logger.Error(ErrorCode.AzureTable_32, errorMsg, te);
                throw new OrleansException(errorMsg, te);
            }
            catch (Exception ex)
            {
                string errorMsg = String.Format("Exception trying to create or connect to Azure table {0} : {1}",
                                                instance.TableName, ex.Message);
                instance.logger.Error(ErrorCode.AzureTable_33, errorMsg, ex);
                throw new OrleansException(errorMsg, ex);
            }
            return(instance);
        }
コード例 #60
0
ファイル: App.xaml.cs プロジェクト: zdmar/calculator
        private void OnAppLaunch(IActivatedEventArgs args, string argument)
        {
            // Uncomment the following lines to display frame-rate and per-frame CPU usage info.
            //#if _DEBUG
            //    if (IsDebuggerPresent())
            //    {
            //        DebugSettings->EnableFrameRateCounter = true;
            //    }
            //#endif

            args.SplashScreen.Dismissed += DismissedEventHandler;

            var           rootFrame = (Window.Current.Content as Frame);
            WeakReference weak      = new WeakReference(this);

            float minWindowWidth  = (float)((double)Resources[ApplicationResourceKeys.Globals.AppMinWindowWidth]);
            float minWindowHeight = (float)((double)Resources[ApplicationResourceKeys.Globals.AppMinWindowHeight]);
            Size  minWindowSize   = SizeHelper.FromDimensions(minWindowWidth, minWindowHeight);

            ApplicationView          appView       = ApplicationView.GetForCurrentView();
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

            // For very first launch, set the size of the calc as size of the default standard mode
            if (!localSettings.Values.ContainsKey("VeryFirstLaunch"))
            {
                localSettings.Values["VeryFirstLaunch"] = false;
                appView.SetPreferredMinSize(minWindowSize);
                appView.TryResizeView(minWindowSize);
            }
            else
            {
                ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto;
            }

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")) // PC Family
                {
                    // Disable the system view activation policy during the first launch of the app
                    // only for PC family devices and not for phone family devices
                    try
                    {
                        ApplicationViewSwitcher.DisableSystemViewActivationPolicy();
                    }
                    catch (Exception)
                    {
                        // Log that DisableSystemViewActionPolicy didn't work
                    }
                }

                // Create a Frame to act as the navigation context
                rootFrame = App.CreateFrame();

                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), argument))
                {
                    // We couldn't navigate to the main page, kill the app so we have a good
                    // stack to debug
                    throw new SystemException();
                }

                SetMinWindowSizeAndThemeAndActivate(rootFrame, minWindowSize);
                m_mainViewId = ApplicationView.GetForCurrentView().Id;
                AddWindowToMap(WindowFrameService.CreateNewWindowFrameService(rootFrame, false, weak));
            }
            else
            {
                // For first launch, LaunchStart is logged in constructor, this is for subsequent launches.

                // !Phone check is required because even in continuum mode user interaction mode is Mouse not Touch
                if ((UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse) &&
                    (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
                {
                    // If the pre-launch hasn't happened then allow for the new window/view creation
                    if (!m_preLaunched)
                    {
                        var newCoreAppView = CoreApplication.CreateNewView();
                        _ = newCoreAppView.Dispatcher.RunAsync(
                            CoreDispatcherPriority.Normal, async() =>
                        {
                            var that = weak.Target as App;
                            if (that != null)
                            {
                                var newRootFrame = App.CreateFrame();

                                SetMinWindowSizeAndThemeAndActivate(newRootFrame, minWindowSize);

                                if (!newRootFrame.Navigate(typeof(MainPage), argument))
                                {
                                    // We couldn't navigate to the main page, kill the app so we have a good
                                    // stack to debug
                                    throw new SystemException();
                                }

                                var frameService = WindowFrameService.CreateNewWindowFrameService(newRootFrame, true, weak);
                                that.AddWindowToMap(frameService);

                                var dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

                                // CSHARP_MIGRATION_ANNOTATION:
                                // class SafeFrameWindowCreation is being interpreted into a IDisposable class
                                // in order to enhance its RAII capability that was written in C++/CX
                                using (var safeFrameServiceCreation = new SafeFrameWindowCreation(frameService, that))
                                {
                                    int newWindowId = ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread());

                                    ActivationViewSwitcher activationViewSwitcher = null;
                                    var activateEventArgs = (args as IViewSwitcherProvider);
                                    if (activateEventArgs != null)
                                    {
                                        activationViewSwitcher = activateEventArgs.ViewSwitcher;
                                    }

                                    if (activationViewSwitcher != null)
                                    {
                                        _ = activationViewSwitcher.ShowAsStandaloneAsync(newWindowId, ViewSizePreference.Default);
                                        safeFrameServiceCreation.SetOperationSuccess(true);
                                    }
                                    else
                                    {
                                        var activatedEventArgs = (args as IApplicationViewActivatedEventArgs);
                                        if ((activatedEventArgs != null) && (activatedEventArgs.CurrentlyShownApplicationViewId != 0))
                                        {
                                            // CSHARP_MIGRATION_ANNOTATION:
                                            // here we don't use ContinueWith() to interpret origin code because we would like to
                                            // pursue the design of class SafeFrameWindowCreate whichi was using RAII to ensure
                                            // some states get handled properly when its instance is being destructed.
                                            //
                                            // To achieve that, SafeFrameWindowCreate has been reinterpreted using IDisposable
                                            // pattern, which forces we use below way to keep async works being controlled within
                                            // a same code block.
                                            var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
                                                frameService.GetViewId(),
                                                ViewSizePreference.Default,
                                                activatedEventArgs.CurrentlyShownApplicationViewId,
                                                ViewSizePreference.Default);
                                            // SafeFrameServiceCreation is used to automatically remove the frame
                                            // from the list of frames if something goes bad.
                                            safeFrameServiceCreation.SetOperationSuccess(viewShown);
                                        }
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        ActivationViewSwitcher activationViewSwitcher = null;
                        var activateEventArgs = (args as IViewSwitcherProvider);
                        if (activateEventArgs != null)
                        {
                            activationViewSwitcher = activateEventArgs.ViewSwitcher;
                        }

                        if (activationViewSwitcher != null)
                        {
                            _ = activationViewSwitcher.ShowAsStandaloneAsync(
                                ApplicationView.GetApplicationViewIdForWindow(CoreWindow.GetForCurrentThread()), ViewSizePreference.Default);
                        }
                        else
                        {
                            TraceLogger.GetInstance().LogError(ViewMode.None, "App.OnAppLaunch", "Null_ActivationViewSwitcher");
                        }
                    }
                    // Set the preLaunched flag to false
                    m_preLaunched = false;
                }
                else // for touch devices
                {
                    if (rootFrame.Content == null)
                    {
                        // When the navigation stack isn't restored navigate to the first page,
                        // configuring the new page by passing required information as a navigation
                        // parameter
                        if (!rootFrame.Navigate(typeof(MainPage), argument))
                        {
                            // We couldn't navigate to the main page,
                            // kill the app so we have a good stack to debug
                            throw new SystemException();
                        }
                    }
                    if (ApplicationView.GetForCurrentView().ViewMode != ApplicationViewMode.CompactOverlay)
                    {
                        if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
                        {
                            // for tablet mode: since system view activation policy is disabled so do ShowAsStandaloneAsync if activationViewSwitcher exists in
                            // activationArgs
                            ActivationViewSwitcher activationViewSwitcher = null;
                            var activateEventArgs = (args as IViewSwitcherProvider);
                            if (activateEventArgs != null)
                            {
                                activationViewSwitcher = activateEventArgs.ViewSwitcher;
                            }
                            if (activationViewSwitcher != null)
                            {
                                var viewId = (args as IApplicationViewActivatedEventArgs).CurrentlyShownApplicationViewId;
                                if (viewId != 0)
                                {
                                    _ = activationViewSwitcher.ShowAsStandaloneAsync(viewId);
                                }
                            }
                        }
                        // Ensure the current window is active
                        Window.Current.Activate();
                    }
                }
            }
        }