public ResultItemViewModel(BsonElement element)
        {
            LazyLoading = true;
            Element = element;
            Type = element.Value.BsonType.ToString();
            if (element.Value.IsBsonArray)
            {
                Value = _toolTip = string.Format("{0} ({1} items)", element.Value.BsonType.ToString(), element.Value.AsBsonArray.Count);
            }
            else if (element.Value.IsBsonDocument)
                Value = _toolTip = string.Format("{0} ({1} fields)", element.Value.BsonType.ToString(), element.Value.AsBsonDocument.ElementCount);
            else if (element.Value.IsValidDateTime)
            {
                Value = _toolTip = element.Value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFzzz");
            }
            else
            {
                Value = _toolTip = element.Value.ToJson(jsonWriterSettings).Replace("\n", " ").Replace("\r", " ").Replace("\\n", " ").Replace("\\r", " ").Trim(' ', '\"');
                if (Value.Length > 100)
                    Value = Value.Substring(0, 100) + "...";
                if (_toolTip.Length > 1000)
                    _toolTip = _toolTip.Substring(0, 1000) + "...";
            }

            CopyToClipboard = new RelayCommand(() =>
            {
                string res = "";
                if (Element.Value.IsBsonDocument)
                {
                    res = Element.Value.ToJson(jsonWriterSettings);
                }
                else
                {
                    BsonDocument document = new BsonDocument();
                    document.Add(Element);
                    res = document.ToJson(jsonWriterSettings);
                }
                Clipboard.SetText(res);
            });
            CopyName = new RelayCommand(() =>
            {
                Clipboard.SetText(Element.Name);
            });
            CopyValue = new RelayCommand(() =>
            {
                string res = Element.Value.ToJson(jsonWriterSettings);
                Clipboard.SetText(res);
            });
        }
 public void TestBsonElementEquals() {
     BsonElement lhs = new BsonElement("Hello", "World");
     BsonElement rhs = new BsonElement("Hello", "World");
     Assert.AreNotSame(lhs, rhs);
     Assert.AreEqual(lhs, rhs);
     Assert.AreEqual(lhs.GetHashCode(), rhs.GetHashCode());
 }
Example #3
0
		/// <summary>
		/// Generates a $group pipeline command based upon the specified group-by and grouping-aggregation specifications
		/// </summary>
		/// <param name="GroupBy">The group-by specification for grouping distinction</param>
		/// <param name="Aggregations">An enumerable of grouping-aggregation expressions</param>
		public static BsonDocument Group(BsonElement GroupBy, IEnumerable<BsonElement> Aggregations) {
			var value = new BsonDocument(GroupBy);
			if (Aggregations != null && Aggregations.Any()) {
				value.Add(Aggregations);
			}
			return new BsonDocument() { { "$group", value } };
		}
 public void TestStringElement()
 {
     BsonElement element = new BsonElement("abc", "def");
     string value = element.Value.AsString;
     Assert.AreEqual("abc", element.Name);
     Assert.AreEqual("def", value);
 }
        private void _validateProperty(Property property, BsonElement documentProperty)
        {
            var value = documentProperty.Value;
            
            if (property.Options != null)
            {
                _assertRequired(property, value);

                _assertUnique(property, value);

                _assertPattern(property, value);
            }

            _assertType(property.Name, property.Type.Name, value.BsonType.ToString());
        }
 /// <summary>
 /// Add Element
 /// </summary>
 /// <param name="BaseDoc"></param>
 /// <param name="AddElement"></param>
 public static String AddElement(String ElementPath, BsonElement AddElement)
 {
     BsonDocument BaseDoc = SystemManager.GetCurrentDocument();
     BsonValue t = GetLastParentDocument(BaseDoc, ElementPath, true);
     if (t.IsBsonDocument)
     {
         try
         {
             t.AsBsonDocument.InsertAt(t.AsBsonDocument.ElementCount, AddElement);
         }
         catch (InvalidOperationException ex)
         {
             return ex.Message;
         }
     }
     SystemManager.GetCurrentCollection().Save(BaseDoc);
     return String.Empty;
 }
Example #7
0
 public static BsonDocument ToGroupSeriesDocument()
 {
     var result = new BsonDocument();
     var finalElements = new List<BsonElement>();
     //first slicer will always be first element in ID representing x axis
     finalElements.Add(new BsonElement("_id", new BsonString("$key.s0")));
     //push first
     var pushElements = new List<BsonElement>();
     //second slicer will always be second element in Key
     pushElements.Add(new BsonElement("s1", new BsonString("$key.s1")));
     //value will always be first element in value
     pushElements.Add(new BsonElement("f0", new BsonString("$value.f0")));
     var pushElement = new BsonElement("$push", new BsonDocument(pushElements));
     var pushField = new BsonElement("f0", new BsonDocument(pushElement));
     finalElements.Add(pushField);
     result.Add(new BsonElement("$group", new BsonDocument(finalElements)));
     return result;
 }
Example #8
0
 /// <summary>
 ///     获得BsonDocument
 /// </summary>
 /// <returns></returns>
 public BsonElement GetBsonDoc()
 {
     BsonDocument ResourceContent = null;
     switch (Type)
     {
         case ResourceType.DataBase:
             ResourceContent = new BsonDocument("db", DataBaseName);
             ResourceContent.Add("collection", CollectionName);
             break;
         case ResourceType.Cluster:
             ResourceContent = new BsonDocument("cluster", BsonBoolean.True);
             break;
         case ResourceType.Any:
             ResourceContent = new BsonDocument("anyResource",BsonBoolean.True);
             break;
     }
     BsonElement Resource = new BsonElement("resource", ResourceContent);
     return Resource;
 }
 // Insert documents into Mongo
 public List<BsonDocument> Create(string collectionName, List<Dictionary<string, BsonValue>> rows)
 {
     List<BsonDocument> documents = new List<BsonDocument>();
     // call to MongoDB which create collection
     var collection = database.GetCollection<BsonDocument>(collectionName);
     foreach (Dictionary<string, BsonValue> row in rows) {
         BsonDocument document = new BsonDocument();
         // create a BSON element for each item in the document
         foreach (string key in row.Keys) {
             BsonElement element = new BsonElement(key, row[key]);
             document.Add(element);
         }
         // add the document to the result list
         documents.Add(document);
         // insert the document into the Mongo collection
         //collection.Insert(document);
     }
     return documents;
 }
Example #10
0
 /// <summary>
 /// 增加角色
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void cmdAddRole_Click(object sender, EventArgs e)
 {
     if (String.IsNullOrEmpty(cmbDB.Text))
     {
         MyMessageBox.ShowMessage("Error", "Please Select A Database");
         return;
     }
     frmUserRole mUserRole = new frmUserRole(new BsonArray());
     mUserRole.ShowDialog();
     BsonElement otherRole = new BsonElement(cmbDB.Text, mUserRole.Result);
     if (OtherDBRolesDict.ContainsKey(cmbDB.Text))
     {
         OtherDBRolesDict[cmbDB.Text] = otherRole;
     }
     else
     {
         OtherDBRolesDict.Add(cmbDB.Text, otherRole);
     }
     RefreshOtherDBRoles();
 }
Example #11
0
 /// <summary>
 ///     Add Element
 /// </summary>
 /// <param name="elementPath"></param>
 /// <param name="addElement"></param>
 /// <param name="currentCollection"></param>
 public static string AddElement(string elementPath, BsonElement addElement, BsonDocument currentDocument,
     MongoCollection currentCollection)
 {
     var baseDoc = currentDocument;
     var t = GetLastParentDocument(baseDoc, elementPath, true);
     if (t.IsBsonDocument)
     {
         try
         {
             t.AsBsonDocument.InsertAt(t.AsBsonDocument.ElementCount, addElement);
         }
         catch (InvalidOperationException ex)
         {
             return ex.Message;
         }
     }
     if (!currentCollection.IsCapped())
     {
         currentCollection.Save(baseDoc);
     }
     return string.Empty;
 }
Example #12
0
        public static BsonDocument ToProjectionDocument(this GroupDefinition source)
        {
            var keyItems = new List<BsonElement>();
            var valueItems = new List<BsonElement>();

            var ignoreId = new BsonElement("_id", new BsonInt32(0));

            for (var i = 0; i < source.Dimensions.Count; i++)
            {
                var el = new BsonElement(String.Format("s{0}", i), new BsonString(String.Format("$_id.s{0}", i)));
                keyItems.Add(el);
            }
            for (var i = 0; i < source.Measures.Count; i++)
            {
                var el = new BsonElement(String.Format("f{0}", i), new BsonString(String.Format("$f{0}", i)));
                valueItems.Add(el);
            }

            var keyValuesDoc = new BsonDocument();
            keyValuesDoc.AddRange(keyItems);
            var keyValuesElement = new BsonElement("key", keyValuesDoc);

            var valueValuesDoc = new BsonDocument();
            valueValuesDoc.AddRange(valueItems);

            var valueValuesElement = new BsonElement("value", valueValuesDoc);

            var ignoreIdDoc = new BsonDocument();
            ignoreIdDoc.Add();

            var projectDoc = new BsonDocument();
            projectDoc.Add(new BsonElement("_id", new BsonInt32(0)));
            projectDoc.Add(keyValuesElement);
            projectDoc.Add(valueValuesElement);
            var projectElement = new BsonElement("$project", projectDoc);
            var result = new BsonDocument {projectElement};
            return result;
        }
