Esempio n. 1
0
 internal int GenerateCandidateId()
 {
     if (_idGenerator == null)
     {
         _idGenerator = new IDGenerator();
     }
     return -_idGenerator.Next();
 }
Esempio n. 2
0
        private static Group ReadMapGroup(BinaryReader br, List <Visgroup> visgroups, IDGenerator generator)
        {
            var grp = new Group(generator.GetNextObjectID());

            ReadMapBase(br, grp, visgroups, generator);
            grp.UpdateBoundingBox(false);
            return(grp);
        }
Esempio n. 3
0
 public static void SetIDGenerator(IDGenerator generator)
 {
     IDGenerator = generator;
 }
Esempio n. 4
0
        private static MapObject ReadMapObject(BinaryReader br, List <Visgroup> visgroups, IDGenerator generator)
        {
            var type = br.ReadCString();

            switch (type)
            {
            case "CMapWorld":
                return(ReadMapWorld(br, visgroups, generator));

            case "CMapGroup":
                return(ReadMapGroup(br, visgroups, generator));

            case "CMapSolid":
                return(ReadMapSolid(br, visgroups, generator));

            case "CMapEntity":
                return(ReadMapEntity(br, visgroups, generator));

            default:
                throw new ProviderException("Unknown RMF map object: " + type);
            }
        }
Esempio n. 5
0
        private static Entity ReadMapEntity(BinaryReader br, List <Visgroup> visgroups, IDGenerator generator)
        {
            var ent = new Entity(generator.GetNextObjectID());

            ReadMapBase(br, ent, visgroups, generator);
            ent.EntityData = ReadEntityData(br);
            br.ReadBytes(2); // Unused
            ent.Origin = br.ReadCoordinate();
            br.ReadBytes(4); // Unused
            ent.UpdateBoundingBox(false);
            return(ent);
        }
