Example #1
0
        /// <summary>
        /// Waits for a signal from another thread, aborting if the operation is cancelled
        /// </summary>
        /// <param name="token"></param>
        /// <returns>True, if the operation succeeds. False if the operation is cancelled</returns>
        public bool Wait(CancellationToken token)
        {
            //Create a new lock to wait for
            SyncLock blocker;

            //Then acquires the lock and wraps it up in preperation to offering it to the queue
            DisposableWrapper wrapper;

            //Next acquires the lock for this instance, and enqueues our wrapped lock
            using (_sync.GetLock())
            {
                if (pulses > 0)
                {
                    pulses--;
                    return(true);
                }
                blocker = new SyncLock();
                queue.Enqueue(wrapper = new DisposableWrapper(blocker.GetLock()));
            }

            //Finally, waits for the lock, and if we time out, we release it ourselves.
            //If on the rare chance the lock is released between the time we stop waiting and the time we try to release it, say we were signalled successfully
            if (!blocker.TryGetLock(token, out IDisposable @lock))
            {
                return(!wrapper.Dispose()); //Just in case a last minute call lets us return true;
            }
            //If we did get a lock however, release that
            @lock.Dispose();

            //Before finally signaling that we were successfuly
            return(true);
        }
        public void Dispose_ShouldCallGarbageCollectorSuppressFinalize()
        {
            using(ShimsContext.Create())
            {
                object suppressFinalizeInstance = null;
                bool suppressFinalizeIsCalled = false;

                ShimGC.SuppressFinalizeObject = delegate(object instance)
                {
                    suppressFinalizeInstance = instance;
                    suppressFinalizeIsCalled = true;
                };

                Assert.IsNull(suppressFinalizeInstance);
                Assert.IsFalse(suppressFinalizeIsCalled);

                var disposableWrapper = new DisposableWrapper<IDisposable>(Mock.Of<IDisposable>());

                disposableWrapper.Dispose();

                Assert.IsNotNull(suppressFinalizeInstance);
                Assert.IsTrue(ReferenceEquals(disposableWrapper, suppressFinalizeInstance));
                Assert.IsTrue(suppressFinalizeIsCalled);
            }
        }
Example #3
0
        /// <summary>
        /// Activates sources of the time source and provides an object that deactivates them on dispose.
        /// </summary>
        protected IDisposable ObtainSourceActiveState()
        {
            using (sync.HighPriority)
            {
                foreach (var slave in handles.All)
                {
                    slave.SourceSideActive = true;
                    slave.RequestStart();
                }
            }

            var result = new DisposableWrapper();

            result.RegisterDisposeAction(() =>
            {
                using (sync.HighPriority)
                {
                    foreach (var slave in handles.All)
                    {
                        slave.SourceSideActive = false;
                    }
                }
            });
            return(result);
        }
Example #4
0
        /// <summary>
        /// Asynchronously waits for a signal from another thread, aborting if the operation is cancelled
        /// </summary>
        /// <param name="token"></param>
        /// <returns>True, if the operation succeeds. False if the operation is cancelled</returns>
        public async Task <bool> WaitAsync(CancellationToken token)
        {
            //The SyncLock to use
            SyncLock blocker;

            //The lock wrapper
            DisposableWrapper wrapper;

            //Next acquires the lock for this instance, and enqueues our wrapped lock
            using (await _sync.GetLockAsync().ConfigureAwait(false))
            {
                //If we have leftover pulses, consume one instead of waiting.
                if (pulses > 0)
                {
                    pulses--;
                    return(true);
                }

                //Otherwise create the SyncLock
                blocker = new SyncLock();

                //And wrap up a lock from it for eventual release
                queue.Enqueue(wrapper = new DisposableWrapper(await blocker.GetLockAsync()));
            }

            //Finally, waits for the lock, and if we time out, we release it ourselves.
            //If on the rare chance the lock is released between the time we stop waiting and the time we try to release it, say we were signalled successfully
            if (!await blocker.TryGetLockAsync(token, l => l.Dispose()))
            {
                return(!wrapper.Dispose());
            }

            //say we were signalled successfully.
            return(true);
        }
Example #5
0
        public DebugDialog()
        {
            InitializeComponent();
            Properties.SelectedObject = new DebugInfo();

            // Check wrapper tracing
            _wrapperTracer = DisposableWrapper.GetTracer();
            if (_wrapperTracer == null)
            {
                // If we don't have a wrapper tracer, hide the tabs
                _tabs.SizeMode = TabSizeMode.Fixed;
                _tabs.ItemSize = new Size(0, 1);
            }
            else
            {
                listWrappers.ListViewItemSorter         = new WrapperCountSorter(0);
                listWrapperTypes.ListViewItemSorter     = new WrapperCountSorter(1);
                listWrapperLocations.ListViewItemSorter = new WrapperCountSorter(1);
                listItemEvents.ListViewItemSorter       = new WrapperCountSorter(0);
                RefreshWrappers();
                RefreshItemEvents();

                // Make it a bit bigger
                Width  = Width + 400;
                Height = Height + 200;
            }

            _taskTracer = Tasks.Tracer;
        }