Example #13
0
        public static BsonDocument ToMatchDocument(this MatchDefinition source)
        {
            var result = new BsonDocument();
            var matchFilterElements = new List<BsonElement>();
            source.Filters.Where(x=>x.AvailableFilterValues.Any(y=>y.Active)).ToList().ForEach(f =>
            {
                var colDoc = new BsonDocument();
                var selectedValues = new BsonArray();
                var selectedFilterValues = f.AvailableFilterValues.Where(x=>x.Active).Select(x => x.Value).Select(x => new BsonString(x)).ToList();
                selectedValues.AddRange(selectedFilterValues);
                //var itemE
                var itemElm = new BsonElement("$in", selectedValues);
                colDoc.Add(itemElm);
                var colElm = new BsonElement(f.Column.ColumnName, colDoc);
                matchFilterElements.Add(colElm);
            });
            var elementsDoc = new BsonDocument();
            elementsDoc.AddRange(matchFilterElements);

            var matchElement = new BsonElement("$match", elementsDoc);
            result.Add(matchElement);
            return result;
        }
        private BsonDocument WrapCommandForQueryMessage(BsonDocument command, ConnectionDescription connectionDescription, out bool messageContainsSessionId, out bool secondaryOk)
        {
            messageContainsSessionId = false;
            var extraElements = new List <BsonElement>();

            if (_session.Id != null)
            {
                var areSessionsSupported =
                    connectionDescription.HelloResult.LogicalSessionTimeout.HasValue ||
                    connectionDescription.HelloResult.ServiceId.HasValue;
                if (areSessionsSupported)
                {
                    var lsid = new BsonElement("lsid", _session.Id);
                    extraElements.Add(lsid);
                    messageContainsSessionId = true;
                }
                else
                {
                    if (!_session.IsImplicit)
                    {
                        throw new MongoClientException("Sessions are not supported.");
                    }
                }
            }
            if (_serverApi != null)
            {
                extraElements.Add(new BsonElement("apiVersion", _serverApi.Version.ToString()));
                if (_serverApi.Strict.HasValue)
                {
                    extraElements.Add(new BsonElement("apiStrict", _serverApi.Strict.Value));
                }
                if (_serverApi.DeprecationErrors.HasValue)
                {
                    extraElements.Add(new BsonElement("apiDeprecationErrors", _serverApi.DeprecationErrors.Value));
                }
            }
            if (_session.ClusterTime != null)
            {
                var clusterTime = new BsonElement("$clusterTime", _session.ClusterTime);
                extraElements.Add(clusterTime);
            }
#pragma warning disable 618
            Action <BsonWriterSettings> writerSettingsConfigurator = null;
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                writerSettingsConfigurator = s => s.GuidRepresentation = GuidRepresentation.Unspecified;
            }
