예제 #1
0
 public EventSourcingDomainRepository(IEventStore eventStore,
                                      IEventPublisher publisher,
                                      ISnapshotProvider snapshotProvider) : base(publisher)
 {
     this.eventStore       = eventStore;
     this.snapshotProvider = snapshotProvider;
 }
예제 #2
0
        /// <summary>
        /// Returns an XMl representation of special objects on the system.
        /// The only real use-case we can imagine for now is the list of NT VSS providers
        ///     (System state, Exchange and SQLServer providers, maybe HyperV vm images)
        /// Another use case (not studied yet) would be VMWare®© storage API
        /// </summary>

        /*internal static string BuildObjectsList(){
         *      string xml = "";
         *      xml += "<objects name=\"/\" type=\"\" version=\"\">";
         *      ISnapshotProvider provider = SnapshotProvider.GetProvider();
         *      foreach(ISnapshot sn in provider.ListSpecialObjects()){
         *              xml += "<object name=\""+sn.Name+"\"  path=\""+sn.Path+"\" version=\""+sn.Version+"\" type=\""+sn.Type+"\">";
         *              foreach(ISnapshot childSn in sn.ChildComponents)
         *                      xml += "<childObject name=\""+childSn.Name+"\"  path=\""+childSn.Path+"\" version=\""+childSn.Version+"\" type=\""+childSn.Type+"\" leaf=\"true\"/>";
         *              xml += "</object>";
         *      }
         *      xml += "</objects>";
         *      return xml;
         * }*/

        internal static string BuildObjectsList()
        {
            string xml = "";

            xml += "{name:\"VSS Writers\", type:\"\", version:\"\", children:[";
            if (!Utilities.PlatForm.IsUnixClient())
            {
                ISnapshotProvider provider = SnapshotProvider.GetProvider("VSS");
                List <ISnapshot>  spos     = provider.ListSpecialObjects();
                if (spos != null)
                {
                    foreach (ISnapshot sn in spos)
                    {
                        xml += "{name:\"" + sn.Path + "\",  path:\"" + sn.MountPoint + "\", version:\"" + sn.Version + "\", type:\"" + sn.Type + "\", disabled:\"" + sn.Disabled + "\", checked:false, children:[";
                        foreach (ISnapshot childSn in sn.ChildComponents)
                        {
                            xml += "{name:\"" + childSn.Path + "\",  path:\"" + childSn.MountPoint + "\", version:\"" + childSn.Version + "\", type:\"" + childSn.Type + "\", leaf:\"true\", disabled:\"" + childSn.Disabled
                                   + "\", icon:\"" + ((childSn.Icon == null)? "" : "data:image/x-windows-bmp;base64," + Convert.ToBase64String(childSn.Icon)) + "\"";
                            if (childSn.Disabled == false)
                            {
                                xml += ", checked:false";
                            }
                            xml += "},";
                        }
                        xml += "]},";
                    }
                }
            }
            xml += "]}";

            return(xml);
        }
예제 #3
0
 public AccountController(ISnapshotProvider <AccountSnapshot> snapshotProvider,
                          IQueryFilterService <AccountSnapshot> queryFilterService,
                          IGlobalsProvider globalsProvider)
 {
     _snapshotProvider   = snapshotProvider;
     _queryFilterService = queryFilterService;
     _globalsProvider    = globalsProvider;
 }
예제 #4
0
        protected override BitmapSource[] CaptureFrames(ISnapshotProvider snapshotProvider, Rect clippingRectangle, Color shadeColor, IProgressScope progress, Func <bool> getIsCancelled)
        {
            var frame1 = this.PrintVersionTag(snapshotProvider.Snapshot(clippingRectangle, this.SampleFactor, shadeColor),
                                              this.Owner.Owner.TankInstance);

            var frame2 = this.PrintVersionTag(this.Owner.Owner.AlternativeSnapshotProvider.Snapshot(clippingRectangle, this.SampleFactor, shadeColor),
                                              this.Owner.Owner.AlternativeTankInstance);

            return(new[] { frame1, frame2 });
        }
 protected override BitmapSource[] CaptureFrames(ISnapshotProvider snapshotProvider, Rect clippingRectangle, Color shadeColor, IProgressScope progress, Func <bool> getIsCancelled)
 {
     return(snapshotProvider.YawAnimationSnapshot(clippingRectangle,
                                                  this.SampleFactor,
                                                  shadeColor,
                                                  this.RotationSpeed,
                                                  this.AnimationFramerate,
                                                  progress,
                                                  getIsCancelled));
 }
        public MultipleSinkChain(string id, string name, ISnapshotProvider source, params ISnapshotConsumer[] sinks)
        {
            Name = name;

            Id = id;

            _source = source;

            _sinks = sinks;
        }
예제 #7
0
        public void AddProvider(ISnapshotProvider snapshotProvider)
        {
            Argument.IsNotNull(() => snapshotProvider);

#if DEBUG
            Log.Debug($"[{Scope}] Adding provider {snapshotProvider.GetType()} to the SnapshotManager (Scope = '{Scope ?? "null"}')");
#endif

            lock (_providers)
            {
                _providers.Add(snapshotProvider);
            }

            SnapshotProviderAdded.SafeInvoke(this, new SnapshotProviderEventArgs(snapshotProvider));
        }