Example #6
0
        public TimeSpan Run()
        {
            Debug.Assert(MethodToBenchmark != null);

            // Note: here we're not just measuring method body but also its invocation chain,
            // including delegate invocation performed here. For very small bodies this time may be significative,
            // to workaround this we should create an invokable type with Reflection.Emit and just pay the price
            // of a callvirt (method will be called through a known interface like IInvokable.Invoke).
            // HOWEVER note that if calling overhead is comparable to code to benchmark (less than few hundred nanoseconds) then
            // this framework is not the right one to perform the benchmark because many other ignored factors
            // will play an important role.
            var stopwatch = new Stopwatch();

            using (var obj = new DisposableWrapper(MethodToBenchmark.DeclaringType))
            {
                InvokeAll(obj.Instance, SetUpMethods);

                var methodToInvoke = (Action)Delegate.CreateDelegate(typeof(Action), obj.Instance, MethodToBenchmark);

                if (_warmUp)
                {
                    methodToInvoke();
                }

                stopwatch.Start();
                methodToInvoke();
                stopwatch.Stop();

                InvokeAll(obj.Instance, CleanUpMethods);
            }

            return(stopwatch.Elapsed);
        }
        public static IDisposable ObtainSinkInactiveState(this ITimeSink @this)
        {
            var result = new DisposableWrapper();

            @this.TimeHandle.SinkSideActive = false;
            result.RegisterDisposeAction(() => @this.TimeHandle.SinkSideActive = true);
            return(result);
        }
        public void Constructor_WithOneParameter_IfTheDisposableParameterIsNotNull_ShouldSetTheWrappedInstance()
        {
            var disposable = Mock.Of<IDisposable>();

            using(var disposableWrapper = new DisposableWrapper<IDisposable>(disposable))
            {
                Assert.IsTrue(ReferenceEquals(disposable, disposableWrapper.WrappedInstance));
            }
        }
Example #9
0
        public static IDisposable TraceRegion(this object o, string message     = null,
                                              [CallerLineNumber] int lineNumber = 0,
                                              [CallerMemberName] string caller  = null,
                                              [CallerFilePath] string fileName  = null)
        {
            var result = new DisposableWrapper();

            Trace(o, $"Entering: {message}", lineNumber, caller, fileName);
            result.RegisterDisposeAction(() => Trace(o, $"Leaving: {message}. Entered", lineNumber, caller, fileName));
            return(result);
        }
Example #10
0
        // Helper for acedInvoke()

        public static ResultBuffer InvokeLisp(ResultBuffer args, ref int stat)
        {
            IntPtr rb = IntPtr.Zero;

            stat = acedInvoke(args.UnmanagedObject, out rb);
            if (stat == (int)PromptStatus.OK && rb != IntPtr.Zero)
            {
                return((ResultBuffer)
                       DisposableWrapper.Create(typeof(ResultBuffer), rb, true));
            }
            return(null);
        }