Esempio n. 6
0
        private void btnCreateOrder_Click(object sender, EventArgs e)
        {
            if (ValidateInput() &&
                MessageBox.Show(Constants.Messages.CREATE_ORDER_CONFIRMATION_MESSAGE, Constants.Messages.CREATE_ORDER_CONFIRMATION_CAPTION, MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                bool   success    = true;
                string saveResult = string.Empty;
                try
                {
                    // Creates OrderBase instance and gets general info
                    OrderBase order = new OrderBase();
                    order.id = rbtnOrderType_Regular.Checked ? IDGenerator.NewId <RegularOrder>() : IDGenerator.NewId <IrregularOrder>();
                    AppLogger.logDebug(this.ToString(), string.Format("Id: {0}", order.id));
                    order.payment_status = this.rbtnPaymentStatus_Paid.Checked ? Constants.PaymentStatus.Paid.ToString() : Constants.PaymentStatus.Unpaid.ToString();
                    order.order_status   = Constants.DeliveryStatus.Waiting.ToString();
                    order.tour_id        = cboDestination.SelectedValue.ToString();
                    order.created_date   = DateTime.Now;
                    order.created_by     = SystemParam.CurrentUser.user_name;
                    int     totalQuantity = 0;
                    decimal totalValue    = 0;
                    decimal totalCost     = 0;
                    foreach (var item in ucItemsList.OrderItems)
                    {
                        item.id        = IDGenerator.NewOrderItemId(order.id, ucItemsList.OrderItems.IndexOf(item) + 1);
                        item.order_id  = order.id;
                        totalQuantity += item.quantity;
                        totalValue    += item.value * item.quantity;
                        totalCost     += item.cost;
                    }
                    order.total_quantity = totalQuantity;
                    order.total_value    = totalValue;
                    order.total_cost     = totalCost;

                    // Convert order info per order type
                    if (rbtnOrderType_Regular.Checked)
                    {
                        RegularOrder regularOrder = order.ToRegular();
                        regularOrder.sender_id    = Sender.id;
                        regularOrder.recipient_id = Recipient.id;

                        saveResult = _regularBusiness.Insert(regularOrder, ucItemsList.OrderItems);
                    }
                    else
                    {
                        IrregularOrder irregularOrder = order.ToIrregular();
                        irregularOrder.sender_name          = tbSenderName.Text;
                        irregularOrder.sender_phone         = tbSenderPhoneNumber.Text;
                        irregularOrder.sender_id_card_no    = tbSenderIDCardNo.Text;
                        irregularOrder.sender_address       = tbSenderAddress.Text;
                        irregularOrder.recipient_name       = tbRecipientName.Text;
                        irregularOrder.recipient_phone      = tbRecipientPhoneNumber.Text;
                        irregularOrder.recipient_id_card_no = tbRecipientIDCardNo.Text;
                        irregularOrder.recipient_address    = tbRecipientAddress.Text;

                        if (rbtnPaymentStatus_Paid.Checked &&
                            (new IrregularOrderPaymentView(irregularOrder, ucItemsList.OrderItems)).ShowDialog() != System.Windows.Forms.DialogResult.OK)
                        {
                            AppLogger.logDebug(this.ToString(), "Payment process cancelled.");
                            return;
                        }
                        saveResult = _irregularBusiness.Insert(irregularOrder, ucItemsList.OrderItems);
                    }
                }
                catch (Exception ex)
                {
                    AppLogger.logError(this.ToString(), ex.Message, ex);
                    success = false;
                }
                if (success && string.IsNullOrEmpty(saveResult))
                {
                    AppLogger.logInfo(this.ToString(), "Finish inserting new order into database.");
                    MessageBox.Show("Đã tạo thành công đơn hàng mới.", string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None);
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
                else
                {
                    if (string.IsNullOrEmpty(saveResult))
                    {
                        saveResult = Constants.Messages.CREATE_ORDER_ERROR_MESSAGE;
                    }
                    MessageBox.Show(saveResult, Constants.Messages.ERROR_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 7
0
 public void GenerateId()
 {
     Id = IDGenerator.GenerateId();
 }
Esempio n. 8
0
        private void Render2D(Viewport2D vp)
        {
            if (_state == ClipState.None ||
                _clipPlanePoint1 == null ||
                _clipPlanePoint2 == null ||
                _clipPlanePoint3 == null)
            {
                return;                              // Nothing to draw at this point
            }
            var z  = (double)vp.Zoom;
            var p1 = vp.Flatten(_clipPlanePoint1);
            var p2 = vp.Flatten(_clipPlanePoint2);
            var p3 = vp.Flatten(_clipPlanePoint3);

            // Draw points
            GL.Begin(BeginMode.Quads);
            GL.Color3(Color.White);
            GLX.Square(new Vector2d(p1.DX, p1.DY), 4, z, true);
            GLX.Square(new Vector2d(p2.DX, p2.DY), 4, z, true);
            GLX.Square(new Vector2d(p3.DX, p3.DY), 4, z, true);
            GL.End();

            GL.Enable(EnableCap.LineSmooth);
            GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest);

            // Draw lines between points and point outlines
            GL.Begin(BeginMode.Lines);
            GL.Color3(Color.White);
            GL.Vertex2(p1.DX, p1.DY);
            GL.Vertex2(p2.DX, p2.DY);
            GL.Vertex2(p2.DX, p2.DY);
            GL.Vertex2(p3.DX, p3.DY);
            GL.Vertex2(p3.DX, p3.DY);
            GL.Vertex2(p1.DX, p1.DY);
            GL.Color3(Color.Black);
            GLX.Square(new Vector2d(p1.DX, p1.DY), 4, z);
            GLX.Square(new Vector2d(p2.DX, p2.DY), 4, z);
            GLX.Square(new Vector2d(p3.DX, p3.DY), 4, z);
            GL.End();

            // Draw the clipped brushes
            if (!_clipPlanePoint1.EquivalentTo(_clipPlanePoint2) &&
                !_clipPlanePoint2.EquivalentTo(_clipPlanePoint3) &&
                !_clipPlanePoint1.EquivalentTo(_clipPlanePoint3))
            {
                var plane = new Plane(_clipPlanePoint1, _clipPlanePoint2, _clipPlanePoint3);
                var faces = new List <Face>();
                var idg   = new IDGenerator();
                foreach (var solid in Document.Selection.GetSelectedObjects().OfType <Solid>().ToList())
                {
                    Solid back, front;
                    if (solid.Split(plane, out back, out front, idg))
                    {
                        if (_side != ClipSide.Front)
                        {
                            faces.AddRange(back.Faces);
                        }
                        if (_side != ClipSide.Back)
                        {
                            faces.AddRange(front.Faces);
                        }
                    }
                }
                GL.LineWidth(2);
                GL.Color3(Color.White);
                Matrix.Push();
                var mat = vp.GetModelViewMatrix();
                GL.MultMatrix(ref mat);
                Rendering.Immediate.MapObjectRenderer.DrawWireframe(faces, true, false);
                Matrix.Pop();
                GL.LineWidth(1);
            }

            GL.Hint(HintTarget.LineSmoothHint, HintMode.Fastest);
            GL.Disable(EnableCap.LineSmooth);
        }
Esempio n. 9
0
        private void Render3D(Viewport3D vp)
        {
            if (_state == ClipState.None ||
                _clipPlanePoint1 == null ||
                _clipPlanePoint2 == null ||
                _clipPlanePoint3 == null ||
                Document.Selection.IsEmpty())
            {
                return;                                  // Nothing to draw at this point
            }
            TextureHelper.Unbind();

            // Draw points

            if (!_clipPlanePoint1.EquivalentTo(_clipPlanePoint2) &&
                !_clipPlanePoint2.EquivalentTo(_clipPlanePoint3) &&
                !_clipPlanePoint1.EquivalentTo(_clipPlanePoint3))
            {
                var plane = new Plane(_clipPlanePoint1, _clipPlanePoint2, _clipPlanePoint3);

                // Draw clipped solids
                GL.Enable(EnableCap.LineSmooth);
                GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest);

                var faces = new List <Face>();
                var idg   = new IDGenerator();
                foreach (var solid in Document.Selection.GetSelectedObjects().OfType <Solid>().ToList())
                {
                    Solid back, front;
                    if (solid.Split(plane, out back, out front, idg))
                    {
                        if (_side != ClipSide.Front)
                        {
                            faces.AddRange(back.Faces);
                        }
                        if (_side != ClipSide.Back)
                        {
                            faces.AddRange(front.Faces);
                        }
                    }
                }
                GL.LineWidth(2);
                GL.Color3(Color.White);
                Rendering.Immediate.MapObjectRenderer.DrawWireframe(faces, true, false);
                GL.LineWidth(1);

                GL.Hint(HintTarget.LineSmoothHint, HintMode.Fastest);
                GL.Disable(EnableCap.LineSmooth);

                // Draw the clipping plane
                var poly  = new Polygon(plane);
                var bbox  = Document.Selection.GetSelectionBoundingBox();
                var point = bbox.Center;
                foreach (var boxPlane in bbox.GetBoxPlanes())
                {
                    var proj = boxPlane.Project(point);
                    var dist = (point - proj).VectorMagnitude() * 0.1m;
                    poly.Split(new Plane(boxPlane.Normal, proj + boxPlane.Normal * Math.Max(dist, 100)));
                }

                GL.Disable(EnableCap.CullFace);
                GL.Begin(PrimitiveType.Polygon);
                GL.Color4(Color.FromArgb(100, Color.Turquoise));
                foreach (var c in poly.Vertices)
                {
                    GL.Vertex3(c.DX, c.DY, c.DZ);
                }
                GL.End();
                GL.Enable(EnableCap.CullFace);
            }
        }
Esempio n. 10
0
        public IEnumerable <MapObject> Create(IDGenerator generator, Box box, ITexture texture, int roundDecimals)
        {
            var numSides = (int)_numSides.GetValue();

            if (numSides < 3)
            {
                yield break;
            }
            var wallWidth = _wallWidth.GetValue();

            if (wallWidth < 1)
            {
                yield break;
            }
            var arc = _arc.GetValue();

            if (arc < 1)
            {
                yield break;
            }
            var startAngle = _startAngle.GetValue();

            if (startAngle < 0 || startAngle > 359)
            {
                yield break;
            }
            var addHeight  = _addHeight.GetValue();
            var curvedRamp = _curvedRamp.GetValue();
            var tiltAngle  = curvedRamp ? _tiltAngle.GetValue() : 0;

            if (DMath.Abs(tiltAngle % 180) == 90)
            {
                yield break;
            }
            var tiltInterp = curvedRamp && _tiltInterp.GetValue();

            // Very similar to the pipe brush, except with options for start angle, arc, height and tilt
            var width  = box.Width;
            var length = box.Length;
            var height = box.Height;

            var majorOut = width / 2;
            var majorIn  = majorOut - wallWidth;
            var minorOut = length / 2;
            var minorIn  = minorOut - wallWidth;

            var start = DMath.DegreesToRadians(startAngle);
            var tilt  = DMath.DegreesToRadians(tiltAngle);
            var angle = DMath.DegreesToRadians(arc) / numSides;

            // Calculate the coordinates of the inner and outer ellipses' points
            var outer = new Coordinate[numSides + 1];
            var inner = new Coordinate[numSides + 1];

            for (var i = 0; i < numSides + 1; i++)
            {
                var a          = start + i * angle;
                var h          = i * addHeight;
                var interp     = tiltInterp ? DMath.Cos(DMath.PI / numSides * (i - numSides / 2M)) : 1;
                var tiltHeight = wallWidth / 2 * interp * DMath.Tan(tilt);

                var xval = box.Center.X + majorOut * DMath.Cos(a);
                var yval = box.Center.Y + minorOut * DMath.Sin(a);
                var zval = box.Start.Z + (curvedRamp ? h + tiltHeight : 0);
                outer[i] = new Coordinate(xval, yval, zval).Round(roundDecimals);

                xval     = box.Center.X + majorIn * DMath.Cos(a);
                yval     = box.Center.Y + minorIn * DMath.Sin(a);
                zval     = box.Start.Z + (curvedRamp ? h - tiltHeight : 0);
                inner[i] = new Coordinate(xval, yval, zval).Round(roundDecimals);
            }

            // Create the solids
            var colour = Colour.GetRandomBrushColour();
            var z      = new Coordinate(0, 0, height).Round(roundDecimals);

            for (var i = 0; i < numSides; i++)
            {
                var faces = new List <Coordinate[]>();

                // Since we are triangulating/splitting each arch segment, we need to generate 2 brushes per side
                if (curvedRamp)
                {
                    // The splitting orientation depends on the curving direction of the arch
                    if (addHeight >= 0)
                    {
                        faces.Add(new[] { outer[i], outer[i] + z, outer[i + 1] + z, outer[i + 1] });
                        faces.Add(new[] { outer[i + 1], outer[i + 1] + z, inner[i] + z, inner[i] });
                        faces.Add(new[] { inner[i], inner[i] + z, outer[i] + z, outer[i] });
                        faces.Add(new[] { outer[i] + z, inner[i] + z, outer[i + 1] + z });
                        faces.Add(new[] { outer[i + 1], inner[i], outer[i] });
                    }
                    else
                    {
                        faces.Add(new[] { inner[i + 1], inner[i + 1] + z, inner[i] + z, inner[i] });
                        faces.Add(new[] { outer[i], outer[i] + z, inner[i + 1] + z, inner[i + 1] });
                        faces.Add(new[] { inner[i], inner[i] + z, outer[i] + z, outer[i] });
                        faces.Add(new[] { inner[i + 1] + z, outer[i] + z, inner[i] + z });
                        faces.Add(new[] { inner[i], outer[i], inner[i + 1] });
                    }
                    yield return(MakeSolid(generator, faces, texture, colour));

                    faces.Clear();

                    if (addHeight >= 0)
                    {
                        faces.Add(new[] { inner[i + 1], inner[i + 1] + z, inner[i] + z, inner[i] });
                        faces.Add(new[] { inner[i], inner[i] + z, outer[i + 1] + z, outer[i + 1] });
                        faces.Add(new[] { outer[i + 1], outer[i + 1] + z, inner[i + 1] + z, inner[i + 1] });
                        faces.Add(new[] { inner[i + 1] + z, outer[i + 1] + z, inner[i] + z });
                        faces.Add(new[] { inner[i], outer[i + 1], inner[i + 1] });
                    }
                    else
                    {
                        faces.Add(new[] { outer[i], outer[i] + z, outer[i + 1] + z, outer[i + 1] });
                        faces.Add(new[] { inner[i + 1], inner[i + 1] + z, outer[i] + z, outer[i] });
                        faces.Add(new[] { outer[i + 1], outer[i + 1] + z, inner[i + 1] + z, inner[i + 1] });
                        faces.Add(new[] { outer[i] + z, inner[i + 1] + z, outer[i + 1] + z });
                        faces.Add(new[] { outer[i + 1], inner[i + 1], outer[i] });
                    }
                    yield return(MakeSolid(generator, faces, texture, colour));
                }
                else
                {
                    var h = i * addHeight * Coordinate.UnitZ;
                    faces.Add(new[] { outer[i], outer[i] + z, outer[i + 1] + z, outer[i + 1] }.Select(x => x + h).ToArray());
                    faces.Add(new[] { inner[i + 1], inner[i + 1] + z, inner[i] + z, inner[i] }.Select(x => x + h).ToArray());
                    faces.Add(new[] { outer[i + 1], outer[i + 1] + z, inner[i + 1] + z, inner[i + 1] }.Select(x => x + h).ToArray());
                    faces.Add(new[] { inner[i], inner[i] + z, outer[i] + z, outer[i] }.Select(x => x + h).ToArray());
                    faces.Add(new[] { inner[i + 1] + z, outer[i + 1] + z, outer[i] + z, inner[i] + z }.Select(x => x + h).ToArray());
                    faces.Add(new[] { inner[i], outer[i], outer[i + 1], inner[i + 1] }.Select(x => x + h).ToArray());
                    yield return(MakeSolid(generator, faces, texture, colour));
                }
            }
        }
Esempio n. 11
0
        public CreateServerPage()
        {
            InitializeComponent();
            backbtn.Content = Data.Language.Hardcoded.GetValue("back");
            saveBtn.Content = Data.Language.Hardcoded.GetValue("save");
            serverViewModel = new NewServerViewModel
            {
                Title      = Data.Language.Hardcoded.GetValue("+ New Server"),
                AddCommand = new DelegateCommand <NewServerViewModel>(vm =>
                {
                    if (!vm.IsValid())
                    {
                        MessageBox.Show(vm.Error);
                        return;
                    }
                    var isBindingToDomain = rbDomain.IsChecked.Value;
                    var messageText       = Data.Language.Hardcoded.GetValue("Domain or port number are required");

                    string name          = null;
                    System.Guid domainid = default(System.Guid);
                    bool defaultbinding  = false;
                    string subDomain     = null;
                    int port             = 0;
                    if (isBindingToDomain)
                    {
                        if (string.IsNullOrEmpty(vm.Domain))
                        {
                            MessageBox.Show(messageText);
                            return;
                        }
                        DomainResult domainresult = null;

                        domainresult = DomainHelper.Parse(vm.Domain);
                        var domain   = new Domain
                        {
                            DomainName     = domainresult.Domain,
                            OrganizationId = GlobalDb.Users.DefaultUser.CurrentOrgId
                        };
                        GlobalDb.Domains.AddOrUpdate(domain);
                        if (domainresult != null && !string.IsNullOrEmpty(domainresult.Domain))
                        {
                            name      = domainresult.Domain;
                            domainid  = IDGenerator.GetDomainId(domainresult.Domain);
                            subDomain = domainresult.SubDomain;
                        }
                        else
                        {
                            MessageBox.Show("Domain is not right");
                            return;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(vm.Port))
                        {
                            int.TryParse(vm.Port, out port);
                        }
                        if (port <= 0 || port > 65535)
                        {
                            MessageBox.Show(messageText);
                            return;
                        }
                        name           = "Port" + vm.Port.ToString();
                        defaultbinding = true;
                    }

                    // add new website.
                    WebSite site = new WebSite
                    {
                        Name          = name,
                        LocalRootPath = vm.Path
                    };
                    GlobalDb.WebSites.AddOrUpdate(site);

                    var bind = new Data.Models.Binding
                    {
                        DomainId           = domainid,
                        SubDomain          = subDomain,
                        WebSiteId          = site.Id,
                        DefaultPortBinding = defaultbinding,
                        Port = port
                    };

                    GlobalDb.Bindings.AddOrUpdate(bind);

                    this.Redirect(new ServerPage());
                })
            };
            DataContext = serverViewModel;
        }
Esempio n. 12
0
        public static async void InitializeApp()
        {
            item_layout_size = screenWidth / 4;

            // Initialize ID Groups
            IDGenerator.InitializeIDGroup(itemStorageIdGenerator);
            IDGenerator.InitializeIDGroup(cabinetEditIdGenerator);
            IDGenerator.InitializeIDGroup(fridgeEditIdGenerator);
            IDGenerator.InitializeIDGroup(storageCellIdGenerator);
            IDGenerator.InitializeIDGroup(IOSNotificationIdGenerator);
            LocalStorageController.ResetDatabase(); // WARNING: FOR TESTING PURPOSES ONLY
            LocalStorageController.InitializeLocalDataBase();

            // Initialize Important Grids
            GridManager.InitializeGrid(metaGridName, 9, 4, GridLength.Auto, GridLength.Star);
            GridManager.InitializeGrid(unplacedGridName, 0, 4, GridLength.Star, GridLength.Star);

            Console.WriteLine("ContentManger 75 is user new -=================================================================== " + ContentManager.isUserNew + ContentManager.isLocal);
            // Load saved data
            if (!isUserNew)
            {
                List <Cabinet> localCabinets = await LocalStorageController.GetTableListAsync <Cabinet>();

                List <Fridge> localFridges = await LocalStorageController.GetTableListAsync <Fridge>();

                List <StorageCell> localStorageCells = await LocalStorageController.GetTableListAsync <StorageCell>();

                List <Item> localItems = await LocalStorageController.GetTableListAsync <Item>();

                List <Cabinet>     baseCabinets     = new List <Cabinet>();
                List <Fridge>      baseFridges      = new List <Fridge>();
                List <StorageCell> baseStorageCells = new List <StorageCell>();
                List <Item>        baseItems        = new List <Item>();

                if (!isLocal)
                {
                    // Populating list with firebase
                    baseCabinets     = (await FireBaseController.GetCabinets()).ToList().ConvertAll(o => o.Object);
                    baseFridges      = (await FireBaseController.GetFridges()).ToList().ConvertAll(o => o.Object);
                    baseItems        = (await FireBaseController.GetItems()).ToList().ConvertAll(o => o.Object);
                    baseStorageCells = (await FireBaseController.GetStorageCells());


                    // Load with cloud data
                    ContentLoader.LoadItems(baseItems);
                    ContentLoader.LoadCabinets(baseCabinets, baseStorageCells, baseItems);
                    ContentLoader.LoadFridges(baseFridges, baseStorageCells, baseItems);
                }
                else
                {
                    // Load with local data
                    ContentLoader.LoadItems(localItems);
                    ContentLoader.LoadCabinets(localCabinets, localStorageCells, localItems);
                    ContentLoader.LoadFridges(localFridges, localStorageCells, localItems);
                }
            }

            if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.Internet)
            {
                Console.WriteLine("Contentmanager 135 User Has Internet :)");
            }
            else
            {
                Console.WriteLine("Contentmanager 138 User Has No Internet :<(");
            }

            // start UI sequence
            pageController.InitializePageSequence();
        }
Esempio n. 13
0
 internal void scaleVODs(string vodType, decimal scale, IDGenerator editor)
 {
     scaleEntities(vodType, scale, editor);
 }
Esempio n. 14
0
        internal LinkedList <ScaledEntity> scaleEntities(string entityType, decimal scale, IDGenerator editor)
        {
            if (scale < 0.0M)
            {
                throw new ArgumentOutOfRangeException("Scale must not be negative.");
            }

            void duplicateLevelEntity(XElement i, LinkedList <ScaledEntity> dupedEntities)
            {
                XElement iCopy = new XElement(i);       // Duplicate at the same position
                var      newID = editor.newID();

                iCopy.Element("Simple").SetAttributeValue("value", newID);
                SaveEditor.getFirstSimplePropertyNamed(iCopy.Element("Complex"), "ID").SetAttributeValue("value", newID);

                Add(iCopy);
                dupedEntities.AddLast(new ScaledEntity((UInt64)i.Element("Simple").Attribute("value"), newID));
            }

            uint   multiples = (uint)scale;             // How many duplicates to certainly make of each entity
            double chance    = (double)(scale % 1);     // The chance of making 1 more duplicate per entity

            Random rand = new Random();

            var selectedEntities = new LinkedList <ScaledEntity>();

            if (scale < 1.0M)
            {
                // chance is now chance to not remove existing entities
                // selectedEntities will be those removed

                // 0 >= scale < 1
                foreach (var i in getEntitiesOfTypes(entityType))
                {
                    if (scale == 0.0M || chance < rand.NextDouble())
                    {
                        var id = (UInt64)i.Element("Simple").Attribute("value");
                        Remove(id);
                        selectedEntities.AddLast(new ScaledEntity(id));
                    }
                }
                //Console.WriteLine( "selectedEntities: " + selectedEntities.Count );
            }
            else
            {
                foreach (var i in getEntitiesOfTypes(entityType))
                {
                    // First the certain duplications
                    for (uint m = 1; m < multiples; m++)
                    {
                        duplicateLevelEntity(i, selectedEntities);
                    }
                    // And now the chance-based duplication
                    if (chance >= rand.NextDouble())    // If the chance is not less than the roll
                    {
                        duplicateLevelEntity(i, selectedEntities);
                    }
                }
                //Console.WriteLine( "selectedEntities: " + selectedEntities.Count );
            }

            return(selectedEntities);
        }
Esempio n. 15
0
 public void OnAddEntity(string name, Scene scene)
 {
     EntityID   = IDGenerator.GetNewID();
     EntityName = name;
     Scene      = scene;
 }
Esempio n. 16
0
        public IEnumerable <MapObject> Create(IDGenerator generator, Box box, ITexture texture, int roundDecimals)
        {
            var width   = box.Width;
            var length  = Math.Max(1, Math.Abs((int)box.Length));
            var height  = box.Height;
            var flatten = (float)_flattenFactor.Value;
            var text    = _text.GetValue();

            var family = _fontChooser.GetFontFamily();
            var style  = Enum.GetValues(typeof(FontStyle)).OfType <FontStyle>().FirstOrDefault(fs => family.IsStyleAvailable(fs));

            if (!family.IsStyleAvailable(style))
            {
                family = FontFamily.GenericSansSerif;
            }

            var set = new PolygonSet();

            var sizes = new List <RectangleF>();

            using (var bmp = new Bitmap(1, 1))
            {
                using (var g = System.Drawing.Graphics.FromImage(bmp))
                {
                    using (var font = new Font(family, length, style, GraphicsUnit.Pixel))
                    {
                        for (var i = 0; i < text.Length; i += 32)
                        {
                            using (var sf = new StringFormat(StringFormat.GenericTypographic))
                            {
                                var rem   = Math.Min(text.Length, i + 32) - i;
                                var range = Enumerable.Range(0, rem).Select(x => new CharacterRange(x, 1)).ToArray();
                                sf.SetMeasurableCharacterRanges(range);
                                var reg = g.MeasureCharacterRanges(text.Substring(i, rem), font, new RectangleF(0, 0, float.MaxValue, float.MaxValue), sf);
                                sizes.AddRange(reg.Select(x => x.GetBounds(g)));
                            }
                        }
                    }
                }
            }

            var xOffset = box.Start.DX;
            var yOffset = box.End.DY;

            for (var ci = 0; ci < text.Length; ci++)
            {
                var c    = text[ci];
                var size = sizes[ci];

                var gp = new GraphicsPath();
                gp.AddString(c.ToString(CultureInfo.InvariantCulture), family, (int)style, length, new PointF(0, 0), StringFormat.GenericTypographic);
                gp.Flatten(new System.Drawing.Drawing2D.Matrix(), flatten);

                var polygons = new List <Polygon>();
                var poly     = new List <PolygonPoint>();

                for (var i = 0; i < gp.PointCount; i++)
                {
                    var type  = gp.PathTypes[i];
                    var point = gp.PathPoints[i];

                    poly.Add(new PolygonPoint(point.X + xOffset, -point.Y + yOffset));

                    if ((type & 0x80) == 0x80)
                    {
                        polygons.Add(new Polygon(poly));
                        poly.Clear();
                    }
                }

                var     tri     = new List <Polygon>();
                Polygon polygon = null;
                foreach (var p in polygons)
                {
                    if (polygon == null)
                    {
                        polygon = p;
                        tri.Add(p);
                    }
                    else if (p.CalculateWindingOrder() != polygon.CalculateWindingOrder())
                    {
                        polygon.AddHole(p);
                    }
                    else
                    {
                        polygon = null;
                        tri.Add(p);
                    }
                }

                foreach (var pp in tri)
                {
                    try
                    {
                        P2T.Triangulate(pp);
                        set.Add(pp);
                    }
                    catch
                    {
                        // Ignore
                    }
                }

                xOffset += size.Width;
            }

            var zOffset = box.Start.Z;

            foreach (var polygon in set.Polygons)
            {
                foreach (var t in polygon.Triangles)
                {
                    var points = t.Points.Select(x => new Coordinate((decimal)x.X, (decimal)x.Y, zOffset).Round(roundDecimals)).ToList();

                    var faces = new List <Coordinate[]>();

                    // Add the vertical faces
                    var z = new Coordinate(0, 0, height).Round(roundDecimals);
                    for (var j = 0; j < points.Count; j++)
                    {
                        var next = (j + 1) % points.Count;
                        faces.Add(new[] { points[j], points[j] + z, points[next] + z, points[next] });
                    }
                    // Add the top and bottom faces
                    faces.Add(points.ToArray());
                    faces.Add(points.Select(x => x + z).Reverse().ToArray());

                    // Nothing new here, move along
                    var solid = new Solid(generator.GetNextObjectID())
                    {
                        Colour = Colour.GetRandomBrushColour(), Flags = (System.UInt32)SolidFlags.solid
                    };
                    foreach (var arr in faces)
                    {
                        var face = new Face(generator.GetNextFaceID())
                        {
                            Parent  = solid,
                            Plane   = new Plane(arr[0], arr[1], arr[2]),
                            Colour  = solid.Colour,
                            Texture = { Texture = texture }
                        };
                        face.Vertices.AddRange(arr.Select(x => new Vertex(x, face)));
                        face.Init();
                        solid.Faces.Add(face);
                    }
                    solid.UpdateBoundingBox();
                    yield return(solid);
                }
            }
        }
Esempio n. 17
0
 public HistoricActivityInstanceManager(DbContext dbContex, ILoggerFactory loggerFactory, IDGenerator idGenerator) : base(dbContex, loggerFactory, idGenerator)
 {
 }
Esempio n. 18
0
 public IncidentManager(DbContext dbContex, ILoggerFactory loggerFactory, IDGenerator idGenerator) : base(dbContex, loggerFactory, idGenerator)
 {
 }
Esempio n. 19
0
 private MapObject GetBrush(Polygon bounds, decimal depth, IDGenerator idGenerator)
 {
     return(null);
 }
Esempio n. 20
0
        public static void DoTimeTest()
        {
            UtilityRandom random = new UtilityRandom();

            random.Next();
            IDGenerator geanIdg = new IDGenerator();

            geanIdg.Generate();

            int count = 500 * 10000;

            Stopwatch sw = new Stopwatch();

            Console.WriteLine("Start......");

            //Gean.Data的Id生成器-----------------------
            long geanIdTime;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = geanIdg.Generate();
            }
            sw.Stop();
            geanIdTime = sw.ElapsedMilliseconds;

            //随机数字-----------------------
            long randNumTime;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = random.Next(1, count).ToString();
            }
            sw.Stop();
            randNumTime = sw.ElapsedMilliseconds;

            //随机4位小写字母-----------------------
            long randTime;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = random.GetString(4, UtilityRandom.RandomCharType.Lowercased);
            }
            sw.Stop();
            randTime = sw.ElapsedMilliseconds;

            //数字累计-----------------------
            long gerTime;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = (i + i + i).ToString();
            }
            sw.Stop();
            gerTime = sw.ElapsedMilliseconds;

            //IDGenerator生成-----------------------
            long idgTime;

            sw.Reset();
            sw.Start();
            UUIDGenerator idg = new UUIDGenerator();

            for (int i = 0; i < count; i++)
            {
                string id = idg.Generate();
            }
            sw.Stop();
            idgTime = sw.ElapsedMilliseconds;

            //Guid-----------------------
            long guidTime;

            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = Guid.NewGuid().ToString();
            }
            sw.Stop();
            guidTime = sw.ElapsedMilliseconds;


            Console.WriteLine("Gean.Data的Id生成器: " + geanIdTime.ToString() + Sudu(geanIdTime, count));
            Console.WriteLine("随机数字: " + randNumTime.ToString() + Sudu(randNumTime, count));
            Console.WriteLine("随机4位小写字母: " + randTime.ToString() + Sudu(randTime, count));
            Console.WriteLine("数字累计: " + gerTime.ToString() + Sudu(gerTime, count));
            Console.WriteLine("IDGenerator生成: " + idgTime.ToString() + Sudu(idgTime, count));
            Console.WriteLine("Guid: " + guidTime.ToString() + Sudu(guidTime, count));
        }