예제 #8
0
 /// <summary>
 /// Creates new instance.
 /// </summary>
 /// <param name="store">The underlaying event store.</param>
 /// <param name="formatter">The formatter for serializing and deserializing event payloads.</param>
 /// <param name="factory">The aggregate root factory.</param>
 /// <param name="eventDispatcher">The dispatcher for newly created events in the aggregates.</param>
 /// <param name="snapshotProvider">The snapshot provider.</param>
 /// <param name="snapshotStore">The store for snapshots.</param>
 public AggregateRootRepository(IEventStore store, IFormatter formatter, IAggregateRootFactory <T> factory, IEventDispatcher eventDispatcher,
                                ISnapshotProvider snapshotProvider, ISnapshotStore snapshotStore)
 {
     Ensure.NotNull(store, "store");
     Ensure.NotNull(formatter, "formatter");
     Ensure.NotNull(factory, "factory");
     Ensure.NotNull(eventDispatcher, "eventDispatcher");
     Ensure.NotNull(snapshotProvider, "snapshotProvider");
     Ensure.NotNull(snapshotStore, "snapshotStore");
     this.store            = store;
     this.formatter        = formatter;
     this.factory          = factory;
     this.eventDispatcher  = eventDispatcher;
     this.snapshotProvider = snapshotProvider;
     this.snapshotStore    = snapshotStore;
 }
예제 #9
0
        public Host(ILogger <Host> logger, ITimer timer,
                    ISnapshotProvider snapshotProvider,
                    IFileHandler fileHandler, IOptions <Settings> settings)
        {
            this.logger      = logger;
            this.timer       = timer;
            this.fileHandler = fileHandler;
            this.settings    = settings;

            timer.OnElapsed(async() =>
            {
                using (var stream = await snapshotProvider.GetSnapshot())
                {
                    fileHandler.SaveStream(stream);
                }
            });
        }
예제 #10
0
        public EventStoreBase(ITracer tracer, ITextSerializer serializer, ISystemTime dateTime, ISnapshotProvider snapshoter, IMetadataProvider metadataProvider)
        {
            this.tracer                 = tracer;
            this.serializer             = serializer;
            this.dateTime               = dateTime;
            this.snapshoter             = snapshoter;
            this.metadataProvider       = metadataProvider;
            this.lastUpdateTimeProvider = () => dateTime.Now.ToString("o");


            // TODO: could be replaced with a compiled lambda
            var constructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IEnumerable <IVersionedEvent>) });

            if (constructor == null)
            {
                throw new InvalidCastException("Type T must have a constructor with the following signature: .ctor(Guid, IEnumerable<IVersionedEvent>)");
            }

            this.entityFactory = (id, events) => (T)constructor.Invoke(new object[] { id, events });

            if (typeof(IMementoOriginator).IsAssignableFrom(typeof(T)) && this.snapshoter != null)
            {
                // TODO: could be replaced with a compiled lambda to make it more performant
                var mementoConstructor = typeof(T).GetConstructor(new[] { typeof(Guid), typeof(IMemento), typeof(IEnumerable <IVersionedEvent>) });
                if (mementoConstructor == null)
                {
                    throw new InvalidCastException(
                              "Type T must have a constructor with the following signature: .ctor(Guid, IMemento, IEnumerable<IVersionedEvent>)");
                }
                this.originatorEntityFactory = (id, memento, events) => (T)mementoConstructor.Invoke(new object[] { id, memento, events });

                this.cacheMementoIfApplicable = (T originator) => this.snapshoter.CacheMementoIfApplicable(originator, _sourceType);

                this.getMementoFromCache = id => this.snapshoter.GetMementoFromCache(id, _sourceType);

                this.markCacheAsStale = id => this.snapshoter.MarkCacheAsStale(id, _sourceType);
            }
            else
            {
                // if no cache object or is not a cache originator, then no-op
                this.cacheMementoIfApplicable = o => { };
                this.getMementoFromCache      = id => { return(null); };
                this.markCacheAsStale         = id => { };
            }
        }
예제 #11
0
        public override void BeginCapture(ISnapshotProvider snapshotProvider, TankInstance tank, Rect clippingRectangle, Color shadeColor, string outputFilename)
        {
            DialogManager.Instance.ShowProgressAsync(this.CapturingDialogTitle,
                                                     string.Format(this.CapturingDialogMessage, tank.Name),
                                                     isCancellable: false)
            .ContinueWith(t =>
            {
                t.Result.SetIndeterminate();

                var captureCompleted = false;

                var dispatcherTimer = new DispatcherTimer(DispatcherPriority.Background,
                                                          Application.Current.Dispatcher);
                dispatcherTimer.Interval = TimeSpan.FromSeconds(0.5);
                dispatcherTimer.Tick    +=
                    (o, e) =>
                {
                    dispatcherTimer.Stop();

                    var bitmapSource = snapshotProvider.Snapshot(clippingRectangle, (float)this.SampleFactor, StaticCapturerBase.GetStaticShadeColor(shadeColor));
                    using (var file = File.OpenWrite(outputFilename))
                    {
                        var encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                        encoder.Save(file);
                    }

                    captureCompleted = true;
                };

                dispatcherTimer.Start();


                while (!captureCompleted)
                {
                    Thread.Sleep(100);
                }

                t.Result.SetTitle(this.CaptureCompletedDialogTitle);
                t.Result.SetMessage(string.Format(this.CaptureCompletedDialogMessage, outputFilename));
                Thread.Sleep(1000);
                t.Result.CloseAsync();
            });
        }