#pragma warning restore 618
            var appendExtraElementsSerializer = new ElementAppendingSerializer <BsonDocument>(BsonDocumentSerializer.Instance, extraElements, writerSettingsConfigurator);
            var commandWithExtraElements      = new BsonDocumentWrapper(command, appendExtraElementsSerializer);

            var serverType             = connectionDescription != null ? connectionDescription.HelloResult.ServerType : ServerType.Unknown;
            var readPreferenceDocument = QueryHelper.CreateReadPreferenceDocument(serverType, _readPreference, out secondaryOk);

            var wrappedCommand = new BsonDocument
            {
                { "$query", commandWithExtraElements },
                { "$readPreference", readPreferenceDocument, readPreferenceDocument != null }
            };
            if (_additionalOptions != null)
            {
                wrappedCommand.Merge(_additionalOptions, overwriteExistingElements: false);
            }

            if (wrappedCommand.ElementCount == 1)
            {
                return(wrappedCommand["$query"].AsBsonDocument);
            }
            else
            {
                return(wrappedCommand);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            try
            {
                MongoClient dbClient = new MongoClient("mongodb://127.0.0.1:27017");

                //Database List
                var dbList = dbClient.ListDatabases().ToList();

                Console.WriteLine("The list of databases are :");
                foreach (var item in dbList)
                {
                    Console.WriteLine(item);
                }

                Console.WriteLine("\n\n");

                //Get Database and Collection
                IMongoDatabase db       = dbClient.GetDatabase("test");
                var            collList = db.ListCollections().ToList();
                Console.WriteLine("The list of collections are :");
                foreach (var item in collList)
                {
                    Console.WriteLine(item);
                }

                var things = db.GetCollection <BsonDocument>("things");

                //CREATE
                BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Luis");

                BsonDocument personDoc = new BsonDocument();
                personDoc.Add(personFirstNameElement);
                personDoc.Add(new BsonElement("PersonAge", 23));

                things.InsertOne(personDoc);

                //UPDATE
                BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName", "Alfredo");

                BsonDocument updatePersonDoc = new BsonDocument();
                updatePersonDoc.Add(updatePersonFirstNameElement);
                updatePersonDoc.Add(new BsonElement("PersonAge", 24));

                BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Luis"));

                var updateDoc = things.FindOneAndReplace(findPersonDoc, updatePersonDoc);

                Console.WriteLine(updateDoc);

                //DELETE
                BsonDocument findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Alfredo"));

                things.FindOneAndDelete(findAnotherPersonDoc);

                //READ
                var resultDoc = things.Find(new BsonDocument()).ToList();
                foreach (var item in resultDoc)
                {
                    Console.WriteLine(item.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
 /// <summary>
 /// Cut Element
 /// </summary>
 /// <param name="ElementPath"></param>
 public static void CutElement(String ElementPath, BsonElement El)
 {
     _ClipElement   = El;
     _IsElementClip = true;
     DropElement(ElementPath, El);
 }
Example #17
0
 /// <summary>
 /// Initializes a new instance of the QueryDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public QueryDocument(BsonElement element)
     : base(element)
 {
 }
Example #18
0
 /// <summary>
 /// Initializes a new instance of the UpdateDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public UpdateDocument(BsonElement element)
     : base(element)
 {
 }
Example #19
0
        protected virtual bool TryConfigureClientOption(MongoClientSettings settings, BsonElement option)
        {
            switch (option.Name)
            {
            case "readConcernLevel":
                var level = (ReadConcernLevel)Enum.Parse(typeof(ReadConcernLevel), option.Value.AsString, ignoreCase: true);
                settings.ReadConcern = new ReadConcern(level);
                break;

            case "readPreference":
                settings.ReadPreference = ReadPreferenceFromBsonValue(option.Value);
                break;

            case "retryWrites":
                settings.RetryWrites = option.Value.ToBoolean();
                break;

            case "w":
                if (option.Value.IsString)
                {
                    settings.WriteConcern = new WriteConcern(option.Value.AsString);
                }
                else
                {
                    settings.WriteConcern = new WriteConcern(option.Value.ToInt32());
                }
                break;

            case "retryReads":
                settings.RetryReads = option.Value.ToBoolean();
                break;

            case "appname":
                settings.ApplicationName = $"{option.Value}_async_{_async}";
                break;

            case "connectTimeoutMS":
                var connectTimeoutMS = option.Value.ToInt32();
                settings.ConnectTimeout = connectTimeoutMS == 0 ? Timeout.InfiniteTimeSpan : TimeSpan.FromMilliseconds(connectTimeoutMS);
                break;

            case "directConnection":
                var isDirectConnection = option.Value.ToBoolean();

#pragma warning disable CS0618 // Type or member is obsolete
                settings.ConnectionMode = ConnectionMode.Automatic;
                settings._connectionModeSwitch(ConnectionModeSwitch.UseDirectConnection);
#pragma warning restore CS0618 // Type or member is obsolete
                settings.DirectConnection = isDirectConnection;

                if (isDirectConnection)
                {
                    settings.Servers = new MongoServerAddress[]
                    {
                        settings.Servers.First()
                    };
                }
                break;

            case "heartbeatFrequencyMS":
                settings.HeartbeatInterval = TimeSpan.FromMilliseconds(option.Value.ToInt32());
                break;

            case "maxPoolSize":
                settings.MaxConnectionPoolSize = option.Value.ToInt32();
                break;

            case "minPoolSize":
                settings.MinConnectionPoolSize = option.Value.ToInt32();
                break;

            case "serverSelectionTimeoutMS":
                settings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(option.Value.ToInt32());
                break;

            case "socketTimeoutMS":
                settings.SocketTimeout = TimeSpan.FromMilliseconds(option.Value.ToInt32());
                break;

            default:
                return(false);
            }

            return(true);
        }
 /// <summary>
 /// Cut Element
 /// </summary>
 /// <param name="ElementPath"></param>
 public static void CopyElement(BsonElement El)
 {
     _ClipElement = El;
     _IsElementClip = true;
 }
        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            e.DrawDefault = false;
            var rect = e.Bounds;

            if (rect.Height == 0)
            {
                //在展开节点的时候会出现根节点绘制错误的问题
                return;
            }
            if ((e.State & TreeNodeStates.Selected) != 0)
            {
                e.Graphics.FillRectangle(
                    (e.State & TreeNodeStates.Focused) != 0 ? SystemBrushes.Highlight : SystemBrushes.Control, rect);
            }
            else
            {
                e.Graphics.FillRectangle(Brushes.White, rect);
            }
            var indentWidth = DatatreeView.Indent * e.Node.Level + 25;

            e.Graphics.DrawRectangle(SystemPens.Control, rect);
            var stringRect = new Rectangle(e.Bounds.X + indentWidth, e.Bounds.Y, colName.Width - indentWidth,
                                           e.Bounds.Height);

            var treeNameString = e.Node.Text;

            if (treeNameString.EndsWith(ConstMgr.ArrayMark))
            {
                //Array_Mark 在计算路径的时候使用,不过,在表示的时候,则不能表示
                treeNameString = treeNameString.Substring(0, treeNameString.Length - ConstMgr.ArrayMark.Length);
            }
            if (treeNameString.EndsWith(ConstMgr.DocumentMark))
            {
                //Document_Mark 在计算路径的时候使用,不过,在表示的时候,则不能表示
                treeNameString = treeNameString.Substring(0, treeNameString.Length - ConstMgr.DocumentMark.Length);
            }
            //感谢cyrus的建议,选中节点的文字表示,底色变更
            if ((e.State & TreeNodeStates.Selected) != 0 && (e.State & TreeNodeStates.Focused) != 0)
            {
                e.Graphics.DrawString(treeNameString, Font, new SolidBrush(SystemColors.HighlightText), stringRect);
            }
            else
            {
                e.Graphics.DrawString(treeNameString, Font, new SolidBrush(Color.Black), stringRect);
            }
            //CSHARP-1066: Change BsonElement from a class to a struct.
            BsonElement mElement;

            if (e.Node.Tag != null)
            {
                if (e.Node.Tag.GetType() != typeof(BsonElement))
                {
                    mElement = new BsonElement("", (BsonValue)e.Node.Tag);
                }
                else
                {
                    mElement = (BsonElement)e.Node.Tag;
                }
            }
            var mValue = e.Node.Tag as BsonValue;

            //画框
            if (e.Node.GetNodeCount(true) > 0 ||
                (mElement.Value != null && (mElement.Value.IsBsonDocument || mElement.Value.IsBsonArray)))
            {
                //感谢Cyrus测试出来的问题:RenderWithVisualStyles应该加上去的。
                if (VisualStyleRenderer.IsSupported && Application.RenderWithVisualStyles)
                {
                    var leftPoint = e.Bounds.X + indentWidth - 20;
                    //感谢 Shadower http://home.cnblogs.com/u/14697/ 贡献的代码
                    var thisNode = e.Node;
                    var glyph    = thisNode.IsExpanded
                        ? VisualStyleElement.TreeView.Glyph.Opened
                        : VisualStyleElement.TreeView.Glyph.Closed;
                    var vsr = new VisualStyleRenderer(glyph);
                    vsr.DrawBackground(e.Graphics, new Rectangle(leftPoint, e.Bounds.Y + 4, 16, 16));
                }
                else
                {
                    var leftPoint = e.Bounds.X + indentWidth - 20;
                    e.Graphics.DrawRectangle(new Pen(Color.Black), new Rectangle(leftPoint, e.Bounds.Y + 4, 12, 12));
                    var leftMid   = new Point(leftPoint + 2, e.Bounds.Y + 10);
                    var rightMid  = new Point(leftPoint + 10, e.Bounds.Y + 10);
                    var topMid    = new Point(leftPoint + 6, e.Bounds.Y + 6);
                    var bottomMid = new Point(leftPoint + 6, e.Bounds.Y + 14);
                    e.Graphics.DrawLine(new Pen(Color.Black), leftMid, rightMid);
                    if (!e.Node.IsExpanded)
                    {
                        e.Graphics.DrawLine(new Pen(Color.Black), topMid, bottomMid);
                    }
                }
            }

            for (var intColumn = 1; intColumn < 3; intColumn++)
            {
                rect.Offset(listView.Columns[intColumn - 1].Width, 0);
                rect.Width = listView.Columns[intColumn].Width;
                e.Graphics.DrawRectangle(SystemPens.Control, rect);
                if (mElement.Value != null || mValue != null)
                {
                    var strColumnText = string.Empty;
                    if (intColumn == 1)
                    {
                        if (mElement.Value != null)
                        {
                            if (!mElement.Value.IsBsonDocument && !mElement.Value.IsBsonArray)
                            {
                                if (mElement.Value.IsValidDateTime)
                                {
                                    if (IsUTC)
                                    {
                                        strColumnText = mElement.Value.AsBsonDateTime.ToUniversalTime().ToString();
                                    }
                                    else
                                    {
                                        strColumnText = mElement.Value.AsBsonDateTime.ToLocalTime().ToString();
                                    }
                                }
                                else
                                {
                                    strColumnText = mElement.Value.ToString();
                                }
                            }
                        }
                        else
                        {
                            if (mValue != null)
                            {
                                //Type这里已经有表示Type的标识了,这里就不重复显示了。
                                if (!mValue.IsBsonDocument && !mValue.IsBsonArray)
                                {
                                    if (e.Node.Level > 0)
                                    {
                                        //根节点有Value,可能是ID,用来取得选中节点的信息
                                        strColumnText = mValue.ToString();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        strColumnText = mElement.Value != null
                            ? mElement.Value.GetType().Name.Substring(4)
                            : mValue.GetType().Name.Substring(4);
                    }

                    var flags = TextFormatFlags.EndEllipsis;
                    switch (listView.Columns[intColumn].TextAlign)
                    {
                    case HorizontalAlignment.Center:
                        flags |= TextFormatFlags.HorizontalCenter;
                        break;

                    case HorizontalAlignment.Left:
                        flags |= TextFormatFlags.Left;
                        break;

                    case HorizontalAlignment.Right:
                        flags |= TextFormatFlags.Right;
                        break;

                    default:
                        break;
                    }

                    rect.Y++;
                    if ((e.State & TreeNodeStates.Selected) != 0 &&
                        (e.State & TreeNodeStates.Focused) != 0)
                    {
                        TextRenderer.DrawText(e.Graphics, strColumnText, e.Node.NodeFont, rect,
                                              SystemColors.HighlightText, flags);
                    }
                    else
                    {
                        TextRenderer.DrawText(e.Graphics, strColumnText, e.Node.NodeFont, rect, e.Node.ForeColor,
                                              e.Node.BackColor, flags);
                    }
                    rect.Y--;
                }
            }
        }
Example #22
0
        protected virtual bool TryConfigureClientOption(MongoClientSettings settings, BsonElement option)
        {
            switch (option.Name)
            {
            case "readConcernLevel":
                var level = (ReadConcernLevel)Enum.Parse(typeof(ReadConcernLevel), option.Value.AsString, ignoreCase: true);
                settings.ReadConcern = new ReadConcern(level);
                break;

            case "readPreference":
                settings.ReadPreference = ReadPreferenceFromBsonValue(option.Value);
                break;

            case "retryWrites":
                settings.RetryWrites = option.Value.ToBoolean();
                break;

            case "w":
                if (option.Value.IsString)
                {
                    settings.WriteConcern = new WriteConcern(option.Value.AsString);
                }
                else
                {
                    settings.WriteConcern = new WriteConcern(option.Value.ToInt32());
                }
                break;

            case "retryReads":
                settings.RetryReads = option.Value.ToBoolean();
                break;

            case "appname":
                settings.ApplicationName = option.Value.ToString();
                break;

            case "connectTimeoutMS":
                settings.ConnectTimeout = TimeSpan.FromMilliseconds(option.Value.ToInt32());
                break;

            case "heartbeatFrequencyMS":
                settings.HeartbeatInterval = TimeSpan.FromMilliseconds(option.Value.ToInt32());
                break;

            case "serverSelectionTimeoutMS":
                settings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(option.Value.ToInt32());
                break;

            default:
                return(false);
            }

            return(true);
        }
Example #23
0
        public ModelKeyValue(BsonElement Detail, Action Refresh)
        {
            InitializeComponent();
            TextName.Text     = Detail.Name;
            TextValue.Text    = Detail.Value.ToString();
            TextBoxKey.Text   = Detail.Name;
            TextBoxValue.Text = Detail.Value.ToString();


            //action delete key
            BTNDelete.MouseDown += (s, e) =>
            {
                SDK.SDK_PageDashboards.DashboardGame.PageKeyValue.RemoveKeys(Detail.Name, result =>
                {
                    if (result)
                    {
                        Refresh();
                    }
                    else
                    {
                        DashboardGame.Notifaction("Faild Delte", Notifaction.StatusMessage.Error);
                    }
                });
            };

            //action BTNEdit
            BTNEdit.MouseDown += (s, e) =>
            {
                Root.Visibility     = Visibility.Collapsed;
                RootEdit.Visibility = Visibility.Visible;
            };


            //action btnBack
            BTNBack.MouseDown += (s, e) =>
            {
                Root.Visibility     = Visibility.Visible;
                RootEdit.Visibility = Visibility.Collapsed;
            };


            //Action btn Save
            BTNSave.MouseDown += (s, e) =>
            {
                if (TextBoxValue.Text.Length >= 1 && TextBoxKey.Text.Length >= 1)
                {
                    SDK.SDK_PageDashboards.DashboardGame.PageKeyValue.UpdateKeys(TextBoxKey.Text, TextBoxValue.Text.ToString(), result =>
                    {
                        if (result)
                        {
                            DashboardGame.Notifaction("Key Updated", Notifaction.StatusMessage.Ok);
                            Refresh();
                        }
                        else
                        {
                            DashboardGame.Notifaction("Update Faild", Notifaction.StatusMessage.Error);
                        }
                    });
                }
                else
                {
                    DashboardGame.Notifaction("Key or Value Short", Notifaction.StatusMessage.Error);
                }
            };
        }
Example #24
0
 /// <summary>
 /// Initializes a new instance of the UpdateDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public UpdateDocument(BsonElement element)
     : base(element)
 {
 }
 /// <summary>
 /// Modify Element
 /// </summary>
 /// <param name="ElementPath"></param>
 /// <param name="NewValue"></param>
 /// <param name="ValueIndex"></param>
 /// <param name="El"></param>
 public static void ModifyElement(String ElementPath, BsonValue NewValue, BsonElement El)
 {
     BsonDocument BaseDoc = SystemManager.GetCurrentDocument();
     BsonValue t = GetLastParentDocument(BaseDoc, ElementPath);
     if (t.IsBsonDocument)
     {
         t.AsBsonDocument.GetElement(El.Name).Value = NewValue;
     }
     SystemManager.GetCurrentCollection().Save(BaseDoc);
 }
 /// <summary>
 /// Initializes a new instance of the GroupByDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public GroupByDocument(BsonElement element)
     : base(element)
 {
 }
Example #27
0
        private void frmGroup_Load(object sender, EventArgs e)
        {
            this.cmbForfinalize.SelectedIndexChanged += new EventHandler(
                 (x, y) => { this.txtfinalizeJs.Text = MongoDBHelper.LoadJavascript(cmbForfinalize.Text); }
            );
            cmbForReduce.SelectedIndexChanged += new EventHandler(
                (x, y) => { txtReduceJs.Text = MongoDBHelper.LoadJavascript(cmbForReduce.Text); }
            );
            foreach (var item in SystemManager.GetJsNameList())
            {
                cmbForfinalize.Items.Add(item);
                cmbForReduce.Items.Add(item);
            }

            MongoCollection mongoCol = SystemManager.GetCurrentCollection();
            List<String> MongoColumn = MongoDBHelper.GetCollectionSchame(mongoCol);
            Point _conditionPos = new Point(50, 20);
            foreach (String item in MongoColumn)
            {
                //动态加载控件
                CheckBox ctrItem = new CheckBox();
                ctrItem.Name = item;
                ctrItem.Location = _conditionPos;
                ctrItem.Text = item;
                this.panColumn.Controls.Add(ctrItem);
                //纵向位置的累加
                _conditionPos.Y += ctrItem.Height;
            }
            _conditionPos = new Point(50, 20);
            ctlAddBsonEl firstAddBsonElCtl = new ctlAddBsonEl();
            firstAddBsonElCtl.Location = _conditionPos;
            firstAddBsonElCtl.Name = "BsonEl" + _conditionCount.ToString();
            BsonElement el = new BsonElement("count", new BsonInt32(0));
            firstAddBsonElCtl.setElement(el);
            panBsonEl.Controls.Add(firstAddBsonElCtl);

            if (!SystemManager.IsUseDefaultLanguage())
            {
                lblReduceFunction.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Group_Tab_Reduce);
                cmdSaveReduceJs.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Common_Save);
                lblfinalizeFunction.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Group_Tab_Finalize);
                cmdSavefinalizeJs.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Common_Save);
                lblSelectGroupField.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Group_Tab_Group_Notes);
                lblAddInitField.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Group_Tab_InitColumn_Note);
                cmdAddInitField.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Group_Tab_InitColumn);
                lblResult.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Group_Tab_Result);
                cmdQuery.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Group_LoadQuery);
                cmdRun.Text = SystemManager.mStringResource.GetText(MagicMongoDBTool.Module.StringResource.TextType.Common_OK);
            }
        }