Example #11
0
        private bool RunWbkOperation <TResult>(ExcelApplicationEx excelApp,
                                               string wbkFullPath,
                                               bool closeWbkAfterAction,
                                               TResult trueValue,
                                               Func <MSExcel.Workbook, RunWbkActionResult <TResult> > action,
                                               out string message)
            where TResult : IComparable
        {
            message = null;
            try
            {
                using (var wrapper = new DisposableWrapper <MSExcel.Application>(excelApp.App,
                                                                                 app =>
                {
                    if (app != null)
                    {
                        app.DisplayAlerts = true;
                    }
                }))
                {
                    if (excelApp != null)
                    {
                        excelApp.App.DisplayAlerts = false; // Отключаем различные сообщения

                        var wbk = OpenWbk(excelApp, wbkFullPath);
                        if (wbk != null)
                        {
                            var res = action(wbk);
                            if (res.Result.CompareTo(trueValue) != 0)
                            {
                                message = res.ErrorMessage;
                                return(false);
                            }

                            wbk.Save();
                            if (closeWbkAfterAction)
                            {
                                wbk.Close(); // Закрываем книгу, в следующий раз она молчаливо себя почистит
                            }
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                message = $"exception in RunWbkOperation: {ex.Message}";
            }

            return(false);
        }
Example #12
0
        public async Task Connect_to_correct_host_with_available_idle(
            string targetSessionAttributes, MockState[] servers, int expectedServer)
        {
            var postmasters = servers.Select(s => PgPostmasterMock.Start(state: s)).ToArray();

            await using var __ = new DisposableWrapper(postmasters);

            // First, open and close a connection with the TargetSessionAttributes matching the first server.
            // This ensures wew have an idle connection in the pool.
            var connectionStringBuilder = new NpgsqlConnectionStringBuilder
            {
                Host = MultipleHosts(postmasters),
                TargetSessionAttributes = servers[0] switch
                {
                    Primary => "read-write",
                    PrimaryReadOnly => "read-only",
                    Standby => "standby",
                    _ => throw new ArgumentOutOfRangeException()
                },
Example #13
0
        public async Task Connect_to_correct_host(string targetSessionAttributes, MockState[] servers, int expectedServer)
        {
            var postmasters = servers.Select(s => PgPostmasterMock.Start(state: s)).ToArray();

            await using var __ = new DisposableWrapper(postmasters);

            var connectionStringBuilder = new NpgsqlConnectionStringBuilder
            {
                Host = MultipleHosts(postmasters),
                TargetSessionAttributes = targetSessionAttributes,
                ServerCompatibilityMode = ServerCompatibilityMode.NoTypeLoading,
            };

            using var pool       = CreateTempPool(connectionStringBuilder, out var connectionString);
            await using var conn = await OpenConnectionAsync(connectionString);

            Assert.That(conn.Port, Is.EqualTo(postmasters[expectedServer].Port));

            for (var i = 0; i <= expectedServer; i++)
            {
                _ = await postmasters[i].WaitForServerConnection();
            }
        }
Example #14
0
        //Retruns ObjectIds of entities at a specific position

        //Including nested entities in block references

        static public ObjectId[] FindAtPointNested(
            Document doc,
            Point3d worldPoint,
            bool selectAll,
            IntPtr filter)
        {
            System.Collections.Generic.List <ObjectId> ids = new System.Collections.Generic.List <ObjectId>();

            Matrix3d wcs2ucs = doc.Editor.CurrentUserCoordinateSystem.Inverse();

            Point3d ucsPoint = worldPoint.TransformBy(wcs2ucs);

            string arg = selectAll ? "_:E:N" : "_:N";

            IntPtr ptrPoint = Marshal.UnsafeAddrOfPinnedArrayElement(worldPoint.ToArray(), 0);

            ArxImports.ads_name sset;

            PromptStatus prGetResult = ArxImports.acedSSGet(arg, ptrPoint, IntPtr.Zero, filter, out sset);
            int          len;

            ArxImports.acedSSLength(ref sset, out len);
            //Need to rely on unsafe code in order to use pointers *

            unsafe
            {
                for (int i = 0; i < len; ++i)
                {
                    ArxImports.resbuf  rb  = new ArxImports.resbuf();
                    ArxImports.resbuf *pRb = &rb;

                    if (ArxImports.acedSSNameX(&pRb, ref sset, i) !=

                        PromptStatus.OK)
                    {
                        continue;
                    }



                    //Create managed ResultBuffer from our resbuf struct

                    using (ResultBuffer rbMng = DisposableWrapper.Create(

                               typeof(ResultBuffer),

                               (IntPtr)pRb,

                               true) as ResultBuffer)
                    {
                        foreach (TypedValue tpVal in rbMng)
                        {
                            //Not interested if it isn't an ObjectId

                            if (tpVal.TypeCode != 5006) //RTENAME

                            {
                                continue;
                            }



                            ObjectId id = (ObjectId)tpVal.Value;



                            if (id != null)
                            {
                                ids.Add(id);
                            }
                        }
                    }
                }
            }



            ArxImports.acedSSFree(ref sset);



            return(ids.ToArray());
        }
        public bool Extract(ICompDesc compDesc, IEnumerable <IGroupItem> compGroups, out string message)
        {
            CompDescLocalWorkbook compDescLocal = compDesc as CompDescLocalWorkbook;

            message = null;

            GroupsMembers = new List <KeyValuePair <IGroupItem, IEnumerable <CFullMemberInfo> > >();

            try
            {
                using (var excelApp = new DisposableWrapper <ExcelApplicationEx>(GlobalDefines.StartExcel(),
                                                                                 app =>
                {
                    if (app != null)
                    {
                        app.App.DisplayAlerts = true;

                        if (app.NewAppCreated)
                        {
                            app.App.Quit();
                        }

                        app = null;
                    }
                }))
                {
                    bool WbkOpened;
                    var  wbk = WorkbookGenerator.OpenWbk(excelApp, compDescLocal.SourceWorkbookName, out WbkOpened);

                    if (wbk == null)
                    {
                        message = string.Format(Properties.Resources.resfmtSourceWorkbookCouldNotBeOpened,
                                                compDescLocal.SourceWorkbookName);
                        return(false);
                    }

                    foreach (var @group in compGroups.Cast <GroupItemLocalWorkbook>())
                    {
                        MSExcel.Worksheet wsh = wbk.Worksheets[@group.SheetName];
                        MSExcel.Range     rng = wsh.Range[$"{@group.TLCell}:{@group.BRCell}"];

                        List <CFullMemberInfo> members = new List <CFullMemberInfo>();
                        for (int row = 0; row < rng.Rows.Count; row++)
                        {
                            string[] NameAndSurname;
                            GlobalDefines.CorrectSurnameAndName(rng[row + 1, @group.PersonalDataColumnIndex].Value, out NameAndSurname);

                            enGrade grade;
                            GlobalDefines.ParseGrade(rng[row + 1, @group.GradeColumnIndex].Value?.ToString(), out grade);

                            short?yearOfBirth = rng[row + 1, @group.YoBColumnIndex].Value == null
                                                    ? null
                                                    : (short?)Convert.ToUInt16(rng[row + 1, @group.YoBColumnIndex].Value);

                            members.Add(new CFullMemberInfo()
                            {
                                Surname     = NameAndSurname[0],
                                Name        = NameAndSurname[1],
                                YearOfBirth = yearOfBirth,
                                SecondCol   = rng[row + 1, @group.TeamColumnIndex].Value,
                                InitGrade   = grade == enGrade.None ? null : (byte?)grade
                            });
                        }

                        GroupsMembers.Add(new KeyValuePair <IGroupItem, IEnumerable <CFullMemberInfo> >(@group, members));
                    }
                }

                CompDesc = compDesc;
                return(true);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(false);
            }
        }
Example #16
0
 // COM_OpenFile(char* filename, int* hndl)
 // filename never has a leading slash, but may ConsoleWrappertain directory walks
 // returns a handle and a length
 // it may actually be inside a pak file
 private static int OpenFile(string filename, out DisposableWrapper <BinaryReader> file)
 {
     return(FileSystem.FindFile(filename, out file, false));
 }
Example #17
0
    static int COM_FindFile(string filename, out DisposableWrapper <BinaryReader> file, bool duplicateStream)
    {
        file = null;

        string cachepath = String.Empty;

        //
        // search through the path, one element at a time
        //
        foreach (searchpath_t sp in com_searchpaths)
        {
            // is the element a pak file?
            if (sp.pack != null)
            {
                // look through all the pak file elements
                pack_t pak = sp.pack;
                foreach (packfile_t pfile in pak.files)
                {
                    if (pfile.name.Equals(filename))
                    {
                        // found it!
                        Con_DPrintf("PackFile: {0} : {1}\n", sp.pack.filename, filename);
                        if (duplicateStream)
                        {
                            FileStream pfs = (FileStream)pak.stream.BaseStream;
                            FileStream fs  = new FileStream(pfs.Name, FileMode.Open, FileAccess.Read, FileShare.Read);
                            file = new DisposableWrapper <BinaryReader>(new BinaryReader(fs, Encoding.ASCII), true);
                        }
                        else
                        {
                            file = new DisposableWrapper <BinaryReader>(pak.stream, false);
                        }

                        file.Object.BaseStream.Seek(pfile.filepos, SeekOrigin.Begin);
                        return(pfile.filelen);
                    }
                }
            }
            else
            {
                // check a file in the directory tree
                if (!static_registered)
                {
                    // if not a registered version, don't ever go beyond base
                    if (filename.IndexOfAny(_Slashes) != -1) // strchr (filename, '/') || strchr (filename,'\\'))
                    {
                        continue;
                    }
                }

                string   netpath  = sp.filename + "/" + filename; //sprintf (netpath, "%s/%s",search->filename, filename);
                DateTime findtime = Sys_FileTime(netpath);
                if (findtime == DateTime.MinValue)
                {
                    continue;
                }

                // see if the file needs to be updated in the cache
                if (String.IsNullOrEmpty(com_cachedir)) // !com_cachedir[0])
                {
                    cachepath = netpath;                //  strcpy(cachepath, netpath);
                }
                else
                {
                    if (IsWindows)
                    {
                        if (netpath.Length < 2 || netpath[1] != ':')
                        {
                            cachepath = com_cachedir + netpath;
                        }
                        else
                        {
                            cachepath = com_cachedir + netpath.Substring(2);
                        }
                    }
                    else
                    {
                        cachepath = com_cachedir + netpath;
                    }

                    DateTime cachetime = Sys_FileTime(cachepath);
                    if (cachetime < findtime)
                    {
                        COM_CopyFile(netpath, cachepath);
                    }
                    netpath = cachepath;
                }

                Con_DPrintf("FindFile: {0}\n", netpath);
                FileStream fs = Sys_FileOpenRead(netpath);
                if (fs == null)
                {
                    file = null;
                    return(-1);
                }
                file = new DisposableWrapper <BinaryReader>(new BinaryReader(fs, Encoding.ASCII), true);
                return((int)fs.Length);
            }
        }

        Con_DPrintf("FindFile: can't find {0}\n", filename);
        return(-1);
    }
Example #18
0
 // COM_OpenFile(char* filename, int* hndl)
 // filename never has a leading slash, but may ConsoleWrappertain directory walks
 // returns a handle and a length
 // it may actually be inside a pak file
 private static Int32 OpenFile(String filename, out DisposableWrapper <BinaryReader> file)
 {
     return(FindFile(filename, out file, false));
 }
Example #19
0
        public bool InitWndControls()
        {
            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                               Properties.Resources.resFillingGenerationFromOnlineBDWnd,
                                                                                               this,
                                                                                               CheckAccess()),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                EndYears.Clear();
                StartYears.Clear();
                EndYears.Add((int)enEndYearSpecVals.AndYounger);
                EndYears.Add((int)enEndYearSpecVals.AndElder);
                for (int i = DateTime.Now.Year - 7; i > DateTime.Now.Year - 100; i--)
                {
                    StartYears.Add(i);
                    EndYears.Add(i);
                }


                GroupNames.Clear();
                lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                {
                    foreach (var groupNameDesc in DBManagerApp.m_AppSettings.m_Settings.AvailableGroupNames)
                    {
                        GroupNames.Add(groupNameDesc.GroupName);
                    }
                }

                // Заполняем выпадающие списки текущими значениями
                LocalDBComps.Clear();

                try
                {
                    foreach (var comp in DBManagerApp.m_Entities.descriptions.ToList())
                    {
                        var item = new CompDescLocalWorkbook()
                        {
                            ID        = comp.id_desc,
                            Name      = comp.name,
                            StartDate = DateTime.Today,
                            EndDate   = DateTime.Today.AddDays(2)
                        };
                        item.DestCompFolder   = GetDefaultDestCompFolderName(item);
                        item.PropertyChanged += comp_PropertyChanged;

                        LocalDBComps.Add(item);
                    }
                    SelectedComp = LocalDBComps.LastOrDefault();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this,
                                    string.Format(Properties.Resources.resfmtErrorDuringReadingDataFromOnlineDB, ex.Message),
                                    Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return(false);
                }

                cmbMainJudge.Items.Clear();
                foreach (var mainJudge in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_judge)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainJudge.Items.Add(mainJudge);
                }

                cmbMainSecretary.Items.Clear();
                foreach (var mainSecretary in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_secretary)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainSecretary.Items.Add(mainSecretary);
                }

                cmbRow6.Items.Clear();
                foreach (var row6 in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.row6)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbRow6.Items.Add(row6);
                }
            }

            return(true);
        }