Esempio n. 21
0
 private static World ReadWorldSpawn(BinaryReader br, List <Visgroup> visgroups, IDGenerator generator)
 {
     return((World)ReadMapObject(br, visgroups, generator));
 }
Esempio n. 22
0
        ///// <param name="verticesBtmRet">Vector3_DW数据</param>
        /// <summary>
        ///     根据导线点坐标绘制巷道
        /// </summary>
        /// <summary>
        ///     获得导线边线点坐标集
        /// </summary>
        /// <returns>导线边线点坐标集List</returns>
        //private List<IPoint> GetTunnelPts(Vector3_DW[] verticesBtmRet)
        //{
        //    var lstBtmRet = new List<IPoint>();
        //    try
        //    {
        //        Vector3_DW vector3dw;
        //        IPoint pt;
        //        for (int i = 0; i < verticesBtmRet.Length; i++)
        //        {
        //            vector3dw = new Vector3_DW();
        //            vector3dw = verticesBtmRet[i];
        //            pt = new PointClass();
        //            pt.X = vector3dw.X;
        //            pt.Y = vector3dw.Y;
        //            pt.Z = vector3dw.Z;
        //            if (!lstBtmRet.Contains(pt))
        //            {
        //                lstBtmRet.Add(pt);
        //            }
        //        }

        //        return lstBtmRet;
        //    }
        //    catch
        //    {
        //        return null;
        //    }
        //}

        #endregion 绘制导线点和巷道图形
        private void btnMultTxt_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                RestoreDirectory = true,
                Multiselect      = true,
                Filter           = @"文本文件(*.txt)|*.txt|所有文件(*.*)|*.*"
            };

            _errorMsg = @"失败文件名:";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var fileCount = ofd.FileNames.Length;

            pbCount.Maximum = fileCount * 2;
            pbCount.Value   = 0;
            foreach (var fileName in ofd.FileNames)
            {
                lblTotal.Text = fileCount.ToString(CultureInfo.InvariantCulture);
                string safeFileName = null;
                try
                {
                    using (new SessionScope())
                    {
                        safeFileName = fileName.Substring(fileName.LastIndexOf(@"\", StringComparison.Ordinal) + 1);
                        var strs            = safeFileName.Split('-');
                        var miningAreaName  = strs[0];
                        var workingFaceName = strs[1];
                        var tunnelName      = strs[2].Split('.')[0];

                        var miningArea = MiningArea.FindOneByMiningAreaName(miningAreaName);
                        if (miningArea == null)
                        {
                            Alert.confirm("该采区不存在,请先添加采区");
                            return;
                        }
                        var workingFace = WorkingFace.FindByWorkingFaceNameAndMiningAreaId(workingFaceName, miningArea.MiningAreaId);
                        if (workingFace == null)
                        {
                            workingFace = AddWorkingFace(miningArea, workingFaceName);
                        }
                        if (workingFace == null)
                        {
                            return;
                        }
                        Tunnel tunnel;
                        if (workingFace.Tunnels != null &&
                            workingFace.Tunnels.FirstOrDefault(u => u.TunnelName == tunnelName) != null)
                        {
                            tunnel = workingFace.Tunnels.FirstOrDefault(u => u.TunnelName == tunnelName);
                        }
                        else
                        {
                            tunnel = AddTunnel(workingFace, tunnelName);
                        }

                        var    sr = new StreamReader(fileName, Encoding.GetEncoding("GB2312"));
                        string fileContent;
                        var    wirePoints = new List <WirePoint>();
                        while ((fileContent = sr.ReadLine()) != null)
                        {
                            if (String.IsNullOrEmpty(fileContent))
                            {
                                continue;
                            }
                            var temp1     = fileContent.Split('|');
                            var pointName = temp1[0];
                            var pointX    = temp1[1];
                            var pointY    = temp1[2];

                            wirePoints.Add(new WirePoint
                            {
                                BindingId     = IDGenerator.NewBindingID(),
                                WirePointName = pointName,
                                CoordinateX   = Convert.ToDouble(pointX),
                                CoordinateY   = Convert.ToDouble(pointY),
                                CoordinateZ   = 0,
                                LeftDis       = 2.5,
                                RightDis      = 2.5,
                                TopDis        = 0,
                                BottomDis     = 0
                            });
                        }
                        if (wirePoints.Count < 2)
                        {
                            Alert.alert(Const_GM.WIRE_INFO_MSG_POINT_MUST_MORE_THAN_TWO);
                            throw new Exception();
                        }
                        var wire = Wire.FindOneByTunnelId(tunnel.TunnelId);

                        if (wire != null)
                        {
                            wire.WireName = tunnelName.Split('.').Length > 0
                                ? tunnelName.Split('.')[0] + "导线点"
                                : tunnelName + "导线点";
                            wire.WirePoints = wirePoints;
                        }
                        else
                        {
                            wire = new Wire
                            {
                                Tunnel      = tunnel,
                                CheckDate   = DateTime.Now,
                                MeasureDate = DateTime.Now,
                                CountDate   = DateTime.Now,
                                WireName    =
                                    tunnelName.Split('.').Length > 0
                                        ? tunnelName.Split('.')[0] + "导线点"
                                        : tunnelName + "导线点",
                                WirePoints = wirePoints
                            };
                        }
                        wire.Save();
                        pbCount.Value++;
                        DrawWirePoint(wirePoints, "CHANGE");
                        double hdwid;
                        _dics = ConstructDics(tunnel, out hdwid);
                        UpdateHdbyPnts(tunnel.TunnelId, wirePoints, _dics, hdwid);
                        pbCount.Value++;
                        lblSuccessed.Text =
                            (Convert.ToInt32(lblSuccessed.Text) + 1).ToString(CultureInfo.InvariantCulture);
                    }
                }
                catch
                {
                    pbCount.Value++;
                    lblError.Text =
                        (Convert.ToInt32(lblError.Text) + 1).ToString(CultureInfo.InvariantCulture);
                    _errorMsg         += safeFileName + "\n";
                    btnDetails.Enabled = true;
                }
            }
            UpdateWarningDataMsg msg;

            if (selectTunnelUserControl1.SelectedTunnel != null)
            {
                msg = new UpdateWarningDataMsg(Const.INVALID_ID, selectTunnelUserControl1.SelectedTunnel.TunnelId,
                                               Wire.TableName, OPERATION_TYPE.ADD, DateTime.Now);
            }
            else
            {
                msg = new UpdateWarningDataMsg(Const.INVALID_ID, 0,
                                               Wire.TableName, OPERATION_TYPE.ADD, DateTime.Now);
            }
            SocketUtil.SendMsg2Server(msg);
            Alert.alert("导入完成");
        }
Esempio n. 23
0
        private static void ReadMapBase(BinaryReader br, MapObject obj, List <Visgroup> visgroups, IDGenerator generator)
        {
            var visgroupId = br.ReadInt32();

            if (visgroupId > 0 && visgroups.Any(x => x.ID == visgroupId))
            {
                obj.Visgroups.Add(visgroupId);
                obj.IsVisgroupHidden = !visgroups.First(x => x.ID == visgroupId).Visible;
            }

            obj.Colour = br.ReadRGBColour();

            var numChildren = br.ReadInt32();

            for (var i = 0; i < numChildren; i++)
            {
                var child = ReadMapObject(br, visgroups, generator);
                child.SetParent(obj);
            }
        }
Esempio n. 24
0
        //private readonly IWithdrawService _withdrawService = null;

        public XResult <AllotAmountWithdrawApplyResponse> Apply(AllotAmountWithdrawApplyRequest request)
        {
            if (request == null)
            {
                return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.INVALID_ARGUMENT, new ArgumentNullException(nameof(request))));
            }

            String service = $"{this.GetType().FullName}.Apply(...)";

            if (!request.IsValid)
            {
                _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, $"{nameof(request)}.IsValid", LogPhase.ACTION, $"快钱盈帐通:{request.ErrorMessage}", request);
                return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.INVALID_ARGUMENT, new ArgumentException(request.ErrorMessage)));
            }

            if (request.Amount < GlobalConfig.X99bill_YZT_WithdrawMinAmount)
            {
                return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.INVALID_ARGUMENT, new ArgumentException($"提现金额至少为{GlobalConfig.X99bill_YZT_WithdrawMinAmount.ToString()}元")));
            }

            var requestHash = $"withdraw:{request.PayeeId}".GetHashCode();

            if (_lockProvider.Exists(requestHash))
            {
                return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.SUBMIT_REPEAT));
            }

            try
            {
                if (!_lockProvider.Lock(requestHash))
                {
                    return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.SUBMIT_REPEAT));
                }

                //检查是否已开户
                if (!_personalSubAccountRepository.Exists(x => x.AppId == request.AppId && x.UID == request.PayeeId))
                {
                    _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "__CheckPersonalAccountRegisterInfo", LogPhase.ACTION, "该用户尚未开户", request);
                    return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.UN_REGISTERED));
                }

                //检查是否已绑卡
                if (!_withdrawBankCardBindInfoRepository.Exists(x => x.AppId == request.AppId && x.PayeeId == request.PayeeId))
                {
                    _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "__CheckBankCardBindInfo", LogPhase.ACTION, "该用户尚未绑卡", request);
                    return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.NO_BANKCARD_BOUND));
                }

                var existsOrder = _allotAmountWithdrawOrderRepository.Exists(x => x.OutTradeNo == request.OutTradeNo);
                if (existsOrder)
                {
                    return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.OUT_TRADE_NO_EXISTED));
                }

                var newId            = IDGenerator.GenerateID();
                var newWithdrawOrder = new AllotAmountWithdrawOrder()
                {
                    Id           = newId,
                    AppId        = request.AppId,
                    TradeNo      = newId.ToString(),
                    PayeeId      = request.PayeeId,
                    OutTradeNo   = request.OutTradeNo,
                    Amount       = request.Amount,
                    CustomerFee  = request.CustomerFee,
                    MerchantFee  = request.MerchantFee,
                    SettlePeriod = request.SettlePeriod,
                    Status       = WithdrawOrderStatus.APPLY.ToString(),
                    ApplyTime    = DateTime.Now
                };

                _allotAmountWithdrawOrderRepository.Add(newWithdrawOrder);

                var saveResult = _allotAmountWithdrawOrderRepository.SaveChanges();
                if (!saveResult.Success)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, $"{nameof(_allotAmountWithdrawOrderRepository)}.SaveChanges()", "保存分账提现记录失败", saveResult.FirstException, newWithdrawOrder);
                    return(new XResult <AllotAmountWithdrawApplyResponse>(null, ErrorCode.DB_UPDATE_FAILED, saveResult.FirstException));
                }

                var resp = new AllotAmountWithdrawApplyResponse()
                {
                    PayeeId    = newWithdrawOrder.PayeeId,
                    OutTradeNo = newWithdrawOrder.OutTradeNo,
                    Amount     = newWithdrawOrder.Amount,
                    Status     = CommonStatus.SUCCESS.ToString(),
                    Msg        = $"申请{CommonStatus.SUCCESS.GetDescription()}"
                };

                return(new XResult <AllotAmountWithdrawApplyResponse>(resp));
            }
            finally
            {
                _lockProvider.UnLock(requestHash);
            }
        }