Example #28
0
    public virtual void Save()
    {
        //修正持仓周期
        if (HasPosition && this.holdingPeriod < 1)
        {
            this.holdingPeriod = 1;                                         //当天入场的
        }
        if (this.holdingPeriod < 1)
        {
            return;
        }

        //提取日线,分线数据,还有大盘的数据
        string     symbol    = this.instrument.Symbol;
        Instrument indexInst = null;

        if (symbol.IndexOf("SHSE.") >= 0)
        {
            indexInst = InstrumentManager.Instruments["SHSE.000001"];
        }
        else if (symbol.IndexOf("SZSE.3") >= 0)
        {
            indexInst = InstrumentManager.Instruments["SZSE.399006"];
        }
        else
        {
            indexInst = InstrumentManager.Instruments["SZSE.399001"];
        }
        //指数的日线和分线
        BarSeries indexDaily = this.getDailySeries(indexInst);

        if (indexDaily.Count <= 0)
        {
            this.readLastNDailys(indexInst, this.indexDailyPeriod - 1);
            this.addTodayDaily(indexInst);
        }
        BarSeries indexMin5 = this.getMin5Series(indexInst);

        if (indexMin5.Count <= 0)
        {
            this.readLastNMin5s(indexInst, this.indexMin5Period);
        }
        //股票的日线和分线
        BarSeries stockDaily = this.getDailySeries(this.instrument);

        if (stockDaily.Count <= 0)
        {
            this.readLastNDailys(this.instrument, this.dailyPeriod - 1);
        }
        BarSeries stockMin5 = this.getMin5Series(this.instrument);

        if (stockMin5.Count <= 0)
        {
            this.readLastNMin5s(this.instrument, this.min5Period);
        }

        if (stockDaily.Count < 1)
        {
            return;                            //没有日线的不记录
        }
        //计算当天的奖赏
        double rewardForInside  = 0.0;     //在场内的奖赏
        double rewardForOutside = 0.0;     //在场外的奖赏

        if (this.holdingPeriod == 1)
        {
            rewardForInside = Math.Log(this.lastPrice / Position.EntryPrice);
        }
        else if (this.holdingPeriod > 1)
        {
            rewardForInside  = Math.Log(this.lastPrice / stockDaily.Last.Close);
            rewardForOutside = Math.Log(this.lastPriceWhenDeal / stockDaily.Last.Close);
        }
        //Console.WriteLine("symbol:{0} --- last price is {1} --- entry Price is {2},has {3} ticks",
        //	this.instrument.Symbol,this.lastPrice,Position.EntryPrice,this.Trades[this.instrument].Count);
        //当天的日线,交易决断前一刻的数据
        this.addTodayDaily(this.instrument);
        //正规化数据
        List <NormalizedBar> indexNormalizedDaily = this.NormalizeBars(indexDaily);
        List <NormalizedBar> indexNormalizedMin5  = this.NormalizeBars(indexMin5);
        List <NormalizedBar> stockNormalizedDaily = this.NormalizeBars(stockDaily);
        List <NormalizedBar> stockNormalizedMin5  = this.NormalizeBars(stockMin5);

        //写入数据库
        try{
            this.initDB();
            string curDateString = Clock.Now.Date.ToString("yyyy-MM-dd");
            //周期大于1且当天停盘没有交易的,不插入新记录,但要修改之前记录的下一个交易日期
            TradeArray trades = this.Trades[this.instrument];
            if (this.holdingPeriod > 1 &&
                (trades.Count <= 0 || trades.LastDateTime < Clock.Now.Date))
            {
                Console.WriteLine("证券{0}:今日没有交易", this.instrument.Symbol);
                BsonElement[] eleArray2 = new BsonElement[3];
                eleArray2[0] = new BsonElement("NextTradeDate", curDateString);
                eleArray2[1] = new BsonElement("Symbol", this.instrument.Symbol);
                eleArray2[2] = new BsonElement("Inside", 1);
                QueryDocument  query2 = new QueryDocument(eleArray2);
                UpdateDocument update = new UpdateDocument();
                update.Add(new BsonElement("$set", new QueryDocument(new BsonElement("NextTradeDate", (string)this.strategy.Global["NextTradeDate"]))));
                this.collection.Update(query2, update);
                return;
            }
            //如果当天已写入记录,先删除
            BsonElement[] eleArray = new BsonElement[2];
            eleArray[0] = new BsonElement("Date", curDateString);
            eleArray[1] = new BsonElement("Symbol", this.instrument.Symbol);
            QueryDocument query = new QueryDocument(eleArray);
            this.collection.Remove(query);
            //写入在场外的记录,如果是第一天,则是假设没有买入,如果是第二天及以后,则是假设卖出
            //此情况下,下一交易日为空
            BsonElement[] eleArray1 = new BsonElement[12];
            eleArray1[0] = new BsonElement("Date", curDateString);
            eleArray1[1] = new BsonElement("Symbol", this.instrument.Symbol);
            eleArray1[2] = new BsonElement("HoldingPeriod", this.holdingPeriod);
            eleArray1[3] = new BsonElement("Inside", 0);          //当前是否在场内
            eleArray1[4] = new BsonElement("IndexDaily", this.GetBsonArrayFromBars(indexNormalizedDaily));
            eleArray1[5] = new BsonElement("IndexMin5", this.GetBsonArrayFromBars(indexNormalizedMin5));
            eleArray1[6] = new BsonElement("StockDaily", this.GetBsonArrayFromBars(stockNormalizedDaily));
            eleArray1[7] = new BsonElement("StockMin5", this.GetBsonArrayFromBars(stockNormalizedMin5));
            eleArray1[8] = new BsonElement("Reward", rewardForOutside);
            eleArray1[9] = new BsonElement("NextTradeDate", "");
            BsonDocument insert = new BsonDocument(eleArray1);
            this.collection.Insert(insert);
            //写入在场内的记录,如果是第一天,则是买入,如果是第二天及以后,则是继续持有
            eleArray1    = new BsonElement[10];
            eleArray1[0] = new BsonElement("Date", curDateString);
            eleArray1[1] = new BsonElement("Symbol", this.instrument.Symbol);
            eleArray1[2] = new BsonElement("HoldingPeriod", this.holdingPeriod);
            eleArray1[3] = new BsonElement("Inside", 1);          //当前是否在场内
            eleArray1[4] = new BsonElement("IndexDaily", this.GetBsonArrayFromBars(indexNormalizedDaily));
            eleArray1[5] = new BsonElement("IndexMin5", this.GetBsonArrayFromBars(indexNormalizedMin5));
            eleArray1[6] = new BsonElement("StockDaily", this.GetBsonArrayFromBars(stockNormalizedDaily));
            eleArray1[7] = new BsonElement("StockMin5", this.GetBsonArrayFromBars(stockNormalizedMin5));
            eleArray1[8] = new BsonElement("Reward", rewardForInside);
            //已到了持仓周期限制,并且确实已卖出的,下一交易日为空
            if (this.holdingPeriod >= this.holdingPeriodLimit && (!HasPosition))
            {
                eleArray1[9] = new BsonElement("NextTradeDate", "");
            }
            else
            {
                eleArray1[9] = new BsonElement("NextTradeDate", (string)this.strategy.Global["NextTradeDate"]);
            }
            insert = new BsonDocument(eleArray1);
            this.collection.Insert(insert);
        }catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
 /// <summary>
 /// Initializes a new instance of the IndexOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public IndexOptionsDocument(
     BsonElement element
 )
     : base(element) {
 }
Example #30
0
 /// <summary>
 /// Initializes a new instance of the ScopeDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public ScopeDocument(BsonElement element)
     : base(element)
 {
 }
Example #31
0
        private TreeNode CreateTreeNode(BsonElement element)
        {
            TreeNode node = new TreeNode();

            if (element.Value.BsonType == BsonType.ObjectId)
            {
                node.BackColor = Color.WhiteSmoke;
                node.Text      = "ID: " + element.Value + "  - " + element.Value.BsonType;
                node.Tag       = element;
            }
            else if (element.Value.BsonType == BsonType.Array)
            {
                node.Text = element.Name + "  - Array";

                foreach (var children in element.Value.AsBsonArray)
                {
                    if (children.BsonType == BsonType.Document)
                    {
                        TreeNode objectNode = new TreeNode
                        {
                            Text      = element.Value.AsBsonArray.IndexOf(children).ToString() + ": Object",
                            BackColor = Color.Honeydew,
                            Tag       = children
                        };

                        foreach (var e in children.AsBsonDocument.Elements)
                        {
                            objectNode.Nodes.Add(CreateTreeNode(e));
                        }
                        node.Nodes.Add(objectNode);
                    }
                    else if (children.BsonType == BsonType.String || children.BsonType == BsonType.Int32)
                    {
                        TreeNode stringNode = new TreeNode
                        {
                            Text = element.Value.AsBsonArray.IndexOf(children).ToString() + ": " + children.RawValue.ToString() + "  - " + children.BsonType,
                            Tag  = children
                        };

                        node.Nodes.Add(stringNode);
                    }
                    else if (children.BsonType == BsonType.Array)
                    {
                        TreeNode arrayNode = new TreeNode
                        {
                            Text      = element.Value.AsBsonArray.IndexOf(children).ToString() + ": Array",
                            Tag       = children,
                            BackColor = Color.WhiteSmoke
                        };

                        foreach (BsonValue e in children.AsBsonArray.Values)
                        {
                            arrayNode.Nodes.Add(CreateTreeNode(e));
                        }

                        node.Nodes.Add(arrayNode);
                    }
                }

                node.Tag       = element;
                node.BackColor = Color.WhiteSmoke;
            }
            else if (element.Value.BsonType == BsonType.Document)
            {
                node.Text = element.Name + " - Object";

                foreach (BsonElement e in element.Value.AsBsonDocument.Elements)
                {
                    node.Nodes.Add(CreateTreeNode(e));
                }

                node.Tag       = element;
                node.BackColor = Color.Honeydew;
            }
            else
            {
                node.Text = element.Name + ": " + element.Value + "  - " + element.Value.BsonType;
                node.Tag  = element;
            }

            return(node);
        }