Example #20
0
        public void MyCommand()
        {
            if (!this.ShowDialog())
            {
                return;
            }
            double            num1              = 1.0;
            double            num2              = 0.25;
            double            num3              = this.m * (double)this.z;
            double            da                = (2.0 * num1 + (double)this.z) * this.m;
            double            df                = ((double)this.z - 2.0 * num1 - 2.0 * num2) * this.m;
            double            db                = num3 * Math.Cos(this.a * Math.PI / 180.0);
            Point3d           point             = this.GetPoint();
            DateTime          now1              = DateTime.Now;
            Circle            circle1           = new Circle(point, Vector3d.get_ZAxis(), db / 2.0);
            Circle            cir1              = new Circle(point, Vector3d.get_ZAxis(), da / 2.0);
            Circle            circle2           = new Circle(point, Vector3d.get_ZAxis(), df / 2.0);
            Circle            pitchCircle       = new Circle(point, Vector3d.get_ZAxis(), num3 / 2.0);
            Point3dCollection point3dCollection = new Point3dCollection();
            Polyline3d        evolent1          = this.CreatEvolent(point, da, db, cir1);
            Polyline3d        evolent2          = this.MirrorEvolent(evolent1, pitchCircle, point);
            Arc  arc   = this.CreatArc(point, evolent1, evolent2);
            Line line1 = new Line(point, ((Curve)evolent1).get_StartPoint());
            Line line2 = new Line(point, ((Curve)evolent2).get_StartPoint());
            DBObjectCollection objectCollection1 = new DBObjectCollection();

            objectCollection1.Add((DBObject)evolent1);
            objectCollection1.Add((DBObject)evolent2);
            objectCollection1.Add((DBObject)line2);
            objectCollection1.Add((DBObject)line1);
            objectCollection1.Add((DBObject)arc);
            DBObjectCollection objectCollection2 = new DBObjectCollection();

            Entity[] entityArray = this.ArrayPolar((Entity)(Region.CreateFromCurves(objectCollection1).get_Item(0) as Region), point, this.z, 2.0 * Math.PI);
            objectCollection1.Clear();
            objectCollection1.Add((DBObject)circle2);
            Region region1 = Region.CreateFromCurves(objectCollection1).get_Item(0) as Region;

            foreach (Entity entity in entityArray)
            {
                Region region2 = entity as Region;
                if (DisposableWrapper.op_Inequality((DisposableWrapper)region2, (DisposableWrapper)null))
                {
                    region1.BooleanOperation((BooleanOperationType)0, region2);
                }
            }
            objectCollection1.Clear();
            Circle circle3 = new Circle(point, Vector3d.get_ZAxis(), 0.15 * (df - 10.0));

            objectCollection1.Add((DBObject)circle3);
            DBObjectCollection fromCurves = Region.CreateFromCurves(objectCollection1);

            region1.BooleanOperation((BooleanOperationType)2, fromCurves.get_Item(0) as Region);
            Solid3d solid3d = new Solid3d();

            solid3d.Extrude(region1, this.h, 0.0);
            solid3d.BooleanOperation((BooleanOperationType)2, this.NewBox(point, this.h, df));
            if (this.doDemo == "Y")
            {
                this.AddEntityToModelSpace((Entity)evolent1);
                this.AddEntityToModelSpace((Entity)evolent2);
                this.AddEntityToModelSpace((Entity)arc);
                this.AddEntityToModelSpace((Entity)line1);
                this.AddEntityToModelSpace((Entity)line2);
                this.AddEntityToModelSpace((Entity)(((RXObject)region1).Clone() as Region));
                Thread.Sleep(this.delay * 5);
            }
            this.ZoomToEntity((Entity)solid3d);
            this.AddEntityToModelSpace((Entity)solid3d);
            DateTime now2 = DateTime.Now;

            this.ed.WriteMessage("\n耗时{0}。", new object[1]
            {
                (object)this.Elapsed(now1, now2)
            });
        }