예제 #12
0
 public ProviderController(ISnapshotProvider <ExtendedProviderSnapshot> extendedSnapshotProvider,
                           IQueryFilterService <ExtendedProviderSnapshot> queryFilterService,
                           Validator validator,
                           IRepo <Provider> providerRepo,
                           IProviderManagerFactory providerManagerFactory,
                           ICalendarService <Freelance> calendarService,
                           ICalendarService <Employment> employmentCalendarService,
                           ICalendarService <FreelanceCalendarPeriod> availabilityCalendarService,
                           TraktatContext context, ICerberosMum cerberosMum
                           ) : base(context, cerberosMum)
 {
     ProviderManager           = providerManagerFactory.Create(Cerberos, providerRepo);
     _extendedSnapshotProvider = extendedSnapshotProvider;
     _queryFilterService       = queryFilterService;
     _validator                  = validator;
     _providerRepo               = providerRepo;
     FreelanceCalendarService    = calendarService;
     EmploymentCalendarService   = employmentCalendarService;
     AvailabilityCalendarService = availabilityCalendarService;
 }
예제 #13
0
        public bool RemoveProvider(ISnapshotProvider snapshotProvider)
        {
            Argument.IsNotNull(() => snapshotProvider);

#if DEBUG
            Log.Debug($"[{Scope}] Removing provider {snapshotProvider.GetType()} from the SnapshotManager (Tag == \"{Scope ?? "null"}\")");
#endif

            var removed = false;

            lock (_providers)
            {
                removed = _providers.Remove(snapshotProvider);
            }

            if (removed)
            {
                SnapshotProviderRemoved.SafeInvoke(this, new SnapshotProviderEventArgs(snapshotProvider));
                return(true);
            }

            return(false);
        }
예제 #14
0
        /// <summary>
        /// Performs a snapshot text with a given test context/object pair, using a given instantiated snapshot provider.
        /// </summary>
        public static void Snapshot <T>([NotNull] ISnapshotProvider <T> provider, [NotNull] T target, [NotNull] TestContext context, bool recordMode)
        {
            string targetPath = CombinedTestResultPath(TestResultsPath(), context);

            // Verify path exists
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }

            string testFileName = context.TestName + ".png";
            string testFilePath = Path.Combine(targetPath, testFileName);

            // Verify comparison file's existence (if not in record mode)
            if (!recordMode)
            {
                if (!File.Exists(testFilePath))
                {
                    Assert.Fail($"Could not find reference image file {testFilePath} to compare. Please re-run the test with {nameof(recordMode)} set to true to record a test result to compare later.");
                }
            }

            var image = provider.GenerateBitmap(target);

            if (recordMode)
            {
                image.Save(testFilePath, ImageFormat.Png);

                Assert.Fail(
                    $"Saved image to path {testFilePath}. Re-run test mode with {nameof(recordMode)} set to false to start comparing with record test result.");
            }
            else
            {
                // Load recorded image and compare
                using (var expected = (Bitmap)Image.FromFile(testFilePath))
                    using (var expLock = expected.FastLock())
                        using (var actLock = image.FastLock())
                        {
                            bool areEqual = expLock.Width == actLock.Width && expLock.DataArray.SequenceEqual(actLock.DataArray);

                            if (areEqual)
                            {
                                return; // Success!
                            }
                            // Save to test results directory for further inspection
                            string directoryName = CombinedTestResultPath(context.TestDir, context);
                            string baseFileName  = Path.ChangeExtension(testFileName, null);

                            string savePathExpected = Path.Combine(directoryName, Path.ChangeExtension(baseFileName + "-expected", ".png"));
                            string savePathActual   = Path.Combine(directoryName, Path.ChangeExtension(baseFileName + "-actual", ".png"));

                            // Ensure path exists
                            if (!Directory.Exists(directoryName))
                            {
                                Assert.IsNotNull(directoryName, "directoryName != null");
                                Directory.CreateDirectory(directoryName);
                            }

                            image.Save(savePathActual, ImageFormat.Png);
                            expected.Save(savePathExpected, ImageFormat.Png);

                            context.AddResultFile(savePathActual);

                            Assert.Fail($"Resulted image did not match expected image. Inspect results under directory {directoryName} for info about results");
                        }
            }
        }
 public SnapshotProviderEventArgs(ISnapshotProvider snapshotProvider)
 {
     SnapshotProvider = snapshotProvider;
 }
예제 #16
0
        public override void BeginCapture(ISnapshotProvider snapshotProvider, TankInstance tank, Rect clippingRectangle, Color shadeColor, string outputFilename)
        {
            DialogManager.Instance.ShowProgressAsync(this.CaptureDialogTitle,
                                                     string.Format(this.CaptureDialogMessage, tank.Name),
                                                     isCancellable: true)
            .ContinueWith(t =>
            {
                Thread.Sleep(500);

                DialogManager.AssignTask(
                    t.Result,
                    ActionTask.Create("ExportAnimationCapture",
                                      progress =>
                {
                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        var takeSnapshotProgress = progress.AddChildScope("TakeSnapshot", 80);
                        var encodeProgress       = progress.AddChildScope("EncodeGIF", 20);

                        var frameSources = this.CaptureFrames(snapshotProvider, clippingRectangle, shadeColor, takeSnapshotProgress, () => t.Result.IsCanceled);

                        if (t.Result.IsCanceled)
                        {
                            return;
                        }

                        var encoder = new AnimatedGifEncoder();

                        using (var file = File.OpenWrite(outputFilename))
                        {
                            encoder.Start(file);

                            encoder.SetRepeat(0);
                            encoder.SetDelay((int)(this.FrameTime * 1000));
                            for (var i = 0; i < frameSources.Length; ++i)
                            {
                                encodeProgress.ReportProgress((double)i / frameSources.Length);

                                if (t.Result.IsCanceled)
                                {
                                    return;
                                }

                                if (this.IsBackgroundTransparent)
                                {
                                    encoder.SetTransparentColor(shadeColor);
                                }

                                encoder.AddFrame(frameSources[i]);
                            }

                            encoder.Finish();
                        }

                        progress.ReportIsIndetermine();

                        t.Result.SetTitle(this.CaptureCompletedDialogTitle);
                        t.Result.SetMessage(string.Format(this.CaptureCompletedDialogMessage, outputFilename));
                        Thread.Sleep(1000);

                        progress.ReportProgress(1.0);
                    }));
                }));
            });
        }