Example #32
0
 /// <summary>
 /// Initializes a new instance of the IndexOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public IndexOptionsDocument(BsonElement element)
     : base(element)
 {
 }
 /// <summary>
 /// Cut Element
 /// </summary>
 /// <param name="ElementPath"></param>
 public static void CopyElement(BsonElement El)
 {
     _ClipElement   = El;
     _IsElementClip = true;
 }
 /// <summary>
 /// Initializes a new instance of the MapReduceOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public MapReduceOptionsDocument(BsonElement element)
     : base(element)
 {
 }
 /// <summary>
 /// Initializes a new instance of the GeoNearOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public GeoNearOptionsDocument(
     BsonElement element
     )
     : base(element)
 {
 }
 /// <summary>
 /// Removes an element from this document.
 /// </summary>
 /// <param name="element">The element to remove.</param>
 public override void RemoveElement(BsonElement element)
 {
     throw new NotSupportedException("RawBsonDocument instances are immutable.");
 }
Example #37
0
        private void Zatwierdz(object sender, RoutedEventArgs e)
        {
            Window window           = this;
            var    areTextboxesNull = false;

            /* var kryminalista = new BsonDocument
             * {
             *  {"imie", new BsonString(imie.Text)},
             *  {"nazwisko", new BsonString(nazwisko.Text)},
             *  {"pseudonim", new BsonString(pseudonim.Text)},
             *  //{"data_urodzenia", new BsonDateTime(data_urodzenia)},
             *  {"miejsce_urodzenia", new BsonString(urodzenie.Text)},
             *  {"miejsce_zameldowania", new BsonString(zamieszkanie.Text)},
             *  //{"poszukiwany", new BsonBoolean(poszukiwany)}
             * }; */
            var kryminalista = new BsonDocument();

            foreach (TextBox textBox in FindVisualChildren <TextBox>(window))
            {
                if (String.IsNullOrEmpty(textBox.Text) || String.IsNullOrWhiteSpace(textBox.Text))
                {
                    areTextboxesNull = true;
                }
            }

            if (!String.IsNullOrWhiteSpace(imie.Text) || !String.IsNullOrEmpty(imie.Text))
            {
                BsonElement element = new BsonElement("imie", new BsonString(imie.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(nazwisko.Text) || !String.IsNullOrEmpty(nazwisko.Text))
            {
                BsonElement element = new BsonElement("nazwisko", new BsonString(nazwisko.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(pseudonim.Text) || !String.IsNullOrEmpty(pseudonim.Text))
            {
                BsonElement element = new BsonElement("pseudonim", new BsonString(pseudonim.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(urodzenie.Text) || !String.IsNullOrEmpty(urodzenie.Text))
            {
                BsonElement element = new BsonElement("miejsce_urodzenia", new BsonString(urodzenie.Text));
                kryminalista.Add(element);
            }
            if (!String.IsNullOrWhiteSpace(zamieszkanie.Text) || !String.IsNullOrEmpty(zamieszkanie.Text))
            {
                BsonElement element = new BsonElement("miejsce_zamieszkania", new BsonString(zamieszkanie.Text));
                kryminalista.Add(element);
            }

            if (isDateKnown == true)
            {
                BsonElement element = new BsonElement("data_urodzenia", new BsonDateTime((DateTime)data_urodzenia.SelectedDate));
                kryminalista.Add(element);
            }
            if ((bool)poszukiwany.IsChecked)
            {
                BsonElement element = new BsonElement("poszukiwany", new BsonBoolean(true));
                kryminalista.Add(element);
            }
            else
            {
                BsonElement element = new BsonElement("poszukiwany", new BsonBoolean(false));
                kryminalista.Add(element);
            }

            if (areTextboxesNull == false)
            {
                StartMongo.collectionPrzestepcy.InsertOne(kryminalista);

                var getData = new StringBuilder();
                getData.Append("Dodano nowego przestepce: " + imie.Text + ", ");
                getData.Append(nazwisko.Text + ", ");
                getData.Append("pseudonim: " + pseudonim.Text + " do bazy danych.");
                MessageBox.Show(getData.ToString(), "Rezultat");
                DialogResult = true;
            }
            else
            {
                MessageBoxResult isUserSure = MessageBox.Show("Czy na pewno chcesz dodać obiekt do bazy danych, bez wszystkich wypełnionych pól?", "Pytanie", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (isUserSure == MessageBoxResult.Yes && imie.Text != "" && nazwisko.Text != "")
                {
                    StartMongo.collectionPrzestepcy.InsertOne(kryminalista);

                    var getData = new StringBuilder();
                    getData.Append("Dodano nowego przestepce: " + imie.Text + ", ");
                    getData.Append(nazwisko.Text + ", ");
                    getData.Append("pseudonim: " + pseudonim.Text + " do bazy danych.");
                    MessageBox.Show(getData.ToString(), "Rezultat");
                    DialogResult = true;
                }
                else
                {
                    MessageBox.Show("Nie dodano nowego przestępcy do bazy danych. Podaj przynajmniej imię i nazwisko!", "Rezultat");
                    DialogResult = false;
                }
            }
        }
        /// <summary>
        /// Tries to get an element of this document.
        /// </summary>
        /// <param name="name">The name of the element.</param>
        /// <param name="element">The element.</param>
        /// <returns>
        /// True if an element with that name was found.
        /// </returns>
        public override bool TryGetElement(string name, out BsonElement element)
        {
            ThrowIfDisposed();
            using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
            using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
            {
                var context = BsonDeserializationContext.CreateRoot(bsonReader);
                
                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    if (bsonReader.ReadName() == name)
                    {
                        var value = DeserializeBsonValue(context);
                        element = new BsonElement(name, value);
                        return true;
                    }

                    bsonReader.SkipValue();
                }
                bsonReader.ReadEndDocument();

                element = default(BsonElement);
                return false;
            }
        }
Example #39
0
    static void Main(string[] args)
    {
        // TO DO: Add your code here

        int dailyPeriod        = 40; //日线周期
        int min5Period         = 10; //分线周期
        int indexDailyPeriod   = 10;
        int indexMin5Period    = 10;
        int holdingPeriodLimit = 5;      //持仓周期限制

        MongoClient   client   = new MongoClient("mongodb://localhost:27017");
        MongoServer   server   = client.GetServer();
        MongoDatabase database = server.GetDatabase("FinanceLast");
        //读取交易日期
        List <DateTime> dates = new List <DateTime>();
        MongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("TradeDates");

        foreach (BsonDocument record in collection.FindAll())
        {
            DateTime date = DateTime.Parse(record["Date"].ToString());
            dates.Add(date);
        }
        //
        collection = database.GetCollection <BsonDocument>("RandomTradeStatistics");
        SimulationDataProvider sdp           = (SimulationDataProvider)ProviderManager.MarketDataSimulator;
        List <string>          activeSymbols = new List <String>();

        activeSymbols.AddRange(sdp.GetSymbols("SHSE", 1));
        activeSymbols.AddRange(sdp.GetSymbols("SZSE", 1));

        DateTime beginDate = new DateTime(2017, 12, 11);
        DateTime endDate   = new DateTime(2017, 12, 31);
        DateTime curDate   = beginDate;
        Dictionary <string, RandomTradeRecord> randomTradeRecordDict = new Dictionary <string, RandomTradeRecord>();

        while (curDate <= endDate)
        {
            //sdp.Connect();
            string curDateString = curDate.ToString("yyyy-MM-dd");
            Console.WriteLine("当前日期是{0}", curDateString);
            int i = dates.IndexOf(curDate);
            if (i < 0)
            {
                Console.WriteLine("今天不是交易日。");
            }
            else
            {
                DateTime nextTradeDate = curDate.AddDays(1);
                if (i + 1 < dates.Count)
                {
                    nextTradeDate = dates[i + 1];
                }
                string nextTradeDateString = nextTradeDate.ToString("yyyy-MM-dd");

                DateTime dealTime  = curDate.Add(new TimeSpan(10, 20, 0));
                DateTime closeTime = curDate.Add(new TimeSpan(15, 3, 0));

                //处理已有的头寸
                QueryDocument query = new QueryDocument(new BsonElement("NextTradeDate", curDateString));
                foreach (BsonDocument record in collection.Find(query))
                {
                    RandomTradeRecord aTradeRecord = new RandomTradeRecord();
                    aTradeRecord._id           = record["_id"].ToString();
                    aTradeRecord.Symbol        = record["Symbol"].ToString();
                    aTradeRecord.HoldingPeriod = (int)record["HoldingPeriod"] + 1;
                    randomTradeRecordDict.Add(aTradeRecord.Symbol, aTradeRecord);
                }

                //获取最新价格,排序,然后随机选择入场

                Dictionary <String, Trade> lastTrades = sdp.GetLastTrades(activeSymbols.ToArray(), dealTime);

                List <string> symbols = new List <string>();
                foreach (KeyValuePair <String, Trade> kvp in lastTrades)
                {
                    if (kvp.Value == null)
                    {
                        continue;
                    }
                    GMTrade gmTrade = (GMTrade)kvp.Value;
                    if (gmTrade.Price <= 0)
                    {
                        continue;
                    }
                    if (gmTrade.Price == gmTrade.UpperLimit)
                    {
                        continue;
                    }
                    if (gmTrade.Price / gmTrade.LastClose - 1 < 0)
                    {
                        continue;
                    }
                    if (randomTradeRecordDict.ContainsKey(kvp.Key))
                    {
                        continue;
                    }
                    symbols.Add(kvp.Key);
                }
                int total = symbols.Count;

                Random randomer      = new Random((int)DateTime.Now.Ticks);
                int[]  randomNumbers = new int[100];
                for (int k = 0; k < 100; k++)
                {
                    randomNumbers[k] = randomer.Next(total);
                }
                foreach (int r in randomNumbers)
                {
                    string symbol = symbols[r];
                    if (!randomTradeRecordDict.ContainsKey(symbol))
                    {
                        RandomTradeRecord aTradeRecord = new RandomTradeRecord();
                        aTradeRecord.Symbol        = symbol;
                        aTradeRecord.HoldingPeriod = 1;
                        randomTradeRecordDict.Add(aTradeRecord.Symbol, aTradeRecord);
                    }
                }
                symbols.Clear();
                //如果当天已写入记录,先删除
                query = new QueryDocument(new BsonElement("Date", curDateString));
                collection.Remove(query);

                foreach (RandomTradeRecord aTradeRecord in randomTradeRecordDict.Values)
                {
                    //读取交易价格和收盘价格
                    Trade nextTrade = sdp.GetNextTrade(aTradeRecord.Symbol, dealTime);
                    if (nextTrade == null || nextTrade.DateTime.Date > curDate)
                    {
                        Console.WriteLine("Symbol {0} 在 {1} 时无法在下一笔成交", aTradeRecord.Symbol, dealTime);
                        aTradeRecord.PriceWhenDeal = 0.0;
                    }
                    else
                    {
                        aTradeRecord.PriceWhenDeal = nextTrade.Price;
                    }

                    Trade closeTrade = sdp.GetLastTrade(aTradeRecord.Symbol, closeTime);
                    if (closeTrade == null || closeTrade.DateTime.Date < curDate)
                    {
                        Console.WriteLine("Symbol {0} 今天没有收盘价", aTradeRecord.Symbol);
                        aTradeRecord.PriceWhenClose = 0.0;
                    }
                    else
                    {
                        aTradeRecord.PriceWhenClose = closeTrade.Price;
                    }

                    //没有交易价格和收盘价格则认为是停盘
                    if (aTradeRecord.PriceWhenDeal <= 0 && aTradeRecord.PriceWhenClose <= 0)
                    {
                        Console.WriteLine("证券{0}:今日没有交易", aTradeRecord.Symbol);
                        if (aTradeRecord.HoldingPeriod > 1)
                        {
                            query = new QueryDocument(new BsonElement("_id", aTradeRecord._id));
                            UpdateDocument update = new UpdateDocument();
                            update.Add(new BsonElement("$set", new BsonDocument(new BsonElement("NextTradeDate", nextTradeDateString))));
                            collection.Update(query, update);
                        }
                        continue;
                    }
                    //读取应指数的日线和5分线,证券的日线和分线
                    string indexSymbol = "";
                    if (aTradeRecord.Symbol.IndexOf("SHSE.") >= 0)
                    {
                        indexSymbol = "SHSE.000001";
                    }
                    else if (aTradeRecord.Symbol.IndexOf("SZSE.3") >= 0)
                    {
                        indexSymbol = "SZSE.399006";
                    }
                    else
                    {
                        indexSymbol = "SZSE.399001";
                    }

                    List <Daily> indexDailys = sdp.GetLastNDailys(indexSymbol, indexDailyPeriod, curDate);
                    List <Bar>   indexMin5s  = sdp.GetLastNBars(indexSymbol, 300, indexMin5Period, dealTime);


                    //***这里多加了当天日线,便于向前复权
                    List <Daily> stockDailys = sdp.GetLastNDailys(aTradeRecord.Symbol, dailyPeriod, curDate);
                    AdjustDailys(stockDailys);
                    List <Bar> stockMin5s = sdp.GetLastNBars(aTradeRecord.Symbol, 300, min5Period, dealTime);
                    //去掉当天日线后,获取昨日收盘价
                    int m = stockDailys.Count;
                    if (m < dailyPeriod)
                    {
                        continue;
                    }
                    if (stockDailys[m - 1].DateTime == curDate)
                    {
                        stockDailys.RemoveAt(m - 1);
                    }
                    else
                    {
                        stockDailys.RemoveAt(0);
                    }
                    double lastClose = stockDailys[stockDailys.Count - 1].Close;
                    //加入当天决断时刻的日线
                    Trade trade = lastTrades[aTradeRecord.Symbol];
                    if (trade == null)
                    {
                        continue;
                    }
                    Daily todayDaily = BuildDailyFormTrade((GMTrade)trade);
                    stockDailys.Add(todayDaily);

                    //正规化数据
                    List <NormalizedBar> indexNormalizedDailys = NormalizeBars(indexDailys);
                    List <NormalizedBar> indexNormalizedMin5s  = NormalizeBars(indexMin5s);
                    List <NormalizedBar> stockNormalizedDailys = NormalizeBars(stockDailys);
                    List <NormalizedBar> stockNormalizedMin5s  = NormalizeBars(stockMin5s);

                    //计算当天的奖赏
                    double rewardForInside  = 0.0;                 //在场内的奖赏
                    double rewardForOutside = 0.0;                 //在场外的奖赏

                    if (aTradeRecord.HoldingPeriod == 1)
                    {
                        rewardForInside = Math.Log(aTradeRecord.PriceWhenClose / aTradeRecord.PriceWhenDeal);
                    }
                    else if (aTradeRecord.HoldingPeriod > 1)
                    {
                        rewardForInside  = Math.Log(aTradeRecord.PriceWhenClose / lastClose);
                        rewardForOutside = Math.Log(aTradeRecord.PriceWhenDeal / lastClose);
                    }
                    //Console.WriteLine("{0},{1},{2}",aTradeRecord.PriceWhenDeal,aTradeRecord.PriceWhenClose,lastClosePrice);
                    //写入在场外的记录,如果是第一天,则是假设没有买入,如果是第二天及以后,则是假设卖出
                    //此情况下,下一交易日为空
                    BsonElement[] eleArray = new BsonElement[9];
                    eleArray[0] = new BsonElement("Date", curDateString);
                    eleArray[1] = new BsonElement("Symbol", aTradeRecord.Symbol);
                    eleArray[2] = new BsonElement("HoldingPeriod", aTradeRecord.HoldingPeriod);
                    eleArray[3] = new BsonElement("IndexDaily", GetBsonArrayFromBars(indexNormalizedDailys));
                    eleArray[4] = new BsonElement("IndexMin5", GetBsonArrayFromBars(indexNormalizedMin5s));
                    eleArray[5] = new BsonElement("StockDaily", GetBsonArrayFromBars(stockNormalizedDailys));
                    eleArray[6] = new BsonElement("StockMin5", GetBsonArrayFromBars(stockNormalizedMin5s));
                    BsonArray bsonArray = new BsonArray(2);
                    bsonArray.Add(rewardForInside);
                    bsonArray.Add(rewardForOutside);
                    eleArray[7] = new BsonElement("Reward", bsonArray);
                    //已到了持仓周期限制,卖出,下一交易日为空
                    if (aTradeRecord.HoldingPeriod >= holdingPeriodLimit)
                    {
                        eleArray[8] = new BsonElement("NextTradeDate", "");
                    }
                    else
                    {
                        eleArray[8] = new BsonElement("NextTradeDate", nextTradeDateString);
                    }
                    BsonDocument insert = new BsonDocument(eleArray);
                    collection.Insert(insert);
                    indexDailys.Clear();
                    indexMin5s.Clear();
                    stockDailys.Clear();
                    stockMin5s.Clear();
                    indexNormalizedDailys.Clear();
                    indexNormalizedMin5s.Clear();
                    stockNormalizedDailys.Clear();
                    stockNormalizedMin5s.Clear();
                }
                lastTrades.Clear();
                randomTradeRecordDict.Clear();
                Console.WriteLine("统计完毕。");
            }
            sdp.FlushAllSeries();
            //sdp.Disconnect();
            //为了防止内存溢出
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForFullGCApproach();
            GC.WaitForFullGCComplete();
            curDate = curDate.AddDays(1);
        }
    }
 /// <summary>
 /// Cut Element
 /// </summary>
 /// <param name="ElementPath"></param>
 public static void CutElement(String ElementPath, BsonElement El)
 {
     _ClipElement = El;
     _IsElementClip = true;
     DropElement(ElementPath, El);
 }
        private void treeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            e.DrawDefault = false;
            Rectangle rect = e.Bounds;

            if (rect.Height == 0)
            {
                ///在展开节点的时候会出现根节点绘制错误的问题
                return;
            }
            if ((e.State & TreeNodeStates.Selected) != 0)
            {
                if ((e.State & TreeNodeStates.Focused) != 0)
                {
                    e.Graphics.FillRectangle(SystemBrushes.Highlight, rect);
                }
                else
                {
                    e.Graphics.FillRectangle(SystemBrushes.Control, rect);
                }
            }
            else
            {
                e.Graphics.FillRectangle(Brushes.White, rect);
            }
            int IndentWidth = DatatreeView.Indent * e.Node.Level + 25;

            e.Graphics.DrawRectangle(SystemPens.Control, rect);
            Rectangle StringRect = new Rectangle(e.Bounds.X + IndentWidth, e.Bounds.Y, colName.Width - IndentWidth, e.Bounds.Height);

            String TreeNameString = e.Node.Text;

            if (TreeNameString.EndsWith(MongoDBHelper.Array_Mark))
            {
                //Array_Mark 在计算路径的时候使用,不过,在表示的时候,则不能表示
                TreeNameString = TreeNameString.Substring(0, TreeNameString.Length - MongoDBHelper.Array_Mark.Length);
            }
            if (TreeNameString.EndsWith(MongoDBHelper.Document_Mark))
            {
                //Document_Mark 在计算路径的时候使用,不过,在表示的时候,则不能表示
                TreeNameString = TreeNameString.Substring(0, TreeNameString.Length - MongoDBHelper.Document_Mark.Length);
            }
            //感谢cyrus的建议,选中节点的文字表示,底色变更
            if ((e.State & TreeNodeStates.Selected) != 0 && (e.State & TreeNodeStates.Focused) != 0)
            {
                e.Graphics.DrawString(TreeNameString, this.Font, new SolidBrush(SystemColors.HighlightText), StringRect);
            }
            else
            {
                e.Graphics.DrawString(TreeNameString, this.Font, new SolidBrush(Color.Black), StringRect);
            }

            BsonElement mElement = e.Node.Tag as BsonElement;
            BsonValue   mValue   = e.Node.Tag as BsonValue;

            //画框
            if (e.Node.GetNodeCount(true) > 0 || (mElement != null && (mElement.Value.IsBsonDocument || mElement.Value.IsBsonArray)))
            {
                //感谢Cyrus测试出来的问题:RenderWithVisualStyles应该加上去的。
                if (VisualStyleRenderer.IsSupported && Application.RenderWithVisualStyles)
                {
                    int LeftPoint = e.Bounds.X + IndentWidth - 20;
                    //感谢 Shadower http://home.cnblogs.com/u/14697/ 贡献的代码
                    var thisNode = e.Node;
                    var glyph    = thisNode.IsExpanded ? VisualStyleElement.TreeView.Glyph.Opened : VisualStyleElement.TreeView.Glyph.Closed;
                    var vsr      = new VisualStyleRenderer(glyph);
                    vsr.DrawBackground(e.Graphics, new Rectangle(LeftPoint, e.Bounds.Y + 4, 16, 16));
                }
                else
                {
                    int LeftPoint = e.Bounds.X + IndentWidth - 20;
                    e.Graphics.DrawRectangle(new Pen(Color.Black), new Rectangle(LeftPoint, e.Bounds.Y + 4, 12, 12));
                    Point LeftMid   = new Point(LeftPoint + 2, e.Bounds.Y + 10);
                    Point RightMid  = new Point(LeftPoint + 10, e.Bounds.Y + 10);
                    Point TopMid    = new Point(LeftPoint + 6, e.Bounds.Y + 6);
                    Point BottomMid = new Point(LeftPoint + 6, e.Bounds.Y + 14);
                    e.Graphics.DrawLine(new Pen(Color.Black), LeftMid, RightMid);
                    if (!e.Node.IsExpanded)
                    {
                        e.Graphics.DrawLine(new Pen(Color.Black), TopMid, BottomMid);
                    }
                }
            }

            for (int intColumn = 1; intColumn < 3; intColumn++)
            {
                rect.Offset(this.listView.Columns[intColumn - 1].Width, 0);
                rect.Width = this.listView.Columns[intColumn].Width;
                e.Graphics.DrawRectangle(SystemPens.Control, rect);
                if (mElement != null || mValue != null)
                {
                    string strColumnText = String.Empty;
                    if (intColumn == 1)
                    {
                        if (mElement != null)
                        {
                            if (!mElement.Value.IsBsonDocument && !mElement.Value.IsBsonArray)
                            {
                                strColumnText = mElement.Value.ToString();
                            }
                        }
                        else
                        {
                            if (mValue != null)
                            {
                                if (!mValue.IsBsonDocument && !mValue.IsBsonArray)
                                {
                                    if (e.Node.Level > 0)
                                    {
                                        //根节点有Value,可能是ID,用来取得选中节点的信息
                                        strColumnText = mValue.ToString();
                                    }
                                }
                                //Type这里已经有表示Type的标识了,这里就不重复显示了。
                                //else
                                //{
                                //if (mValue.IsBsonDocument) { strColumnText = MongoDBHelper.Document_Mark; }
                                //if (mValue.IsBsonArray) { strColumnText = MongoDBHelper.Array_Mark; }
                                //}
                            }
                        }
                    }
                    else
                    {
                        if (mElement != null)
                        {
                            strColumnText = mElement.Value.GetType().Name.Substring(4);
                        }
                        else
                        {
                            strColumnText = mValue.GetType().Name.Substring(4);
                        }
                    }

                    TextFormatFlags flags = TextFormatFlags.EndEllipsis;
                    switch (this.listView.Columns[intColumn].TextAlign)
                    {
                    case HorizontalAlignment.Center:
                        flags |= TextFormatFlags.HorizontalCenter;
                        break;

                    case HorizontalAlignment.Left:
                        flags |= TextFormatFlags.Left;
                        break;

                    case HorizontalAlignment.Right:
                        flags |= TextFormatFlags.Right;
                        break;

                    default:
                        break;
                    }

                    rect.Y++;
                    if ((e.State & TreeNodeStates.Selected) != 0 &&
                        (e.State & TreeNodeStates.Focused) != 0)
                    {
                        TextRenderer.DrawText(e.Graphics, strColumnText, e.Node.NodeFont, rect, SystemColors.HighlightText, flags);
                    }
                    else
                    {
                        TextRenderer.DrawText(e.Graphics, strColumnText, e.Node.NodeFont, rect, e.Node.ForeColor, e.Node.BackColor, flags);
                    }
                    rect.Y--;
                }
            }
        }
        /// <summary>
        ///     OK
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            //Project
            var project     = QueryFieldPicker.GetAggregation();
            var supressAggr = project[0];
            var projectAggr = project[1];

            if (supressAggr[0].AsBsonDocument.ElementCount > 0)
            {
                Aggregation.Add(supressAggr);
            }
            //TODO:需要优化,全项目的时候,不用输出
            if (projectAggr[0].AsBsonDocument.ElementCount > 0)
            {
                Aggregation.Add(projectAggr);
            }

            //match
            var match = ConditionPan.GetMatchDocument();

            if (match != null)
            {
                Aggregation.Add(match);
            }

            //Sort
            var sort = SortPanel.GetSortDocument();

            if (sort != null)
            {
                Aggregation.Add(sort);
            }

            //Group
            if (chkIdNull.Checked)
            {
                var id = new BsonDocument
                {
                    new BsonElement("_id", BsonNull.Value)
                };
                id.AddRange(FieldsElement.Value.AsBsonDocument.Elements);
                var group = new BsonDocument("$group", id);
                Aggregation.Add(group);
            }
            else
            {
                if (!string.IsNullOrEmpty(GroupIdElement.Name))
                {
                    var id = new BsonDocument
                    {
                        new BsonElement("_id", GroupIdElement.Value)
                    };
                    id.AddRange(FieldsElement.Value.AsBsonDocument.Elements);
                    var group = new BsonDocument("$group", id);
                    Aggregation.Add(group);
                }
            }


            //Skip
            if (chkSkip.Checked && int.Parse(txtSkip.Text) > 0)
            {
                Aggregation.Add(new BsonDocument("$skip", int.Parse(txtSkip.Text)));
            }
            //Limit
            if (chkLimit.Checked && int.Parse(txtLimit.Text) > 0)
            {
                Aggregation.Add(new BsonDocument("$limit", int.Parse(txtLimit.Text)));
            }
            //IndexStats
            if (chkIndexStats.Checked)
            {
                Aggregation.Add(new BsonDocument("$indexStats", new BsonDocument()));
            }
            //sortByCount
            if (chkSortByCount.Checked)
            {
                Aggregation.Add(new BsonDocument("$sortByCount", cmbSortByCount.Text));
            }
            //Sample
            if (chkSample.Checked)
            {
                var size = new BsonDocument("size", (int.Parse(txtSample.Text)));
                Aggregation.Add(new BsonDocument("$sample", size));
            }
            //unwind
            if (chkUnwind.Checked)
            {
                if (!chkPreserveNullAndEmptyArrays.Checked && string.IsNullOrEmpty(txtincludeArrayIndex.Text))
                {
                    Aggregation.Add(new BsonDocument("$unwind", cmbUnwind.Text));
                }
                else
                {
                    var UnwindDoc = new BsonDocument();
                    var field     = new BsonElement("path", cmbUnwind.Text);
                    UnwindDoc.Add(field);
                    if (chkPreserveNullAndEmptyArrays.Checked)
                    {
                        var preserveNullAndEmptyArrays = new BsonElement("preserveNullAndEmptyArrays", BsonBoolean.True);
                        UnwindDoc.Add(preserveNullAndEmptyArrays);
                    }
                    if (!string.IsNullOrEmpty(txtincludeArrayIndex.Text))
                    {
                        var includeArrayIndex = new BsonElement("includeArrayIndex", txtincludeArrayIndex.Text);
                        UnwindDoc.Add(includeArrayIndex);
                    }
                    Aggregation.Add(new BsonDocument("$unwind", UnwindDoc));
                }
            }
            Close();
        }
Example #43
0
 /// <summary>
 ///     Get Element or Bsonvalue
 /// </summary>
 public BsonElement GetElement()
 {
     var value = ElBsonValue.GetValue();
     var el = new BsonElement(txtElName.Text, value);
     return el;
 }
Example #44
0
        /// <summary>
        /// Serializes an object to a BsonWriter.
        /// </summary>
        /// <param name="bsonWriter">The BsonWriter.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <param name="value">The object.</param>
        /// <param name="options">The serialization options.</param>
        public override void Serialize(
            BsonWriter bsonWriter,
            Type nominalType,
            object value,
            IBsonSerializationOptions options)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // could get here with a BsonDocumentWrapper from BsonValueSerializer switch statement
            var wrapper = value as BsonDocumentWrapper;

            if (wrapper != null)
            {
                BsonDocumentWrapperSerializer.Instance.Serialize(bsonWriter, nominalType, value, null);
                return;
            }

            var rawBsonDocument = value as RawBsonDocument;

            if (rawBsonDocument != null)
            {
                RawBsonDocumentSerializer.Instance.Serialize(bsonWriter, nominalType, value, options);
                return;
            }

            var bsonDocument = (BsonDocument)value;
            var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions;

            if (documentSerializationOptions == null)
            {
                var message = string.Format(
                    "Serialize method of BsonDocument expected serialization options of type {0}, not {1}.",
                    BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)),
                    BsonUtils.GetFriendlyTypeName(options.GetType()));
                throw new BsonSerializationException(message);
            }

            bsonWriter.WriteStartDocument();
            BsonElement idElement = null;

            if (documentSerializationOptions.SerializeIdFirst && bsonDocument.TryGetElement("_id", out idElement))
            {
                bsonWriter.WriteName(idElement.Name);
                BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), idElement.Value, null);
            }

            foreach (var element in bsonDocument)
            {
                // if serializeIdFirst is false then idElement will be null and no elements will be skipped
                if (!object.ReferenceEquals(element, idElement))
                {
                    bsonWriter.WriteName(element.Name);
                    BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), element.Value, null);
                }
            }

            bsonWriter.WriteEndDocument();
        }
 /// <summary>
 /// Sets an element of the document (replacing the existing element at that position).
 /// </summary>
 /// <param name="index">The zero based index of the element to replace.</param>
 /// <param name="element">The new element.</param>
 /// <returns>
 /// The document.
 /// </returns>
 public override BsonDocument SetElement(int index, BsonElement element)
 {
     throw new NotSupportedException("RawBsonDocument instances are immutable.");
 }
 /// <summary>
 /// Initializes a new instance of the CollectionOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public CollectionOptionsDocument(BsonElement element)
     : base(element)
 {
 }
 /// <summary>
 /// Initializes a new instance of the GeoHaystackSearchOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public GeoHaystackSearchOptionsDocument(
     BsonElement element
 )
     : base(element)
 {
 }
 /// <summary>
 /// Initializes a new instance of the GeoHaystackSearchOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public GeoHaystackSearchOptionsDocument(BsonElement element)
     : base(element)
 {
 }
 /// <summary>
 /// Drop Element
 /// </summary>
 /// <param name="BaseDoc"></param>
 /// <param name="ElementPath"></param>
 public static void DropElement(String ElementPath, BsonElement El)
 {
     BsonDocument BaseDoc = SystemManager.GetCurrentDocument();
     BsonValue t = GetLastParentDocument(BaseDoc, ElementPath);
     if (t.IsBsonDocument)
     {
         t.AsBsonDocument.Remove(El.Name);
     }
     SystemManager.GetCurrentCollection().Save(BaseDoc);
 }