Example #21
0
 public static DisposableWrapper Create(Type type, IntPtr unmanagedPointer, bool autoDelete)
 {
     return(DisposableWrapper.Create(type, unmanagedPointer, autoDelete));
 }
        public bool InitWndControls()
        {
            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                               Properties.Resources.resFillingGenerationFromOnlineBDWnd,
                                                                                               this,
                                                                                               CheckAccess()),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                EndYears.Clear();
                StartYears.Clear();
                EndYears.Add((int)enEndYearSpecVals.AndYounger);
                EndYears.Add((int)enEndYearSpecVals.AndElder);
                for (int i = DateTime.Now.Year - 7; i > DateTime.Now.Year - 100; i--)
                {
                    StartYears.Add(i);
                    EndYears.Add(i);
                }

                // Заполняем выпадающие списки текущими значениями
                RemoteDBComps.Clear();
                if (OnlineDBManager.Instance.IsConnectedToRemoteDB)
                {
                    try
                    {
                        var speedGroups = m_DBManager
                                          .Entities
                                          .group
                                          .Where(gr =>
                                                 gr
                                                 .participants
                                                 .SelectMany(part => part.participants_kind)
                                                 .Any(kind => kind.kind_id == (int)enOnlineDBKind.Speed))
                                          .ToList();

                        // Выбираем только соревы на скорость
                        foreach (var comp in speedGroups.SelectMany(gr => gr.events).Distinct().ToList())
                        {
                            var item = new CompItemRemoteDB()
                            {
                                Desc = new CompDescRemoteDB()
                            };
                            (item.Desc as CompDescRemoteDB).ID              = comp.id;
                            (item.Desc as CompDescRemoteDB).Name            = comp.name;
                            (item.Desc as CompDescRemoteDB).RemoteStartDate = comp.date1;
                            (item.Desc as CompDescRemoteDB).RemoteEndDate   = comp.date2;
                            (item.Desc as CompDescRemoteDB).UpdateDatesFromRemoteOnes();

                            foreach (var group in speedGroups.Where(gr => gr.events.Any(ev => ev.id == comp.id)))
                            {
                                if (DBManagerApp.m_AppSettings.m_Settings.AvailableGroupNames.Any(arg => string.Compare(arg.GroupName, group.name, true) == 0))
                                {
                                    var groupItem = new GroupItemRemoteDB((item.Desc as CompDescRemoteDB))
                                    {
                                        ID        = group.id,
                                        Name      = group.name,
                                        Sex       = ((enOnlineSex)(group.sex ? 1 : 0)).ToLocalSexValue(),
                                        StartYear = DateTime.Now.Year - group.year2,
                                        EndYear   = group.year1.HasValue ? DateTime.Now.Year - group.year1 : null,
                                        StartDate = item.Desc.StartDate,
                                        EndDate   = item.Desc.EndDate
                                    };
                                    item.Groups.Add(groupItem);
                                }
                            }

                            RemoteDBComps.Add(item);
                        }
                        SelectedComp = RemoteDBComps.LastOrDefault();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this,
                                        string.Format(Properties.Resources.resfmtErrorDuringReadingDataFromOnlineDB, ex.Message),
                                        Title,
                                        MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                        return(false);
                    }
                }

                cmbMainJudge.Items.Clear();
                foreach (var mainJudge in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_judge)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainJudge.Items.Add(mainJudge);
                }

                cmbMainSecretary.Items.Clear();
                foreach (var mainSecretary in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.main_secretary)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbMainSecretary.Items.Add(mainSecretary);
                }

                cmbRow6.Items.Clear();
                foreach (var row6 in DBManagerApp
                         .m_Entities
                         .groups
                         .Select(arg => arg.row6)
                         .Where(arg => !string.IsNullOrEmpty(arg))
                         .Distinct())
                {
                    cmbRow6.Items.Add(row6);
                }
            }

            return(true);
        }