Esempio n. 25
0
        private static Solid ReadMapSolid(BinaryReader br, List <Visgroup> visgroups, IDGenerator generator)
        {
            var sol = new Solid(generator.GetNextObjectID());

            ReadMapBase(br, sol, visgroups, generator);
            var numFaces = br.ReadInt32();

            for (var i = 0; i < numFaces; i++)
            {
                var face = ReadFace(br, generator);
                face.Parent = sol;
                face.Colour = sol.Colour;
                sol.Faces.Add(face);
            }
            sol.UpdateBoundingBox(false);
            return(sol);
        }
Esempio n. 26
0
 public DecisionRequirementsDefinitionManager(DbContext dbContex, ILoggerFactory loggerFactory, IDGenerator idGenerator) : base(dbContex, loggerFactory, idGenerator)
 {
 }
Esempio n. 27
0
        private static MapObject ReadMapWorld(BinaryReader br, List <Visgroup> visgroups, IDGenerator generator)
        {
            var wld = new World(generator.GetNextObjectID());

            ReadMapBase(br, wld, visgroups, generator);
            wld.EntityData = ReadEntityData(br);
            var numPaths = br.ReadInt32();

            for (var i = 0; i < numPaths; i++)
            {
                wld.Paths.Add(ReadPath(br));
            }
            return(wld);
        }