예제 #17
0
 public void AddProvider(AggregateRootType eventProviderType, ISnapshotProvider snapshotProvider)
 {
     Contract.Requires(eventProviderType != null);
     Contract.Requires(snapshotProvider != null);
     Contract.Ensures(GetProvider(eventProviderType) != null);
 }
예제 #18
0
        public ISnapshot[] CreateVolumeSnapShot(List <FileSystem> volumes, string[] spoPaths, SnapshotSupportedLevel level)
        {
            using (new Alphaleonis.Win32.Security.PrivilegeEnabler(Privilege.Backup, Privilege.Restore)){
                //PrivilegesManager pm = new PrivilegesManager();
                //pm.Grant();
                VssBackupType vssLevel = VssBackupType.Full;
                if (level == SnapshotSupportedLevel.Full)
                {
                    vssLevel = VssBackupType.Full;
                }
                else if (level == SnapshotSupportedLevel.Incremental)
                {
                    vssLevel = VssBackupType.Incremental;
                }
                else if (level == SnapshotSupportedLevel.Differential)
                {
                    vssLevel = VssBackupType.Differential;
                }
                else if (level == SnapshotSupportedLevel.TransactionLog)
                {
                    vssLevel = VssBackupType.Log;
                }
                ArrayList snapshots = new ArrayList();
                Metadata = new SPOMetadata();
                bool snapshotSuccedeed = false;
                try{
                    IVssImplementation vss = VssUtils.LoadImplementation();
                    backup = vss.CreateVssBackupComponents();
                    Logger.Append(Severity.DEBUG, "0/6 Initializing Snapshot (" + ((spoPaths == null)? "NON-component mode" : "component mode") + ", level " + level + ")");
                    backup.InitializeForBackup(null);
                    if (spoPaths == null)            // component-less snapshot set
                    {
                        backup.SetBackupState(false, true, VssBackupType.Full, false);
                    }
                    else
                    {
                        backup.SetBackupState(true, true, vssLevel, (vssLevel == VssBackupType.Full)?false:true);
                    }
                    if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                    {
                        // The only context supported on Windows XP is VssSnapshotContext.Backup
                        backup.SetContext(VssSnapshotContext.AppRollback /*|VssSnapshotContext.All*/);
                    }
                    Logger.Append(Severity.DEBUG, "1/6 Gathering writers metadata and status");
                    using (IVssAsync async = backup.GatherWriterMetadata()){
                        async.Wait();
                        async.Dispose();
                    }
                    // gather writers status before adding backup set components
                    using (IVssAsync async = backup.GatherWriterStatus()){
                        async.Wait();
                        async.Dispose();
                    }
                    Logger.Append(Severity.DEBUG, "2/6 Adding writers and components");
                    // Now we add the components (vss writers, writer paths/params) of this snapshot set
                    if (spoPaths != null)
                    {
                        foreach (IVssExamineWriterMetadata writer in backup.WriterMetadata)
                        {
                            foreach (string spo in spoPaths)
                            {
                                //Logger.Append (Severity.TRIVIA, "Searching writer and/or component matching "+spo);
                                int index = spo.IndexOf(writer.WriterName);
                                if (index < 0 && spo != "*")
                                {
                                    continue;
                                }
                                bool found = false;
                                Logger.Append(Severity.TRIVIA, "Found matching writer " + writer.WriterName + ", instance name=" + writer.InstanceName);
                                // First we check that the writer's status is OK, else we don't add it to avoid failure of complete snapshot if it's not
                                bool writerOk = false;
                                foreach (VssWriterStatusInfo status in backup.WriterStatus)
                                {
                                    if (status.Name == writer.WriterName)
                                    {
                                        Logger.Append(Severity.TRIVIA, "Checking required writer " + status.Name
                                                      + ", status=" + status.State.ToString() + ", error state=" + status.Failure.ToString());
                                        if (status.State == VssWriterState.Stable && status.Failure == VssError.Success)                                // if we get there it means that we are ready to add the wanted component to VSS set
                                        {
                                            writerOk = true;
                                        }
                                        else
                                        {
                                            Logger.Append(Severity.ERROR, "Cannot add writer " + status.Name + " to snapshot set,"
                                                          + " status=" + status.State.ToString() + ". Backup data  managed by this writer may not be consistent");
                                            if (LogEvent != null)
                                            {
                                                LogEvent(this, new LogEventArgs(820, Severity.WARNING, status.Name + ", Status=" + status.State.ToString() + ", Failure=" + status.Failure.ToString()));
                                            }
                                        }
                                    }
                                }
                                if (!writerOk)
                                {
                                    if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                                    {
                                        backup.DisableWriterClasses(new Guid[] { writer.WriterId });
                                    }
                                    continue;
                                }
                                bool addAllComponents = false;
                                if (spo.Length == index + writer.WriterName.Length || spo == "*" || spo == "" + writer.WriterName + @"\*")
                                {
                                    addAllComponents = true;
                                }
                                foreach (IVssWMComponent component in writer.Components)
                                {
                                    found = false;
                                    //Console.WriteLine("createvolsnapshot : current component is :"+component.LogicalPath+@"\"+component.ComponentName);
                                    if ((!addAllComponents) && spo.IndexOf(component.LogicalPath + @"\" + component.ComponentName) < 0)
                                    {
                                        continue;
                                    }
                                    //Logger.Append (Severity.TRIVIA, "Asked to recursively select all '"+writer.WriterName+"' writer's components");
                                    if (OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                                    {
                                        foreach (VssWMDependency dep in  component.Dependencies)
                                        {
                                            Logger.Append(Severity.TRIVIA, "Component " + component.ComponentName + " depends on component " + dep.ComponentName);
                                        }
                                    }
                                    if (component.Selectable)
                                    {
                                        backup.AddComponent(writer.InstanceId, writer.WriterId, component.Type, component.LogicalPath, component.ComponentName);
                                    }
                                    Logger.Append(Severity.INFO, "Added writer '" + writer.WriterName + "' component " + component.ComponentName);
                                    found = true;

                                    // Second we need to find every drive containing files necessary for writer's backup
                                    // and add them to drives list, in case they weren't explicitely selected as part of backuppaths
                                    List <VssWMFileDescription> componentFiles = new List <VssWMFileDescription>();
                                    componentFiles.AddRange(component.Files);
                                    componentFiles.AddRange(component.DatabaseFiles);
                                    componentFiles.AddRange(component.DatabaseLogFiles);
                                    foreach (VssWMFileDescription file in componentFiles)
                                    {
                                        if (string.IsNullOrEmpty(file.Path))
                                        {
                                            continue;
                                        }
                                        //Console.WriteLine ("component file path="+file.Path+", alt backuplocation="+file.AlternateLocation
                                        //		+", backuptypemask="+file.BackupTypeMask.ToString()+", spec="+file.FileSpecification+", recursive="+file.IsRecursive);
                                        // TODO : Reuse GetInvolvedDrives (put it into VolumeManager class)
                                        string drive = file.Path.Substring(0, 3).ToUpper();
                                        if (drive.Contains(":") && drive.Contains("\\"))
                                        {
                                            var searchedVol = from FileSystem vol in volumes
                                                              where vol.MountPoint.Contains(drive)
                                                              select vol;
                                            //if(!volumes.Contains(drive)){
                                            if (searchedVol == null)
                                            {
                                                Logger.Append(Severity.INFO, "Select VSS component " + component.LogicalPath
                                                              + @"\" + component.ComponentName + " requires snapshotting of drive " + drive + ", adding it to the list.");
                                                volumes.Add(searchedVol.First());
                                            }
                                            break;
                                        }
                                    }

                                    //Logger.Append(Severity.TRIVIA, "Added writer/component "+spo);
                                    //break;
                                }
                                //metadata.Metadata.Add(writer.SaveAsXml());
                                Metadata.Metadata.Add(writer.WriterName, writer.SaveAsXml());
                                if (found == false)
                                {
                                    Logger.Append(Severity.WARNING, "Could not find VSS component " + spo + " which was part of backup paths");
                                }
                            }
                        }
                    }
                    Logger.Append(Severity.DEBUG, "3/6 Preparing Snapshot ");
                    //backup.SetBackupState(false,  true, VssBackupType.Full, false);
                    Guid snapID = backup.StartSnapshotSet();
                    //Guid volID = new Guid();
                    foreach (FileSystem volume in volumes)
                    {
                        VSSSnapshot snapshot = new VSSSnapshot();
                        snapshot.Type = this.Name;
                        Logger.Append(Severity.DEBUG, "Preparing Snapshot of " + volume.MountPoint);
                        if (volume.MountPoint != null && backup.IsVolumeSupported(volume.MountPoint))
                        {
                            snapshot.Id = backup.AddToSnapshotSet(volume.MountPoint);

                            snapshot.Path = volume.MountPoint;
                        }
                        else                  // return the fake provider to get at least a degraded backup, better than nothing
                        {
                            Logger.Append(Severity.WARNING, "Volume '" + volume.MountPoint + "' is not snapshottable (or null). Backup will be done without snapshot, risks of data inconsistancy.");
                            ISnapshotProvider fakeSnapProvider = SnapshotProvider.GetProvider("NONE");
                            List <FileSystem> fakeList         = new List <FileSystem>();
                            fakeList.Add(volume);
                            snapshot = (VSSSnapshot)fakeSnapProvider.CreateVolumeSnapShot(fakeList, null, SnapshotSupportedLevel.Full)[0];
                        }
                        if (snapshot.Id == System.Guid.Empty)
                        {
                            Logger.Append(Severity.ERROR, "Unable to add drive " + volume.MountPoint + " to snapshot set (null guid)");
                        }
                        else
                        {
                            Logger.Append(Severity.TRIVIA, "Drive " + volume.MountPoint + " will be snapshotted to " + snapshot.Id);
                        }
                        snapshots.Add(snapshot);
                    }
                    Logger.Append(Severity.DEBUG, "4/6 Calling Prepare...");
                    using (IVssAsync async = backup.PrepareForBackup()){
                        async.Wait();
                        async.Dispose();
                    }
                    Logger.Append(Severity.DEBUG, "5/6 Snapshotting volumes");
                    using (IVssAsync async = backup.DoSnapshotSet()){
                        async.Wait();
                        async.Dispose();
                    }
                    //if(OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003))
                    foreach (IVssExamineWriterMetadata w in backup.WriterMetadata)
                    {
                        foreach (IVssWMComponent comp in w.Components)
                        {
                            try{
                                backup.SetBackupSucceeded(w.InstanceId, w.WriterId, comp.Type, comp.LogicalPath, comp.ComponentName, true);
                                Logger.Append(Severity.TRIVIA, "Component " + comp.ComponentName + " has been notified about backup success.");
                            }
                            catch (Exception) {
                                //Logger.Append (Severity.WARNING, "Could not notify component "+comp.ComponentName+" about backup completion : "+se.Message);
                            }
                        }
                    }
                    //Node.Misc.VSSObjectHandle.StoreObject(backup);
                    try{
                        //on XP backupcomplete consider that we have done with the snapshot and releases it.
                        //if(OperatingSystemInfo.IsAtLeast(OSVersionName.WindowsServer2003)){
                        backup.BackupComplete();

                        Metadata.Metadata.Add("_bcd_", backup.SaveAsXml());
                        //}
                    }catch (Exception bce) {
                        Logger.Append(Severity.WARNING, "Error calling VSS BackupComplete() : " + bce.Message);
                    }

                    using (IVssAsync async = backup.GatherWriterStatus()){
                        async.Wait();
                        async.Dispose();
                    }

                    Logger.Append(Severity.DEBUG, "6/6 Successfully shapshotted volume(s) ");

                    foreach (ISnapshot sn in snapshots)
                    {
                        if (sn.Id == Guid.Empty)
                        {
                            continue;
                        }
                        sn.MountPoint = backup.GetSnapshotProperties(sn.Id).SnapshotDeviceObject;
                        sn.TimeStamp  = Utilities.Utils.GetUtcUnixTime(backup.GetSnapshotProperties(sn.Id).CreationTimestamp.ToUniversalTime());

                        /*
                         * DirectoryInfo snapMountPoint = Directory.CreateDirectory( Path.Combine(Utilities.ConfigManager.GetValue("Backups.TempFolder"), "snapshot_"+sn.Id));
                         * Logger.Append(Severity.DEBUG, "Mounting shapshotted volume '"+sn.Name+"' to '"+snapMountPoint.FullName+"'");
                         * backup.ExposeSnapshot(sn.Id, null, VssVolumeSnapshotAttributes.ExposedLocally, snapMountPoint.FullName);
                         * //sn.Path = snapMountPoint.FullName+Path.DirectorySeparatorChar;
                         * //sn.Path = @"\\?\Volume{"+sn.Id+"}"+Path.DirectorySeparatorChar;*/
                    }
                }
                catch (Exception e) {
                    try{
                        //backup.BackupComplete();
                        backup.AbortBackup();
                    }
                    catch (Exception ae) {
                        Logger.Append(Severity.ERROR, "Error trying to cancel VSS snapshot set : " + ae.Message);
                    }

                    // TODO !! report snapshoty failure to hub task
                    Logger.Append(Severity.ERROR, "Error creating snapshot :'" + e.Message + " ---- " + e.StackTrace + "'. Backup will continue without snapshot. Backup of VSS components will fail. !TODO! report that to hub");
                    backup.Dispose();
                    throw new Exception(e.Message);
                }
                finally{
                    // TODO !!! reactivate dispose
                    //backup.Dispose();

                    //pm.Revoke();
                }

                return((ISnapshot[])snapshots.ToArray(typeof(ISnapshot)));
            }
        }
예제 #19
0
 public void SetSnapshotProvider(ISnapshotProvider provider)
 {
     _snapshotProvider = provider;
 }
 /// <summary>
 /// Creates new instance.
 /// </summary>
 /// <param name="eventStore">The underlaying event store.</param>
 /// <param name="commandStore">The underlaying command store.</param>
 /// <param name="eventFormatter">The formatter for serializing event payloads.</param>
 /// <param name="commandFormatter">The formatter for serializing commands.</param>
 /// <param name="factory">The process root factory.</param>
 /// <param name="eventDispatcher">The dispatcher for newly created events in the processes.</param>
 /// <param name="commandDispatcher">The dispatcher for newly created commands in the processes.</param>
 /// <param name="snapshotProvider">The snapshot provider.</param>
 /// <param name="snapshotStore">The store for snapshots.</param>
 public ProcessRootRepository(IEventStore eventStore, ICommandStore commandStore, IFormatter eventFormatter, ISerializer commandFormatter,
                              IAggregateRootFactory <T> factory, IEventDispatcher eventDispatcher, ICommandDispatcher commandDispatcher, ISnapshotProvider snapshotProvider, ISnapshotStore snapshotStore)
     : base(eventStore, eventFormatter, factory, eventDispatcher, snapshotProvider, snapshotStore)
 {
     Ensure.NotNull(commandStore, "commandStore");
     Ensure.NotNull(commandDispatcher, "commandDispatcher");
     Ensure.NotNull(commandFormatter, "commandFormatter");
     this.commandStore      = commandStore;
     this.commandFormatter  = commandFormatter;
     this.commandDispatcher = commandDispatcher;
 }
        public EventStore(IEventBus eventBus, ICommandBus commandBus, ITextSerializer serializer, Func <EventStoreDbContext> contextFactory, ITracer tracer, ISystemTime dateTime, ISnapshotProvider snapshoter, IMetadataProvider metadataProvider)
            : base(tracer, serializer, dateTime, snapshoter, metadataProvider)
        {
            this.eventBus   = eventBus;
            this.commandBus = commandBus;

            this.contextFactory      = contextFactory;
            this.queryContextFactory = () =>
            {
                var context = this.contextFactory.Invoke();
                context.Configuration.AutoDetectChangesEnabled = false;
                return(context);
            };

            if (!typeof(ISqlBus).IsAssignableFrom(this.eventBus.GetType()))
            {
                throw new InvalidCastException("El eventBus debe implementar ISqlBus para ser transaccional con el EventStore");
            }

            if (!typeof(ISqlBus).IsAssignableFrom(this.commandBus.GetType()))
            {
                throw new InvalidCastException("El commandBus debe implementar ISqlBus para ser transaccional con el EventStore");
            }
        }
예제 #22
0
        public void AddProvider(AggregateRootType eventProviderType, ISnapshotProvider snapshotProvider)
        {
            _providers.Add(eventProviderType, snapshotProvider);

            Contract.Assume(GetProvider(eventProviderType) == snapshotProvider);
        }
예제 #23
0
 public abstract void BeginCapture(ISnapshotProvider snapshotProvider, TankInstance tank, Rect clippingRectangle, Color shadeColor, string outputFilename);
 public TinyLibraryCQRSDomainRepository(IDomainEventStorage domainEventStorage, IEventBus eventBus, ISnapshotProvider snapshotProvider)
     : base(domainEventStorage, eventBus, snapshotProvider)
 {
 }
예제 #25
0
 public InMemoryEventStore(IInMemoryBus bus, ITextSerializer serializer, EventStoreDbContext context, ITracer tracer, ISystemTime dateTime, ISnapshotProvider snapshoter, IMetadataProvider metadataProvider)
     : base(tracer, serializer, dateTime, snapshoter, metadataProvider)
 {
     this.bus     = bus;
     this.context = context;
 }
예제 #26
0
 protected abstract BitmapSource[] CaptureFrames(ISnapshotProvider snapshotProvider, Rect clippingRectangle, Color shadeColor, IProgressScope progress, Func <bool> getIsCancelled);
예제 #27
0
 public EventSourcingDomainRepository(IEventStore eventStore,
                                      IEventPublisher publisher,
                                      ISnapshotProvider snapshotProvider)
     : this(eventStore, publisher, snapshotProvider, null)
 {
 }
예제 #28
0
 /// <summary>
 /// 初始化一个 <c>EventSourcedDomainRepository</c> 类实例。
 /// </summary>
 /// <param name="domainEventStorage">一个 <see cref="Anycmd.Events.Storage.IDomainEventStorage{T}"/>
 /// 类型的实例,该实例是一种储存领域事件的装置。</param>
 /// <param name="eventBus">一个 <see cref="Anycmd.Bus.IEventBus"/> 类型的事件总线对象,领域事件发向该总线。</param>
 /// <param name="snapshotProvider"><see cref="Anycmd.Snapshots.Providers.ISnapshotProvider{T}"/>
 /// 处理快照操作的快照提供程序。</param>
 public EventSourcedDomainRepository(IDomainEventStorage <TAggregateRootId> domainEventStorage, IEventBus eventBus, ISnapshotProvider <TAggregateRootId> snapshotProvider)
     : base(eventBus)
 {
     this._domainEventStorage = domainEventStorage;
     this._snapshotProvider   = snapshotProvider;
 }
 /// <summary>
 /// Initializes a new instance of <c>EventSourcedDomainRepository</c> class.
 /// </summary>
 /// <param name="domainEventStorage">The <see cref="Apworks.Events.Storage.IDomainEventStorage"/> instance
 /// that handles the storage mechanism for domain events.</param>
 /// <param name="eventBus">The <see cref="Apworks.Bus.IEventBus"/> instance to which the domain events
 /// are published.</param>
 /// <param name="snapshotProvider">The <see cref="Apworks.Snapshots.Providers.ISnapshotProvider"/> instance
 /// that is used for handling the snapshot operations.</param>
 public EventSourcedDomainRepository(IDomainEventStorage domainEventStorage, IEventBus eventBus, ISnapshotProvider snapshotProvider)
     : base(eventBus)
 {
     this.domainEventStorage = domainEventStorage;
     this.snapshotProvider   = snapshotProvider;
 }
예제 #30
0
        /// <summary>
        /// This method first looks if backup needs snapshotting drives. If so, then we do snapshot
        /// and use it to call BuildBackup method
        /// </summary>
        private void PrepareDrivesAndSnapshots()
        {
            SnapshotSupportedLevel snapLevel = ConvertBackupLevelToSnLevel(this.Level);

            Logger.Append(Severity.INFO, "Preparing backup for Task " + this.Id);
            HubNotificationEvent(this.Id, 701 /*snapshotting*/, "", "");

            backupRootDrives = GetBackupInvolvedRootDrives();



            Console.WriteLine("PrepareDrivesAndSnapshots()() backupRootDrives count=" + backupRootDrives.Count);
            string[] snapshotProvNames = new string[backupRootDrives.Count];
            for (int i = 0; i < backupRootDrives.Count; i++)
            {
                if (backupRootDrives[i].RequiresSnapshot)
                {
                    snapshotProvNames[i] = SnapshotProvider.GetDriveSnapshotProviderName(backupRootDrives[i].SystemDrive.MountPoint);
                }
                else
                {
                    snapshotProvNames[i] = "NONE";
                }
            }

            // the final list of all snapshot needed to perform the backup set
            backupSnapshots = new List <ISnapshot>();

            // We try to make all snapshot in the shortest amount of time we can,
            // for data to be as consistent as possible
            foreach (string snapProv in snapshotProvNames.Distinct())
            {
                Console.WriteLine("PrepareDrivesAndSnapshots() snapshotProvNames=" + snapProv);
                List <FileSystem> snapShotMemberDrives = new List <FileSystem>();
                for (int i = 0; i < backupRootDrives.Count; i++)
                {
                    if (snapshotProvNames[i] == snapProv)
                    {
                        snapShotMemberDrives.Add(backupRootDrives[i].SystemDrive);
                    }
                }
                //Gather SpecialObjects (VSS writers) if any
                var spoList = from BasePath bp in this.BackupSet.BasePaths
                              where bp.Type != null && bp.Type.ToLower().StartsWith("object:")                  //P2PBackup.Common.BasePath.PathType.OBJECT
                              select bp.Path;

                ISnapshotProvider snapProvider = SnapshotProvider.GetProvider(snapProv);
                snapshotProviders.Add(snapProvider);
                snapProvider.LogEvent += LogReceivedEvent;
                ISnapshot[] volSnaps;
                try{
                    volSnaps = snapProvider.CreateVolumeSnapShot(snapShotMemberDrives, spoList.ToArray(), snapLevel);
                    //if(snapProvider.Metadata != null)
                    //	Index.Header.ProviderMetadata.Add(new Tuple<string, Hashtable>(snapProvider.Name, snapProvider.Metadata.Metadata));
                    string volList = "";
                    foreach (FileSystem vol in snapShotMemberDrives)
                    {
                        volList += vol.MountPoint + ",";
                    }
                    Logger.Append(Severity.INFO, "Took snapshots (type " + snapProvider.Type + ") of drives " + volList);
                }
                catch (Exception e) {
                    // we return a fake snapshot (snapshot path is the volume itself)
                    string volList = "";
                    foreach (FileSystem vol in snapShotMemberDrives)
                    {
                        volList += vol.MountPoint + ",";
                    }
                    Logger.Append(Severity.WARNING, "Unable to take snapshot of drives " + volList + ", falling back to fake provider. Error was : " + e.Message + " --- " + e.StackTrace);
                    HubNotificationEvent(this.Id, 805 /*cant snapshot*/, volList, e.Message);
                    ISnapshotProvider nullProv = SnapshotProvider.GetProvider("NONE");
                    volSnaps = nullProv.CreateVolumeSnapShot(snapShotMemberDrives, spoList.ToArray(), snapLevel);
                }
                backupSnapshots.AddRange(volSnaps);
                snapProvider.LogEvent -= LogReceivedEvent;
            }

            //finally, add snapshot to corresponding BackupRootDrive
            Console.WriteLine("##### dumping rootdrives : ");
            foreach (BackupRootDrive rd in backupRootDrives)
            {
                foreach (ISnapshot snap in backupSnapshots)
                {
                    if (/*snap.MountPoint*/ snap.Path == rd.SystemDrive.MountPoint)
                    {
                        rd.Snapshot = snap;
                        Console.WriteLine("matched snapshot : " + snap.Path + ", snap mount path=" + snap.MountPoint);
                        // let's change paths and excluded paths to their snapshotted values
                        foreach (BasePath bp in rd.Paths)
                        {
                            //bp.Path = snap.Path + bp.Path;

                            /*if(snap.Name == "/")
                             *      bp.Path = snap.Path;
                             * else
                             *      bp.Path = bp.Path.Replace(snap.Name, snap.Path);*/
                            for (int i = 0; i < bp.ExcludedPaths.Count; i++)
                            {
                                //bp.ExcludedPaths[i] = snap.Path +  bp.ExcludedPaths[i];
                                if (snap.Path == "/")
                                {
                                    bp.ExcludedPaths[i] = snap.MountPoint + bp.ExcludedPaths[i];
                                }
                                else
                                {
                                    bp.ExcludedPaths[i] = bp.ExcludedPaths[i].Replace(snap.Path, snap.MountPoint);
                                    //bp.ExcludedPaths[i] = bp.ExcludedPaths[i].Replace(snap.Name, "");
                                    //bp.ExcludedPaths[i] = Path.Combine(snap.Path, bp.ExcludedPaths[i]);
                                    //bp.ExcludedPaths[i] = Path.GetFullPath(bp.ExcludedPaths[i]);
                                }
                            }
                        }
                        break;
                    }
                }

                Console.WriteLine("BackupRootDrive id=" + rd.ID + ", mount=" + rd.SystemDrive.MountPoint /*+", snapshot= "+rd.snapshot.Path*/);
                foreach (BasePath p in rd.Paths)
                {
                    Console.WriteLine("\t p=" + p.Path + ", excludes : ");
                    foreach (string s in p.ExcludedPaths)
                    {
                        Console.WriteLine("\t excluded " + s);
                    }
                    Console.WriteLine("\t\t, include patterns : ");
                    foreach (string s in p.IncludePolicy)
                    {
                        Console.WriteLine("\t match " + s);
                    }
                }
            }
            Console.WriteLine("#####   #####");
            foreach (BackupRootDrive rds in backupRootDrives)
            {
                Logger.Append(Severity.DEBUG, "Drive '" + rds.SystemDrive.OriginalMountPoint + "' was snapshotted to '" + rds.Snapshot.MountPoint + "' using provider '" + rds.Snapshot.Type + "' with timestamp " + rds.Snapshot.TimeStamp + " (" + Utils.GetLocalDateTimeFromUnixTime(rds.Snapshot.TimeStamp) + ")");
            }
        }