Example #23
0
 public static int COM_FOpenFile(string filename, out DisposableWrapper <BinaryReader> file)
 {
     return(COM_FindFile(filename, out file, true));
 }
Example #24
0
        public bool Generate(out string message, Action <KeyValuePair <IGroupItem, IEnumerable <CFullMemberInfo> > > beforeExportingGroup)
        {
            message = null;

            if ((m_DataExtractor == null) || (m_DataExtractor.CompDesc == null) || ((m_DataExtractor.GroupsMembers?.Count ?? 0) == 0))
            {
                message = "error in Generate: extractor is not set, or CompDesc is not set, or there are not group members";
                return(false);
            }

            // Создаём папку с соревнованиями
            lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
            {
                if (!CopyFilesToNewFolder(m_DataExtractor.CompDesc.DestCompFolder,
                                          DBManagerApp.m_AppSettings.m_Settings.WorkbookTemplateFolder,
                                          DBManagerApp.m_AppSettings.m_Settings.FilesToCopyFromWorkbookTemplateFolder,
                                          out message))
                {
                    return(false);
                }
            }

            try
            {
                using (var excelApp = new DisposableWrapper <ExcelApplicationEx>(GlobalDefines.StartExcel(),
                                                                                 app =>
                {
                    if (app != null)
                    {
                        app.App.DisplayAlerts = true;

                        if (app.NewAppCreated)
                        {
                            app.App.Quit();
                        }

                        app = null;
                    }
                }))
                {
                    string wbkTemplateFullPath = null;
                    lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                    {
                        wbkTemplateFullPath = Path.Combine(m_DataExtractor.CompDesc.DestCompFolder,
                                                           DBManagerApp.m_AppSettings.m_Settings.WorkbookTemplateName);
                    }
                    if (!PrepareTemplateWorkbook(excelApp.Object, wbkTemplateFullPath, out message))
                    {
                        return(false);
                    }

                    foreach (var group in m_DataExtractor.GroupsMembers)
                    {
                        beforeExportingGroup(group);

                        string wbkFullPath = Path.Combine(m_DataExtractor.CompDesc.DestCompFolder, group.Key.WorkbookName);

                        if (!CreateGroupWbkAndWriteGroupDesc(excelApp.Object,
                                                             wbkTemplateFullPath,
                                                             wbkFullPath,
                                                             m_DataExtractor.CompDesc,
                                                             group.Key,
                                                             out message))
                        {
                            return(false);
                        }

                        if (!ExportDataWriteMembersToWbk(excelApp.Object, wbkFullPath, group.Value, out message))
                        {
                            return(false);
                        }
                    }

                    // Удаляем TemplateWorkbook и соответствующий xml-файл
                    File.Delete(wbkTemplateFullPath);
                    try
                    {
                        File.Delete(Path.ChangeExtension(wbkTemplateFullPath, ".xml"));
                    }
                    catch
                    { }
                }

                return(true);
            }
            catch (Exception ex)
            {
                message = $"exception in Generate: {ex.Message}";
                return(false);
            }
        }