Example #50
0
        protected override bool TryConfigureClientOption(MongoClientSettings settings, BsonElement option)
        {
            switch (option.Name)
            {
            case "autoEncryptOpts":
                settings.AutoEncryptionOptions = ConfigureAutoEncryptionOptions(option.Value.AsBsonDocument);
                break;

            default:
                return(false);
            }

            return(true);
        }
 /// <summary>
 /// Initializes a new instance of the CommandDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public CommandDocument(BsonElement element)
     : base(element)
 {
 }
 /// <summary>
 /// Initializes a new instance of the MapReduceOptionsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public MapReduceOptionsDocument(BsonElement element)
     : base(element)
 {
 }
 /// <summary>
 /// Initializes a new instance of the ScopeDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public ScopeDocument(BsonElement element)
     : base(element)
 {
 }
Example #54
0
        /// <summary>
        /// Deletes many to many relation record
        /// </summary>
        /// <param name="relationId"></param>
        /// <param name="originId"></param>
        /// <param name="targetId"></param>
        public void DeleteManyToManyRecord(Guid relationId, Guid originId, Guid targetId)
        {
            var entityRepository = new MongoEntityRepository();
            var relation         = Read(relationId);
            var originEntity     = entityRepository.Read(relation.OriginEntityId);
            var originField      = originEntity.Fields.Single(x => x.Id == relation.OriginFieldId);
            var targetEntity     = entityRepository.Read(relation.TargetEntityId);
            var targetField      = targetEntity.Fields.Single(x => x.Id == relation.TargetFieldId);

            var originColletion = MongoStaticContext.Context.GetBsonCollection("rec_" + originEntity.Name);
            var originFieldName = originField.Name;

            if (originFieldName == "id")
            {
                originFieldName = "_id";
            }
            var          originRecords      = originColletion.Find(Query.EQ(originFieldName, originId)).ToList();
            var          originRecordsCount = originRecords.Count();
            BsonDocument originRecord       = null;

            if (originRecordsCount == 0)
            {
                throw new StorageException("There are no record with specified origin id.");
            }
            else if (originRecordsCount > 1)
            {
                throw new StorageException("There are more than 1 record with same origin id.");
            }
            else
            {
                originRecord = originRecords[0];
                var         targetsElementName = $"#{ relation.Name}_targets";
                BsonElement bsonElement        = null;
                if (originRecord.Elements.Any(x => x.Name == targetsElementName))
                {
                    bsonElement = originRecord.GetElement(targetsElementName);
                }
                //try { bsonElement = originRecord.GetElement(targetsElementName); } catch { }
                if (bsonElement != null)
                {
                    var targets = BsonTypeMapper.MapToDotNetValue(bsonElement.Value) as List <object>;
                    if (targets != null && targets.Contains(targetId))
                    {
                        targets.Remove(targetId);
                        if (targets.Count == 0)
                        {
                            targets = null;
                        }
                        originRecord[targetsElementName] = BsonTypeMapper.MapToBsonValue(targets);
                    }
                }
                else
                {
                    originRecord[targetsElementName] = BsonTypeMapper.MapToBsonValue(null);
                }
            }

            var targetColletion = MongoStaticContext.Context.GetBsonCollection("rec_" + targetEntity.Name);
            var targetFieldName = targetField.Name;

            if (targetFieldName == "id")
            {
                targetFieldName = "_id";
            }
            var          targetRecords      = targetColletion.Find(Query.EQ(targetFieldName, targetId)).ToList();
            var          targetRecordsCount = targetRecords.Count();
            BsonDocument targetRecord       = null;

            if (targetRecordsCount == 0)
            {
                throw new StorageException("There are no record with specified target id.");
            }
            else if (targetRecordsCount > 1)
            {
                throw new StorageException("There are more than 1 record with same target id.");
            }
            else
            {
                targetRecord = targetRecords[0];
                var         originsElementName = $"#{ relation.Name}_origins";
                BsonElement bsonElement        = null;
                if (targetRecord.Elements.Any(x => x.Name == originsElementName))
                {
                    bsonElement = targetRecord.GetElement(originsElementName);
                }
                //try { bsonElement = targetRecord.GetElement(originsElementName); } catch { }
                if (bsonElement != null)
                {
                    var origins = BsonTypeMapper.MapToDotNetValue(bsonElement.Value) as List <object>;
                    if (origins != null && origins.Contains(originId))
                    {
                        origins.Remove(originId);
                        if (origins.Count == 0)
                        {
                            origins = null;
                        }
                        targetRecord[originsElementName] = BsonTypeMapper.MapToBsonValue(origins);
                    }
                }
                else
                {
                    targetRecord[originsElementName] = BsonTypeMapper.MapToBsonValue(null);
                }
            }

            MongoTransaction transaction = null;

            if (!MongoStaticContext.Context.TransactionInProgress)
            {
                transaction = MongoStaticContext.Context.CreateTransaction();
            }

            try
            {
                originColletion.Save(originRecord);
                targetColletion.Save(targetRecord);

                if (transaction != null)
                {
                    transaction.Commit();
                }
            }
            catch
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
        }
 /// <summary>
 /// Initializes a new instance of the SortByDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public SortByDocument(
     BsonElement element
 )
     : base(element) {
 }