Esempio n. 28
0
        /// <summary>
        /// Adds new DataObjects to the database.
        /// </summary>
        /// <param name="dataObjects">DataObjects to add to the database</param>
        /// <param name="tableHandler">Table Handler for the DataObjects Collection</param>
        /// <returns>True if objects were added successfully; false otherwise</returns>
        protected override IEnumerable <bool> AddObjectImpl(DataTableHandler tableHandler, IEnumerable <DataObject> dataObjects)
        {
            var success = new List <bool>();

            if (!dataObjects.Any())
            {
                return(success);
            }

            try
            {
                // Check Primary Keys
                var usePrimaryAutoInc = tableHandler.FieldElementBindings.Any(bind => bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement);

                // Columns
                var columns = tableHandler.FieldElementBindings.Where(bind => bind.PrimaryKey == null || !bind.PrimaryKey.AutoIncrement)
                              .Select(bind => new { Binding = bind, ColumnName = string.Format("`{0}`", bind.ColumnName), ParamName = string.Format("@{0}", bind.ColumnName) }).ToArray();

                // Prepare SQL Query
                var command = string.Format("INSERT INTO `{0}` ({1}) VALUES({2})", tableHandler.TableName,
                                            string.Join(", ", columns.Select(col => col.ColumnName)),
                                            string.Join(", ", columns.Select(col => col.ParamName)));

                var objs = dataObjects.ToArray();

                // Init Object Id GUID
                foreach (var obj in objs.Where(obj => obj.ObjectId == null))
                {
                    obj.ObjectId = IDGenerator.GenerateID();
                }

                // Build Parameters
                var parameters = objs.Select(obj => columns.Select(col => new QueryParameter(col.ParamName, col.Binding.GetValue(obj), col.Binding.ValueType)));

                // Primary Key Auto Inc Handler
                if (usePrimaryAutoInc)
                {
                    var lastId = ExecuteScalarImpl(command, parameters, true);

                    var binding         = tableHandler.FieldElementBindings.First(bind => bind.PrimaryKey != null && bind.PrimaryKey.AutoIncrement);
                    var resultByObjects = lastId.Select((result, index) => new { Result = Convert.ToInt64(result), DataObject = objs[index] });

                    foreach (var result in resultByObjects)
                    {
                        if (result.Result > 0)
                        {
                            DatabaseSetValue(result.DataObject, binding, result.Result);
                            result.DataObject.ObjectId    = result.Result.ToString();
                            result.DataObject.Dirty       = false;
                            result.DataObject.IsPersisted = true;
                            result.DataObject.IsDeleted   = false;
                            success.Add(true);
                        }
                        else
                        {
                            if (Log.IsErrorEnabled)
                            {
                                Log.ErrorFormat("Error adding data object into {0} Object = {1}, UsePrimaryAutoInc, Query = {2}", tableHandler.TableName, result.DataObject, command);
                            }

                            success.Add(false);
                        }
                    }
                }
                else
                {
                    var affected        = ExecuteNonQueryImpl(command, parameters);
                    var resultByObjects = affected.Select((result, index) => new { Result = result, DataObject = objs[index] });

                    foreach (var result in resultByObjects)
                    {
                        if (result.Result > 0)
                        {
                            result.DataObject.Dirty       = false;
                            result.DataObject.IsPersisted = true;
                            result.DataObject.IsDeleted   = false;
                            success.Add(true);
                        }
                        else
                        {
                            if (Log.IsErrorEnabled)
                            {
                                Log.ErrorFormat("Error adding data object into {0} Object = {1} Query = {2}", tableHandler.TableName, result.DataObject, command);
                            }

                            success.Add(false);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (Log.IsErrorEnabled)
                {
                    Log.ErrorFormat("Error while adding data objects in table: {0}\n{1}", tableHandler.TableName, e);
                }
            }

            return(success);
        }
Esempio n. 29
0
 public Fridge()
 {
     ID = new IDGenerator().GetNewID("FG");
 }
Esempio n. 30
0
 public ExternalTaskManager(DbContext dbContex, ILoggerFactory loggerFactory, IDGenerator idGenerator)
     : base(dbContex, loggerFactory, idGenerator)
 {
 }
Esempio n. 31
0
        public static void DoTimeTest()
        {
            UtilityRandom random = new UtilityRandom();
            random.Next();
            IDGenerator geanIdg = new IDGenerator();
            geanIdg.Generate();

            int count = 500 * 10000;

            Stopwatch sw = new Stopwatch();
            Console.WriteLine("Start......");

            //Gean.Data的Id生成器-----------------------
            long geanIdTime;
            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = geanIdg.Generate();
            }
            sw.Stop();
            geanIdTime = sw.ElapsedMilliseconds;

            //随机数字-----------------------
            long randNumTime;
            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = random.Next(1, count).ToString();
            }
            sw.Stop();
            randNumTime = sw.ElapsedMilliseconds;

            //随机4位小写字母-----------------------
            long randTime;
            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = random.GetString(4, UtilityRandom.RandomCharType.Lowercased);
            }
            sw.Stop();
            randTime = sw.ElapsedMilliseconds;

            //数字累计-----------------------
            long gerTime;
            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = (i + i + i).ToString();
            }
            sw.Stop();
            gerTime = sw.ElapsedMilliseconds;

            //IDGenerator生成-----------------------
            long idgTime;
            sw.Reset();
            sw.Start();
            UUIDGenerator idg = new UUIDGenerator();
            for (int i = 0; i < count; i++)
            {
                string id = idg.Generate();
            }
            sw.Stop();
            idgTime = sw.ElapsedMilliseconds;

            //Guid-----------------------
            long guidTime;
            sw.Reset();
            sw.Start();
            for (int i = 0; i < count; i++)
            {
                string id = Guid.NewGuid().ToString();
            }
            sw.Stop();
            guidTime = sw.ElapsedMilliseconds;

            Console.WriteLine("Gean.Data的Id生成器: " + geanIdTime.ToString() + Sudu(geanIdTime, count));
            Console.WriteLine("随机数字: " + randNumTime.ToString() + Sudu(randNumTime, count));
            Console.WriteLine("随机4位小写字母: " + randTime.ToString() + Sudu(randTime, count));
            Console.WriteLine("数字累计: " + gerTime.ToString() + Sudu(gerTime, count));
            Console.WriteLine("IDGenerator生成: " + idgTime.ToString() + Sudu(idgTime, count));
            Console.WriteLine("Guid: " + guidTime.ToString() + Sudu(guidTime, count));
        }
Esempio n. 32
0
 protected BaseObject()
 {
     SerialID = IDGenerator.Get();
 }