Example #25
0
        private void RefreshSheetNames()
        {
            if (!File.Exists(SelectedComp.SourceWorkbookName) ||
                System.IO.Path.GetExtension(SelectedComp.SourceWorkbookName) == GlobalDefines.MAIN_WBK_EXTENSION ||
                System.IO.Path.GetExtension(SelectedComp.SourceWorkbookName) == GlobalDefines.XLS_EXTENSION ||
                System.IO.Path.GetExtension(SelectedComp.SourceWorkbookName) == GlobalDefines.XLSX_EXTENSION)
            {
                SheetNames.Clear();

                using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                                   Properties.Resources.resGettingSheetNames,
                                                                                                   this,
                                                                                                   CheckAccess()),
                                                                             asyncResult =>
                {
                    if (asyncResult?.hFinishedSearchEvent != null)
                    {
                        asyncResult.hFinishedSearchEvent.Set();
                    }
                }))
                {
                    try
                    {
                        using (var excelApp = new DisposableWrapper <ExcelApplicationEx>(GlobalDefines.StartExcel(),
                                                                                         app =>
                        {
                            if (app != null)
                            {
                                app.App.DisplayAlerts = true;

                                if (app.NewAppCreated)
                                {
                                    app.App.Quit();
                                }

                                app = null;
                            }
                        }))
                        {
                            bool WbkOpened;
                            var  wbk = WorkbookGenerator.OpenWbk(excelApp, SelectedComp.SourceWorkbookName, out WbkOpened);

                            if (wbk != null)
                            {
                                foreach (MSExcel.Worksheet wsh in wbk.Worksheets)
                                {
                                    SheetNames.Add(wsh.Name);
                                }
                            }
                            else
                            {
                                MessageBox.Show(this,
                                                string.Format(Properties.Resources.resfmtSourceWorkbookCouldNotBeOpened, SelectedComp.SourceWorkbookName),
                                                Title,
                                                MessageBoxButton.OK,
                                                MessageBoxImage.Error);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this,
                                        string.Format(Properties.Resources.resfmtErrorDurExcelOperation, ex.Message),
                                        Title,
                                        MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show(this, Properties.Resources.resInvalidSourceWorkbookName, Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #26
0
        /// <summary>
        /// COM_FindFile
        /// Finds the file in the search path.
        /// </summary>
        private static Int32 FindFile(String filename, out DisposableWrapper <BinaryReader> file, Boolean duplicateStream)
        {
            file = null;

            var cachepath = String.Empty;

            //
            // search through the path, one element at a time
            //
            foreach (var sp in _SearchPaths)
            {
                // is the element a pak file?
                if (sp.pack != null)
                {
                    // look through all the pak file elements
                    var pak = sp.pack;
                    foreach (var pfile in pak.files)
                    {
                        if (pfile.name.Equals(filename))
                        {
                            // found it!
                            ConsoleWrapper.DPrint("PackFile: {0} : {1}\n", sp.pack.filename, filename);
                            if (duplicateStream)
                            {
                                var pfs = ( FileStream )pak.stream.BaseStream;
                                var fs  = new FileStream(pfs.Name, FileMode.Open, FileAccess.Read, FileShare.Read);
                                file = new DisposableWrapper <BinaryReader>(new BinaryReader(fs, Encoding.ASCII), true);
                            }
                            else
                            {
                                file = new DisposableWrapper <BinaryReader>(pak.stream, false);
                            }

                            file.Object.BaseStream.Seek(pfile.filepos, SeekOrigin.Begin);
                            return(pfile.filelen);
                        }
                    }
                }
                else if (sp.pk3 != null)   // is the element a pk3 file?
                {
                    // look through all the pak file elements
                    var pk3 = sp.pk3;

                    foreach (var pfile in pk3.Entries)
                    {
                        if (pfile.FullName.Equals(filename))
                        {
                            // found it!
                            ConsoleWrapper.DPrint("PK3File: {0} : {1}\n", sp.pk3filename, filename);

                            file = new DisposableWrapper <BinaryReader>(new BinaryReader(pfile.Open( ), Encoding.ASCII), false);

                            return(( Int32 )pfile.Length);
                        }
                    }
                }
                else
                {
                    // check a file in the directory tree
                    if (!_StaticRegistered)
                    {
                        // if not a registered version, don't ever go beyond base
                        if (filename.IndexOfAny(_Slashes) != -1)     // strchr (filename, '/') || strchr (filename,'\\'))
                        {
                            continue;
                        }
                    }

                    var netpath  = sp.filename + "/" + filename; //sprintf (netpath, "%s/%s",search->filename, filename);
                    var findtime = GetFileTime(netpath);
                    if (findtime == DateTime.MinValue)
                    {
                        continue;
                    }

                    // see if the file needs to be updated in the cache
                    if (String.IsNullOrEmpty(_CacheDir)) // !com_cachedir[0])
                    {
                        cachepath = netpath;             //  strcpy(cachepath, netpath);
                    }
                    else
                    {
                        if (Utilities.IsWindows)
                        {
                            if (netpath.Length < 2 || netpath[1] != ':')
                            {
                                cachepath = _CacheDir + netpath;
                            }
                            else
                            {
                                cachepath = _CacheDir + netpath.Substring(2);
                            }
                        }
                        else
                        {
                            cachepath = _CacheDir + netpath;
                        }

                        var cachetime = GetFileTime(cachepath);
                        if (cachetime < findtime)
                        {
                            CopyFile(netpath, cachepath);
                        }
                        netpath = cachepath;
                    }

                    ConsoleWrapper.DPrint("FindFile: {0}\n", netpath);
                    var fs = OpenRead(netpath);
                    if (fs == null)
                    {
                        file = null;
                        return(-1);
                    }
                    file = new DisposableWrapper <BinaryReader>(new BinaryReader(fs, Encoding.ASCII), true);
                    return(( Int32 )fs.Length);
                }
            }

            ConsoleWrapper.DPrint("FindFile: can't find {0}\n", filename);
            return(-1);
        }
Example #27
0
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckSettings())
            {
                return;
            }

            var dataExtractor = new LocalWorkbookDataExtractor();
            var generator     = new WorkbookGenerator(dataExtractor);

            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(Title,
                                                                                               string.Format(Properties.Resources.resImportingCompetitions,
                                                                                                             SelectedComp.Name,
                                                                                                             SelectedComp.DestCompFolder),
                                                                                               this,
                                                                                               CheckAccess()),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                string errorMessage = null;
                if (!dataExtractor.Extract(SelectedComp, CompGroups, out errorMessage))
                {
                    MessageBox.Show(this,
                                    string.Format(Properties.Resources.resfmtCouldNotExtractDataFromRemoteDB, errorMessage),
                                    AppAttributes.Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return;
                }

                if (!generator.Generate(out errorMessage,
                                        arg =>
                                        CWaitingWnd.SetPrompt(((ShowAsyncResult)wrapper).WndID,
                                                              string.Format(Properties.Resources.resImportingCompetitionsWithGroupName,
                                                                            SelectedComp.Name,
                                                                            SelectedComp.DestCompFolder,
                                                                            arg.Key.Name))))
                {
                    MessageBox.Show(this,
                                    string.Format(Properties.Resources.resfmtCouldNotExtractDataToWbks, errorMessage),
                                    AppAttributes.Title,
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    return;
                }

                // Показываем книгу в проводнике
                Process.Start(SelectedComp.DestCompFolder);

                MessageBox.Show(this,
                                Properties.Resources.resDataIsExtractedToWbksSuccessfully,
                                AppAttributes.Title,
                                MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }
        }
Example #28
0
 // COM_FOpenFile(char* filename, FILE** file)
 // If the requested file is inside a packfile, a new FILE * will be opened
 // into the file.
 public static Int32 FOpenFile(String filename, out DisposableWrapper <BinaryReader> file)
 {
     return(FindFile(filename, out file, true));
 }
Example #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Param"></param>
        /// <param name="MadeChanges"></param>
        public override bool SyncWithFilesAndDB(CScannerBase.CSyncParamBase Param)
        {
            LastException = null;

            CSyncParam SyncParam = Param as CSyncParam;

            if (SyncParam == null ||
                SyncParam.m_Dir == GlobalDefines.DEFAULT_XML_STRING_VAL ||
                !Directory.Exists(SyncParam.m_Dir))
            {
                return(false);
            }

            using (var wrapper = new DisposableWrapper <ShowAsyncResult>(CWaitingWnd.ShowAsync(DBManagerApp.MainWnd.Title,
                                                                                               string.Format(Properties.Resources.resfmtSyncingDir, SyncParam.m_Dir),
                                                                                               DBManagerApp.MainWnd,
                                                                                               true),
                                                                         asyncResult =>
            {
                if (asyncResult?.hFinishedSearchEvent != null)
                {
                    asyncResult.hFinishedSearchEvent.Set();
                }
            }))
            {
                lock (EventsCS)
                {
                    if (State == enScanningThreadState.Worked)
                    {   // Синхронизацию можно проводить только при незапущенном сканировании
                        return(false);
                    }

                    m_PathWatcher.EnableRaisingEvents = false;

                    List <string> ScannedFilesFullPaths = new List <string>();

                    try
                    {
                        if (SyncParam.m_lstFileScannerSettings != null)
                        {
                            bool AllFilesSync = true;

                            foreach (CFileScannerSettings ScannerSettings in SyncParam.m_lstFileScannerSettings)
                            {
                                if (Path.GetDirectoryName(ScannerSettings.FullFilePath) != SyncParam.m_Dir)
                                {   // Файл не находится в просматриваемой папке => он нам не нужен
                                    AllFilesSync = false;
                                    lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                        DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(ScannerSettings.FullFilePath);
                                    continue;
                                }

                                string FullScannerFilePath = Path.Combine(SyncParam.m_Dir, ScannerSettings.FullFilePath);
                                ScannedFilesFullPaths.Add(FullScannerFilePath);

                                CFileScanner Scanner = null;
                                if (m_FileScanners.TryGetValue(FullScannerFilePath, out Scanner))
                                {
                                    m_FileScanners[FullScannerFilePath] =
                                        Scanner = new CFileScanner(ScannerSettings.FullFilePath,
                                                                   this,
                                                                   true,
                                                                   new CFileScanner.CSyncParam(ScannerSettings.GroupId,
                                                                                               FullScannerFilePath));
                                    if (!Scanner.SyncSuccessfully)
                                    {   // Синхронизироваться не удалось
                                        m_FileScanners.Remove(FullScannerFilePath);
                                        AllFilesSync = false;
                                        lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                            DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(ScannerSettings.FullFilePath);
                                    }
                                }
                                else
                                {
                                    Scanner = new CFileScanner(ScannerSettings.FullFilePath,
                                                               this,
                                                               true,
                                                               new CFileScanner.CSyncParam(ScannerSettings.GroupId,
                                                                                           FullScannerFilePath));
                                    if (Scanner.SyncSuccessfully)
                                    {
                                        m_FileScanners.Add(ScannerSettings.FullFilePath, Scanner);
                                    }
                                    else
                                    {   // Синхронизироваться не удалось
                                        AllFilesSync = false;
                                        lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                            DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(ScannerSettings.FullFilePath);
                                    }
                                }
                            }

                            if (!AllFilesSync)
                            {
                                DBManagerApp.m_AppSettings.Write();
                            }
                        }

                        // Пытаемся загрузить данные из всех остальных XML-файлов, имеющихся в папке
                        string[] AllXMLFullFilePaths = Directory.GetFiles(SyncParam.m_Dir, "*.xml");
                        foreach (string FullFilePath in from xmlFileL in AllXMLFullFilePaths
                                 join xmlFileR in ScannedFilesFullPaths on xmlFileL equals xmlFileR into XMLFiles
                                 from scannedFile in XMLFiles.DefaultIfEmpty()
                                 where scannedFile == null
                                 select xmlFileL)
                        {
                            CFileScanner Scanner = null;
                            if (m_FileScanners.TryGetValue(FullFilePath, out Scanner))
                            {
                                m_FileScanners[FullFilePath] =
                                    Scanner = new CFileScanner(FullFilePath,
                                                               this,
                                                               true,
                                                               new CFileScanner.CSyncParam(m_FileScanners[FullFilePath].Group == null ?
                                                                                           GlobalDefines.NO_OUR_COMP_IN_DB :
                                                                                           m_FileScanners[FullFilePath].Group.id_group,
                                                                                           FullFilePath));
                                if (!Scanner.SyncSuccessfully)
                                {   // Синхронизироваться не удалось
                                    m_FileScanners.Remove(FullFilePath);
                                    lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                        DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.Remove(FullFilePath);
                                    continue;
                                }
                            }
                            else
                            {
                                Scanner = new CFileScanner(FullFilePath,
                                                           this,
                                                           true,
                                                           new CFileScanner.CSyncParam(GlobalDefines.NO_OUR_COMP_IN_DB,
                                                                                       FullFilePath));

                                if (Scanner.SyncSuccessfully)
                                {   // Удалось синхронизироваться => добавляем сканер в m_FileScanners и в файл настроек
                                    m_FileScanners.Add(FullFilePath, Scanner);
                                }
                            }

                            if (Scanner.Group != null)
                            {
                                CFileScannerSettings ScannerSettings = new CFileScannerSettings()
                                {
                                    FullFilePath = FullFilePath,
                                    GroupId      = Scanner.Group.id_group
                                };
                                lock (DBManagerApp.m_AppSettings.m_SettingsSyncObj)
                                    DBManagerApp.m_AppSettings.m_Settings.dictFileScannerSettings.TryAddValue(FullFilePath, ScannerSettings);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        List <CDataChangedInfo> Changes = new List <CDataChangedInfo>();
                        OnException(ref Changes, ex, CompId);
                    }

                    if (Directory.Exists(m_PathWatcher.Path))
                    {
                        m_PathWatcher.EnableRaisingEvents = true;
                    }
                }
            }

            return(true);
        }