Example #56
0
        /// <summary>
        /// Generate the code and the code file.
        /// </summary>
        /// <param name="database">The existing instance of MongoDatabase.</param>
        /// <param name="directory">The directoty to store the code files.</param>
        /// <param name="globalNamespace">The code file namespace to use.</param>
        /// <returns>The number of code files created.</returns>
        public async Task <int> Generate(IMongoDatabase database, string directory, string globalNamespace)
        {
            // Make sure the page reference exists.
            if (database == null)
            {
                throw new ArgumentNullException("database");
            }
            if (String.IsNullOrEmpty(directory))
            {
                throw new ArgumentNullException("directory");
            }
            if (String.IsNullOrEmpty(globalNamespace))
            {
                throw new ArgumentNullException("globalNamespace");
            }

            int ret = 0;

            // Get the collections names within the database.
            IAsyncCursor <MongoDB.Bson.BsonDocument> collections = await database.ListCollectionsAsync();

            // Make sure collection exist.
            if (collections != null)
            {
                // Move to the list.
                bool moved = await collections.MoveNextAsync();

                // Get the list.
                IEnumerable <BsonDocument> documentList = collections.Current;

                // Make sure collection exist.
                if (documentList != null && documentList.Count() > 0)
                {
                    // For each collection in the database.
                    foreach (BsonDocument document in documentList)
                    {
                        try
                        {
                            // Get the collection name.
                            BsonElement nameElement    = document.GetElement("name");
                            BsonValue   nameValue      = nameElement.Value;
                            string      collectionName = nameValue.AsString;

                            // Get the document collection.
                            IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>(collectionName);
                            BsonDocument[] bsonDocuments = (await collection.Find(new BsonDocument()).Limit(1).ToListAsync()).ToArray();

                            // At least one document should be returned.
                            if (bsonDocuments != null && bsonDocuments.Length > 0)
                            {
                                // Create the bson model container.
                                Nequeo.Data.MongoDb.CodeDom.BsonModelContainer model = new Nequeo.Data.MongoDb.CodeDom.BsonModelContainer();
                                model.ClassName    = collectionName;
                                model.Namespace    = globalNamespace;
                                model.BsonDocument = bsonDocuments[0];
                                model.AssignProperties();

                                // Generate the code files.
                                CodeCompileUnit unit = Generate(model);
                                CreateCodeFile(directory.TrimEnd('\\') + "\\" + collectionName + ".cs", unit);

                                // Increment by one.
                                ret++;
                            }
                        }
                        catch { }
                    }
                }
            }

            // Return the number of code files created.
            return(ret);
        }
Example #57
0
        /// <summary>
        /// Constructs an output column and adds it to the provided output, using the column metadata from the provided BSON element.
        /// </summary>
        /// <param name="output"></param>
        /// <param name="bsonElement"></param>
        /// <returns></returns>
        private IDTSOutputColumn100 BuildOutputColumn(IDTSOutput100 output, BsonElement bsonElement)
        {
            IDTSOutputColumn100 outColumn = output.OutputColumnCollection.New();

            // Set the properties of the output column.
            outColumn.Name = bsonElement.Name;

            DataType dt = GetColumnDataType(bsonElement.Value);
            int length = 0;
            int codepage = 0;

            if (dt == DataType.DT_STR)
            {
                length = 256;
                codepage = 1252;
            }

            outColumn.SetDataTypeProperties(dt, length, 0, 0, codepage);

            // Setting these values enables the end-user to configure the error behavior on a per-column basis
            if (!output.IsErrorOut)
            {
                outColumn.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent;
                outColumn.TruncationRowDisposition = DTSRowDisposition.RD_FailComponent;
            }

            return outColumn;
        }
 /// <summary>
 /// Initializes a new instance of the FieldsDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public FieldsDocument(BsonElement element)
     : base(element)
 {
 }
        public void TestBsonElementEquals()
        {
            var a = new BsonElement("a", 1);
            var b = new BsonElement("a", 1);
            var c = new BsonElement("b", 1);
            var d = new BsonElement("b", 2);
            var n = (BsonElement)null;

            Assert.IsTrue(object.Equals(a, b));
            Assert.IsFalse(object.Equals(a, c));
            Assert.IsFalse(object.Equals(a, d));
            Assert.IsFalse(object.Equals(c, d));
            Assert.IsFalse(a.Equals(n));
            Assert.IsFalse(a.Equals(null));

            Assert.IsTrue(a == b);
            Assert.IsFalse(a == c);
            Assert.IsFalse(a == d);
            Assert.IsFalse(c == d);
            Assert.IsFalse(a == null);
            Assert.IsFalse(null == a);
            Assert.IsTrue(n == null);
            Assert.IsTrue(null == n);

            Assert.IsFalse(a != b);
            Assert.IsTrue(a != c);
            Assert.IsTrue(a != d);
            Assert.IsTrue(c != d);
            Assert.IsTrue(a != null);
            Assert.IsTrue(null != a);
            Assert.IsFalse(n != null);
            Assert.IsFalse(null != n);
        }
Example #60
0
 /// <summary>
 /// Initializes a new instance of the IndexKeysDocument class and adds one element.
 /// </summary>
 /// <param name="element">An element to add to the document.</param>
 public IndexKeysDocument(BsonElement element)
     : base(element)
 {
 }