Пример #1
0
        public IUserProfileWinner AggregationResultForWinsReport(Object listitem)
        {
            UserProfileWinner up = new UserProfileWinner();

            try
            {
                var doc = listitem as BsonDocument;
                up.FirstName = doc["FirstName"].AsString;
                up.LastName  = doc["LastName"].AsString;
                if (doc.Contains("RegisteredOn"))
                {
                    up.RegisteredOn = new DateTime(doc["RegisteredOn"].AsInt64).ToLocalTime();
                }
                up.Email = doc["Email"].AsString;

                if (doc.Contains("Prizes"))
                {
                    BsonValue ps    = doc["Prizes"].AsBsonDocument["_v"];
                    var       prize = BsonSerializer.Deserialize <UserPrize>(ps.ToJson());
                    up.Prizes.Add(prize);
                }
            }
            catch (Exception)
            {
            }

            return(up);
        }
Пример #2
0
        public List <GraphSeries> GetGraphAxis(string query, IEnumerable <Guid> applicationIds,
                                               DateTime dateStart, DateTime dateEnd)
        {
            BsonValue value = this.GetDatabase().Eval(EvalFlags.NoLock, new BsonJavaScript(query),
                                                      applicationIds, dateStart, dateEnd);

            return(BsonSerializer.Deserialize <List <GraphSeries> >(value.ToJson()));
        }
Пример #3
0
 public static Dictionary <Tkey, Tvalue> AsDictionary <Tkey, Tvalue>(this BsonValue bsonValue)
 {
     using (var reader = BsonReader.Create(bsonValue.ToJson()))
     {
         var dictionarySerializer = new DictionarySerializer <Tkey, Tvalue>();
         var result = dictionarySerializer.Deserialize(reader, typeof(Dictionary <Tkey, Tvalue>), new DictionarySerializationOptions());
         return((Dictionary <Tkey, Tvalue>)result);
     }
 }
Пример #4
0
        //Get document as JSON string. Return null if document isn't found
        public string GetDocument(string documentName)
        {
            BsonValue document = PlayerDocument.GetValue(documentName);

            if (document == null)
            {
                return(null);
            }
            return(document.ToJson());
        }
Пример #5
0
 public void LogFindOneByIdAs <T>(MongoCollection collection, BsonValue bsonKey)
 {
     if (_writeToFile == null)
     {
         return;
     }
     _writeToFile.Write("{0:yyyy-MM-dd HH:mm:ss.ffffff} ", DateTime.Now);
     _writeToFile.Write("FindOneByIdAs : {0} key ", collection.zGetFullName());
     _writeToFile.Write(bsonKey.ToJson());
     _writeToFile.Write(" type {0}", typeof(T));
     _writeToFile.WriteLine();
 }
Пример #6
0
        public static void FindOneById <TDocument>(string databaseName, string collectionName, object key, string server = null)
        {
            MongoCollection collection = MongoCommand.GetDatabase(server, databaseName).GetCollection(collectionName);
            BsonValue       bsonKey    = BsonValue.Create(key);

            Trace.Write("FindOneByIdAs : {0} key ", collection.zGetFullName());
            Trace.Write(bsonKey.ToJson());
            Trace.Write(" type {0}", typeof(TDocument));
            TDocument result = collection.zFindOneById <TDocument>(bsonKey);

            Trace.WriteLine(result.zToJson());
        }
        public static void EnsureFieldEquals(BsonDocument document, string name, BsonValue value)
        {
            if (!document.Contains(name))
            {
                throw new FormatException($"Missing field: \"{name}\".");
            }

            if (!document[name].Equals(value))
            {
                throw new FormatException($"Field \"{name}\" has an invalid value: {value.ToJson()}.");
            }
        }
Пример #8
0
        public async Task <Hero[]> GetHeroes()
        {
            IAsyncCursor <BsonDocument> task = await mainCollection.FindAsync(Builders <BsonDocument> .Filter.Empty);

            List <BsonDocument> docs = await task.ToListAsync();

            BsonDocument heroesDocument = docs.FirstOrDefault();
            BsonValue    heroesValue    = heroesDocument["heroes"];
            List <Hero>  heroesObj      = BsonSerializer.Deserialize <List <Hero> >(heroesValue.ToJson());

            Hero[] currHeroes = heroesObj.ToArray();
            this.heroes = currHeroes;
            return(currHeroes);
        }
Пример #9
0
        public List <GraphSeries> GetGraphAxis(string query, Guid applicationId,
                                               IEnumerable <string> versions, DateTime dateStart, DateTime dateEnd)
        {
            try
            {
                BsonValue value = this.GetDatabase().Eval(EvalFlags.NoLock, new BsonJavaScript(query),
                                                          applicationId, dateStart, dateEnd, versions);

                return(BsonSerializer.Deserialize <List <GraphSeries> >(value.ToJson()));
            }
            catch (Exception ex)
            {
                throw new DataAccessLayerException(ex);
            }
        }
Пример #10
0
        static Response Json(BsonValue bson)
        {
            var jsonString = bson.ToJson(typeof(object), new JsonWriterSettings {
                OutputMode   = JsonOutputMode.JavaScript,
                Indent       = true,
                NewLineChars = "\n",
                IndentChars  = " "
            });
            var jsonBytes = Encoding.UTF8.GetBytes(jsonString);

            return(new Response {
                Contents = s => s.Write(jsonBytes, 0, jsonBytes.Length),
                ContentType = "application/json"
            });
        }
 public static Dictionary <Tkey, Tvalue> AsDictionary <Tkey, Tvalue>(this BsonValue bsonValue)
 {
     using (BsonReader reader = new JsonReader(bsonValue.ToJson()))
     {
         var    dictionarySerializer = new DictionaryInterfaceImplementerSerializer <Dictionary <Tkey, Tvalue> >();
         object result = dictionarySerializer.Deserialize(
             BsonDeserializationContext.CreateRoot(reader, b => { }),
             new BsonDeserializationArgs()
         {
             NominalType = typeof(Dictionary <Tkey, Tvalue>)
         }
             );
         return((Dictionary <Tkey, Tvalue>)result);
     }
 }
Пример #12
0
        /// <summary>
        ///     eval Javascript
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdEval_Click(object sender, EventArgs e)
        {
            MongoDatabase mongoDB = SystemManager.GetCurrentDataBase();
            var           js      = new BsonJavaScript(ctlEval.Context);
            var           Params  = new List <Object>();

            if (txtParm.Text != String.Empty)
            {
                foreach (String parm in txtParm.Text.Split(",".ToCharArray()))
                {
                    if (parm.StartsWith("'") & parm.EndsWith("'"))
                    {
                        Params.Add(parm.Trim("'".ToCharArray()));
                    }
                    else
                    {
                        try
                        {
                            Boolean isNuberic = true;
                            for (int i = 0; i < parm.Length; i++)
                            {
                                if (!char.IsNumber(parm, i))
                                {
                                    isNuberic = false;
                                }
                            }
                            if (isNuberic)
                            {
                                Params.Add(Convert.ToInt16(parm));
                            }
                        }
                        catch (Exception ex)
                        {
                            SystemManager.ExceptionDeal(ex, "Exception", "Parameter Exception");
                        }
                    }
                }
            }
            try
            {
                BsonValue result = mongoDB.Eval(js, Params.ToArray());
                MyMessageBox.ShowMessage("Result", "Result", result.ToJson(SystemManager.JsonWriterSettings), true);
            }
            catch (Exception ex)
            {
                SystemManager.ExceptionDeal(ex, "Exception", "Result");
            }
        }
Пример #13
0
        public Tile Get(TileType tileType, string query, Guid applicationId, DateTime dateStart, DateTime dateEnd, DateTime dateStartCompare, DateTime dateEndCompare)
        {
            try
            {
                Type type = TileTypeMapping.Get(tileType);

                BsonValue value = this.GetDatabase().Eval(EvalFlags.NoLock, new BsonJavaScript(query),
                                                          applicationId, dateStart, dateEnd, dateStartCompare, dateEndCompare);

                return((Tile)BsonSerializer.Deserialize(value.ToJson(), type));
            }
            catch (Exception ex)
            {
                throw new DataAccessLayerException(ex);
            }
        }
Пример #14
0
 public void AssertValuesMatch(BsonValue actual, BsonValue expected)
 {
     try
     {
         AssertValuesMatch(actual, expected, isRoot: true, isRecursiveCall: false);
     }
     catch (XunitException exception)
     {
         var jsonWriterSettings = new JsonWriterSettings {
             Indent = true
         };
         var message =
             $"Expected value to be: {expected?.ToJson(jsonWriterSettings)}{Environment.NewLine}" +
             $"But found: {actual?.ToJson(jsonWriterSettings)}.";
         throw new AssertionException(message, exception);
     }
 }
Пример #15
0
 /// <summary>
 /// Converts a <see cref="BsonValue" /> into an <see cref="OriginalContext" />
 /// </summary>
 /// <param name="value">The <see cref="BsonValue" /> that is the source</param>
 /// <returns>An <see cref="OriginalContext" /> with the values from the <see cref="BsonValue" /></returns>
 public static OriginalContext ToOriginalContext(this BsonValue value)
 {
     try
     {
         var doc            = value.AsBsonDocument;
         var application    = doc[EventConstants.APPLICATION].AsGuid;
         var boundedContext = doc[EventConstants.BOUNDED_CONTEXT].AsGuid;
         var tenant         = doc[EventConstants.TENANT].AsGuid;
         var environment    = doc[EventConstants.ENVIRONMENT].AsString;
         var claims         = doc[EventConstants.CLAIMS].AsBsonArray.ToClaims();
         return(new OriginalContext(application, boundedContext, tenant, environment, claims));
     }
     catch (Exception)
     {
         Console.WriteLine(value.ToJson());
         throw;
     }
 }
Пример #16
0
        public object GetDetail(string query, Guid applicationId,
                                DateTime dateStart, DateTime dateEnd, string detailId)
        {
            try
            {
                BsonValue value = this.GetDatabase().Eval(EvalFlags.NoLock, new BsonJavaScript(query),
                                                          applicationId, dateStart, dateEnd, detailId);

                JsonWriterSettings settings = JsonWriterSettings.Defaults;
                settings.OutputMode = JsonOutputMode.Strict;

                return(new JavaScriptSerializer().DeserializeObject(value.ToJson(settings)));
            }
            catch (Exception ex)
            {
                throw new DataAccessLayerException(ex);
            }
        }
        private JArray GetJArray(BsonValue bsonValue)
        {
            string json = bsonValue.ToString();
            JArray ar;

            try
            {
                ar = JsonConvert.DeserializeObject <JArray>(RemoveISODateFunctions(json),
                                                            new IsoDateTimeConverter());
            }
            catch (Exception)
            {
                json = bsonValue.ToJson();
                ar   = JsonConvert.DeserializeObject <JArray>(RemoveISODateFunctions(json),
                                                              new IsoDateTimeConverter());
            }

            return(ar);
        }
Пример #18
0
 /// <summary>
 /// get object value from BsonValue
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 public static object GetValue(this BsonValue value, Type totype = null)
 {
     return(value.BsonType switch
     {
         BsonType.Array => value.AsBsonArray.ToArray().Select(x => x.GetValue()),
         BsonType.Boolean => value.AsBoolean,
         BsonType.DateTime => value.ToUniversalTime(),
         BsonType.Decimal128 => value.AsDecimal,
         BsonType.Document => totype is null?value.ToJson() : BsonSerializer.Deserialize(value.ToBsonDocument(), totype),
             BsonType.Double => value.AsDouble,
             BsonType.Int32 => value.AsInt32,
             BsonType.Int64 => value.AsInt64,
             BsonType.Null => null,
             BsonType.ObjectId => value.AsString,
             BsonType.String => value.AsString,
             BsonType.Timestamp => value.AsString,
             BsonType.Undefined => null,
             _ => null
     });
Пример #19
0
 /// <summary>
 ///     Method to invoke when the RunQuery command is executed.
 /// </summary>
 private void OnRunQueryExecute()
 {
     if (CollectionNames == null)
     {
         CollectionNames = Funani.GetCollectionNames();
     }
     try
     {
         QueryException = null; // reset
         var       bsonJS = new BsonJavaScript(Query);
         BsonValue result = Funani.Eval(new EvalArgs()
         {
             Code = bsonJS
         });
         QueryResults = result.ToJson().Split();
     }
     catch (Exception ex)
     {
         QueryException = ex;
     }
 }
Пример #20
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            try
            {
                MongoClient   client  = new MongoClient(this.txtConnectionString.Text);
                MongoDatabase datbase = client.GetServer().GetDatabase(this.txtDatabase.Text);

                BsonValue value = datbase.Eval
                                  (
                    new MongoDB.Bson.BsonJavaScript(this.txtJavaScript.Text),
                    new Guid(this.txtApplicationId.Text),
                    DateTime.Parse(this.txtStartDate.Text),
                    DateTime.Parse(this.txtEndDate.Text),
                    DateTime.Parse(this.txtStartDateCompare.Text),
                    DateTime.Parse(this.txtEndDateCompare.Text)
                                  );

                this.txtResult.Text = value.ToJson();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace, "Error");
            }
        }
        private void AssertCommandAspect(BsonDocument actualCommand, string name, BsonValue expectedValue)
        {
            var commandName = actualCommand.ElementCount == 0 ? "<unknown>" : actualCommand.GetElement(0).Name;

            if (expectedValue.IsBsonNull)
            {
                switch (name)
                {
                case "autocommit":
                case "readConcern":
                case "startTransaction":
                case "txnNumber":
                case "writeConcern":
                    if (actualCommand.Contains(name))
                    {
                        throw new AssertionFailedException($"Did not expect field '{name}' in command: {actualCommand.ToJson()}.");
                    }
                    return;
                }
            }

            if (!actualCommand.Contains(name))
            {
                // some missing fields are only missing because the C# driver omits default values
                switch (name)
                {
                case "new":
                    if (commandName == "findAndModify" && expectedValue == false)
                    {
                        return;
                    }
                    break;
                }

                throw new AssertionFailedException($"Expected field '{name}' in command: {actualCommand.ToJson()}.");
            }

            var actualValue = actualCommand[name];

            if (name == "updates")
            {
                AdaptExpectedUpdateModels(actualValue.AsBsonArray.Cast <BsonDocument>().ToList(), expectedValue.AsBsonArray.Cast <BsonDocument>().ToList());
            }

            var namesToUseOrderInsensitiveComparisonWith = new[] { "writeConcern" };
            var useOrderInsensitiveComparison            = namesToUseOrderInsensitiveComparisonWith.Contains(name);

            if (!(useOrderInsensitiveComparison ? BsonValueEquivalencyComparer.Compare(actualValue, expectedValue) : actualValue.Equals(expectedValue)))
            {
                throw new AssertionFailedException($"Expected field '{name}' in command '{commandName}' to be {expectedValue.ToJson()} but found {actualValue.ToJson()}.");
            }
        }
Пример #22
0
        public static PixelCoordinates toPixelCoordinate(this BsonValue value)
        {
            var coord = BsonSerializer.Deserialize <PixelCoordinates>(value.ToJson());

            return(coord);
        }
        private void AssertCommandAspect(BsonDocument actualCommand, string name, BsonValue expectedValue)
        {
            var commandName = actualCommand.ElementCount == 0 ? "<unknown>" : actualCommand.GetElement(0).Name;

            if (expectedValue.IsBsonNull)
            {
                switch (name)
                {
                case "allowDiskUse":
                case "autocommit":
                case "readConcern":
                case "recoveryToken":
                case "startTransaction":
                case "txnNumber":
                case "writeConcern":
                case "maxTimeMS":
                    if (actualCommand.Contains(name))
                    {
                        throw new AssertionFailedException($"Did not expect field '{name}' in command: {actualCommand.ToJson()}.");
                    }
                    return;
                }
            }

            if (!actualCommand.Contains(name))
            {
                // some missing fields are only missing because the C# driver omits default values
                switch (name)
                {
                case "new":
                    if (commandName == "findAndModify" && expectedValue == false)
                    {
                        return;
                    }
                    break;

                case "cursor" when commandName == "listCollections":
                    return;
                }

                throw new AssertionFailedException($"Expected field '{name}' in command: {actualCommand.ToJson()}.");
            }

            var actualValue = actualCommand[name];

            if (name == "updates")
            {
                AdaptExpectedUpdateModels(actualValue.AsBsonArray.Cast <BsonDocument>().ToList(), expectedValue.AsBsonArray.Cast <BsonDocument>().ToList());
            }

            var namesToUseOrderInsensitiveComparisonWith = new[] { "writeConcern", "maxTimeMS", "updates", "indexes", "getMore", "deletes" };
            var useOrderInsensitiveComparison            = namesToUseOrderInsensitiveComparisonWith.Contains(name);

            if (!(useOrderInsensitiveComparison ? BsonValueEquivalencyComparer.Compare(actualValue, expectedValue) : actualValue.Equals(expectedValue)))
            {
                switch (name)
                {
                case "out":
                    if (commandName == "mapReduce")
                    {
                        if (expectedValue is BsonString &&
                            actualValue.IsBsonDocument &&
                            actualValue.AsBsonDocument.Contains("replace") &&
                            actualValue["replace"] == expectedValue.AsString)
                        {
                            // allow short form for "out" to be equivalent to the long form
                            // Assumes that the driver is correctly generating the following
                            // fields: db, sharded, nonAtomic
                            return;
                        }
                    }
                    break;
                }

                throw new AssertionFailedException($"Expected field '{name}' in command '{commandName}' to be {expectedValue.ToJson()} but found {actualValue.ToJson()}.");
            }
        }
Пример #24
0
        static async Task MainAsync()
        {
            List <User> luser = new List <User>();

            var client = new MongoClient();

            IMongoDatabase db = client.GetDatabase("db");

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

            using (IAsyncCursor <BsonDocument> cursor = await collection.FindAsync(new BsonDocument()))
            {
                while (await cursor.MoveNextAsync())
                {
                    IEnumerable <BsonDocument> batch = cursor.Current;


                    foreach (var document in batch)
                    {
                        var user = new User
                        {
                            id        = (ObjectId)document[0],
                            name      = (string)document[1],
                            surname   = (string)document[2],
                            address   = (string)document[3],
                            phone     = (string)document[4],
                            CC_Info   = document[5],
                            purchases = document[6],
                        };

                        luser.Add(user);
                    }
                }
            }

            //EMBBEDED

            Console.WriteLine("VISU KLIENTU KREDITINIU INFORMACIJA ");

            foreach (var user in luser)
            {
                BsonValue dimVal = user.CC_Info;
                List <CC> d      = BsonSerializer.Deserialize <List <CC> >(dimVal.ToJson());
                Console.WriteLine("Klientas: " + user.name);
                foreach (var b in d)
                {
                    Console.WriteLine("Card Number: " + b.Card_Number);
                    Console.WriteLine("CVV: " + b.CVV);
                    Console.WriteLine("Expiration Date: " + b.Expires + '\n');
                }
            }

            //AGGREGATE

            Console.WriteLine("BENDRA VISU KLIENTU PIRKINIU SUMA ");
            double sum = 0;

            foreach (var user in luser)
            {
                BsonValue        dimVal = user.purchases;
                List <purchases> d      = BsonSerializer.Deserialize <List <purchases> >(dimVal.ToJson());
                foreach (var b in d)
                {
                    sum += b.total_price;
                }
            }

            Console.WriteLine("SUMA: " + sum);


            var    coll    = db.GetCollection <User>("Users");
            string map     = @"function(){
                for (var i = 0; i< this.purchases.length; i++){
                        var value = this.purchases[i].total_price;
                        emit(this.purchases[i].product, value);
                }
            }";
            string reduce  = @"function(product, total_price){
                   return Array.sum(total_price);
            }       
            ";
            var    options = new MapReduceOptions <User, BsonDocument>
            {
                OutputOptions = MapReduceOutputOptions.Inline
            };

            var results = coll.MapReduce(map, reduce, options).ToList();
            var rr      = results.ToJson();

            foreach (var r in results)
            {
                Console.WriteLine(r);
            }
        }
Пример #25
0
        /** Get an updated type of heroes array */
        public static async void GetCurrentHeroes()
        {
            try
            {
                /* Get all docs from collection */
                IMongoCollection <BsonDocument> mainCollection = DB.mainCollection;
                using (IAsyncCursor <BsonDocument> task = await mainCollection.FindAsync(Builders <BsonDocument> .Filter.Empty))
                {
                    List <BsonDocument> docs = await task.ToListAsync();

                    /* Retrieve heroes document and deserialize it into array */
                    BsonDocument heroesDocument = docs.FirstOrDefault();
                    BsonValue    heroesValue    = heroesDocument["heroes"];
                    List <Hero>  heroesObj      = BsonSerializer.Deserialize <List <Hero> >(heroesValue.ToJson());
                    Hero[]       currHeroes     = heroesObj.ToArray();
                    heroes     = currHeroes;
                    DB_Changed = false;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
        /// <summary>
        /// Set custom field data for one field (specified by owner HVO and field ID).
        /// </summary>
        /// <returns><c>true</c>, if custom field data was set, <c>false</c> otherwise (e.g., if value hadn't changed,
        /// or value was null, or field type was one not implemented in FDO, such as CellarPropertyType.Float).</returns>
        /// <param name="hvo">HVO of object whose field we're setting.</param>
        /// <param name="flid">Field ID of custom field to set.</param>
        /// <param name="value">Field's new value (as returned by GetCustomFieldData).</param>
        /// <param name="guidOrGuids">GUID or guids associated with new value (as returned by GetCustomFieldData).
        /// May be null or BsonNull.Value if no GUIDs associated with this value.</param>
        public bool SetCustomFieldData(int hvo, int flid, BsonValue value, BsonValue guidOrGuids)
        {
            if ((value == null) || (value == BsonNull.Value) ||
                ((value.BsonType == BsonType.Array) && (value.AsBsonArray.Count == 0)))
                return false;
            List<Guid> fieldGuids = new List<Guid>();
            if (guidOrGuids == null || guidOrGuids == BsonNull.Value)
            {
                fieldGuids.Add(Guid.Empty);
            }
            else
            {
                if (guidOrGuids is BsonArray)
                    fieldGuids.AddRange(guidOrGuids.AsBsonArray.Select(bsonValue => ParseGuidOrDefault(bsonValue.AsString)));
                else
                    fieldGuids.Add(ParseGuidOrDefault(guidOrGuids.AsString));
            }
            ISilDataAccessManaged data = (ISilDataAccessManaged)cache.DomainDataByFlid;
            CellarPropertyType fieldType = (CellarPropertyType)fdoMetaData.GetFieldType(flid);
            string fieldName = fdoMetaData.GetFieldNameOrNull(flid);
            //			logger.Debug("Custom field named {0} has type {1}", fieldName, fieldType.ToString());
            if (fieldName == null)
                return false;

            // Valid field types in FDO are GenDate, Integer, String, OwningAtomic, ReferenceAtomic, and ReferenceCollection, so that's all we implement.
            switch (fieldType)
            {
            case CellarPropertyType.GenDate:
                {
                    var valueAsMultiText = BsonSerializer.Deserialize<LfMultiText>(value.AsBsonDocument);
                    string valueAsString = valueAsMultiText.BestString(new string[] { MagicStrings.LanguageCodeForGenDateFields });
                    if (string.IsNullOrEmpty(valueAsString))
                        return false;
                    GenDate valueAsGenDate;
                    if (GenDate.TryParse(valueAsString, out valueAsGenDate))
                    {
                        GenDate oldValue = data.get_GenDateProp(hvo, flid);
                        if (oldValue == valueAsGenDate)
                            return false;
                        else
                        {
                            data.SetGenDate(hvo, flid, valueAsGenDate);
                            return true;
                        }
                    }
                    return false;
                }

            case CellarPropertyType.Integer:
                {
                    var valueAsMultiText = BsonSerializer.Deserialize<LfMultiText>(value.AsBsonDocument);
                    string valueAsString = valueAsMultiText.BestString(new string[] { MagicStrings.LanguageCodeForIntFields });
                    if (string.IsNullOrEmpty(valueAsString))
                        return false;
                    int valueAsInt;
                    if (int.TryParse(valueAsString, out valueAsInt))
                    {
                        int oldValue = data.get_IntProp(hvo, flid);
                        if (oldValue == valueAsInt)
                            return false;
                        else
                        {
                            data.SetInt(hvo, flid, valueAsInt);
                            return true;
                        }
                    }
                    return false;
                }

            case CellarPropertyType.OwningAtomic:
                {
                    // Custom field is a MultiparagraphText, which is an IStText object in FDO
                    IStTextRepository textRepo = cache.ServiceLocator.GetInstance<IStTextRepository>();
                    Guid fieldGuid = fieldGuids.FirstOrDefault();
                    IStText text;
                    if (!textRepo.TryGetObject(fieldGuid, out text))
                    {
                        int currentFieldContentsHvo = data.get_ObjectProp(hvo, flid);
                        if (currentFieldContentsHvo != FdoCache.kNullHvo)
                            text = (IStText)cache.GetAtomicPropObject(currentFieldContentsHvo);
                        else
                        {
                            // NOTE: I don't like the "magic" -2 number below, but FDO doesn't seem to have an enum for this. 2015-11 RM
                            int newStTextHvo = data.MakeNewObject(cache.GetDestinationClass(flid), hvo, flid, -2);
                            text = (IStText)cache.GetAtomicPropObject(newStTextHvo);
                        }
                    }
                    // Shortcut: if text contents haven't changed, we don't want to change anything at all
                    BsonValue currentFdoTextContents = ConvertUtilities.GetCustomStTextValues(text, flid,
                        cache.ServiceLocator.WritingSystemManager, cache.MetaDataCacheAccessor, cache.DefaultUserWs);
                    if ((currentFdoTextContents == BsonNull.Value || currentFdoTextContents == null) &&
                        (value == BsonNull.Value || value == null))
                        return false;
                    if (currentFdoTextContents != null && currentFdoTextContents.Equals(value))
                    {
                        // No changes needed.
                        return false;
                    }
                    // BsonDocument passed in contains "paragraphs". ParseCustomStTextValuesFromBson wants only a "value" element
                    // inside the doc, so we'll need to construct a new doc for the StTextValues.
                    BsonDocument doc = value.AsBsonDocument;
                    LfMultiParagraph multiPara = BsonSerializer.Deserialize<LfMultiParagraph>(doc);
                    // Now we have another way to check for "old value and new value were the same": if the FDO multiparagraph was empty,
                    // GetCustomStTextValues will have returned null -- so if this multiPara has no paragraphs, that's also an unchanged situation
                    if ((multiPara.Paragraphs == null || multiPara.Paragraphs.Count <= 0) &&
                        (currentFdoTextContents == BsonNull.Value || currentFdoTextContents == null))
                        return false;
                    int wsId;
                    if (multiPara.InputSystem == null)
                        wsId = cache.MetaDataCacheAccessor.GetFieldWs(flid);
                    else
                        wsId = cache.WritingSystemFactory.GetWsFromStr(multiPara.InputSystem);
                    ConvertUtilities.SetCustomStTextValues(text, multiPara.Paragraphs, wsId);

                    return true;
                }

            case CellarPropertyType.ReferenceAtomic:
                Console.WriteLine("ReferenceAtomic field named {0} with value {1}", fieldName, value.ToJson());
                int log_fieldWs = fdoMetaData.GetFieldWs(flid);
                string log_fieldWsStr = servLoc.WritingSystemManager.GetStrFromWs(log_fieldWs);
                Console.WriteLine("Writing system for this field has ID {0} and name ({1})", log_fieldWs, log_fieldWsStr);
                if (fieldGuids.First() != Guid.Empty)
                {
                    int referencedHvo = data.get_ObjFromGuid(fieldGuids.First());
                    int oldHvo = data.get_ObjectProp(hvo, flid);
                    if (referencedHvo == oldHvo)
                        return false;
                    else
                    {
                        data.SetObjProp(hvo, flid, referencedHvo);
                        // TODO: What if the value of the referenced object has changed in LanguageForge? (E.g., change that possibility's text from "foo" to "bar")
                        // Need to implement that scenario.
                        return true;
                    }
                }
                else
                {
                    // It's a reference to an ICmPossibility instance: create a new entry in appropriate PossibilityList
                    LfStringField valueAsLfStringField = BsonSerializer.Deserialize<LfStringField>(value.AsBsonDocument);
                    string nameHierarchy = valueAsLfStringField.Value;
                    if (nameHierarchy == null)
                        return false;
                    int fieldWs = fdoMetaData.GetFieldWs(flid);
                    // Oddly, this can return 0 for some custom fields. TODO: Find out why: that seems like it would be an error.
                    if (fieldWs == 0)
                        fieldWs = cache.DefaultUserWs;
                    ICmPossibilityList parentList = GetParentListForField(flid);
                    ICmPossibility newPoss = parentList.FindOrCreatePossibility(nameHierarchy, fieldWs);

                    int oldHvo = data.get_ObjectProp(hvo, flid);
                    if (newPoss.Hvo == oldHvo)
                        return false;
                    else
                    {
                        data.SetObjProp(hvo, flid, newPoss.Hvo);
                        return true;
                    }
                }

            case CellarPropertyType.ReferenceCollection:
            case CellarPropertyType.ReferenceSequence:
                {
                    if (value == null || value == BsonNull.Value)
                    {
                        // FDO writes multi-references if their list is empty, but not if it's null
                        int oldValue = data.get_ObjectProp(hvo, flid);
                        if (oldValue == FdoCache.kNullHvo)
                            return false;
                        else
                        {
                            data.SetObjProp(hvo, flid, FdoCache.kNullHvo);
                            return true;
                        }
                    }
                    int fieldWs = fdoMetaData.GetFieldWs(flid);
                    // TODO: Investigate why this is sometimes coming back as 0 instead of as a real writing system ID
                    if (fieldWs == 0)
                        fieldWs = cache.DefaultUserWs;
                    ICmPossibilityList parentList = GetParentListForField(flid);

                    LfStringArrayField valueAsStringArray = BsonSerializer.Deserialize<LfStringArrayField>(value.AsBsonDocument);

                    // Step 1: Check if any of the fieldGuids is Guid.Empty, which would indicate a brand-new object that wasn't in FDO
                    List<string> fieldData = valueAsStringArray.Values;
                    Console.WriteLine("Reference collection had values {0}", String.Join(", ", fieldData));
                    Console.WriteLine("Reference collection had GUIDs {0}", guidOrGuids.ToJson());
                    IEnumerable<ICmPossibility> fieldObjs = fieldGuids.Zip<Guid, string, ICmPossibility>(fieldData, (thisGuid, thisData) =>
                        {
                            ICmPossibility newPoss;
                            if (thisGuid == default(Guid)) {
                                newPoss = ((ICmPossibilityList)parentList).FindOrCreatePossibility(thisData, fieldWs);
                                return newPoss;
                            }
                            else {
                                newPoss = servLoc.GetObject(thisGuid) as ICmPossibility;
                                return newPoss;
                            }
                        });

                    // Step 2: Remove any objects from the "old" list that weren't in the "new" list
                    // We have to look them up by HVO because that's the only public API available in FDO
                    // Following logic inspired by XmlImportData.CopyCustomFieldData in FieldWorks source
                    int[] oldHvosArray = data.VecProp(hvo, flid);
                    int[] newHvosArray = fieldObjs.Select(poss => poss.Hvo).ToArray();
                    HashSet<int> newHvos = new HashSet<int>(newHvosArray);
                    HashSet<int> combinedHvos = new HashSet<int>();
                    // Loop backwards so deleting items won't mess up indices of subsequent deletions
                    for (int idx = oldHvosArray.Length - 1; idx >= 0; idx--)
                    {
                        int oldHvo = oldHvosArray[idx];
                        if (newHvos.Contains(oldHvo))
                            combinedHvos.Add(oldHvo);
                        else
                            data.Replace(hvo, flid, idx, idx + 1, null, 0); // Important to pass *both* null *and* 0 here to remove items
                    }

                    // Step 3: Add any objects from the "new" list that weren't in the "old" list
                    foreach (int newHvo in newHvosArray)
                    {
                        if (combinedHvos.Contains(newHvo))
                            continue;
                        // This item was added in the new list
                        data.Replace(hvo, flid, combinedHvos.Count, combinedHvos.Count, new int[] { newHvo }, 1);
                        combinedHvos.Add(newHvo);
                    }
                    // Now (and not before), replace an empty list with null in the custom field value
                    if (data.VecProp(hvo, flid).Length == 0)
                    {
                        if (data.get_ObjectProp(hvo, flid) == FdoCache.kNullHvo)
                            return false;
                        else
                        {
                            data.SetObjProp(hvo, flid, FdoCache.kNullHvo);
                            return true;
                        }
                    }
                    return true;
                }

            case CellarPropertyType.String:
                {
                    var valueAsMultiText = BsonSerializer.Deserialize<LfMultiText>(value.AsBsonDocument);
                    int wsIdForField = cache.MetaDataCacheAccessor.GetFieldWs(flid);
                    string wsStrForField = cache.WritingSystemFactory.GetStrFromWs(wsIdForField);
                    KeyValuePair<string, string> kv = valueAsMultiText.BestStringAndWs(new string[] { wsStrForField });
                    string foundWs = kv.Key ?? string.Empty;
                    string foundData = kv.Value ?? string.Empty;
                    int foundWsId = cache.WritingSystemFactory.GetWsFromStr(foundWs);
                    if (foundWsId == 0)
                        return false; // Skip any unidentified writing systems
                    ITsString oldValue = data.get_StringProp(hvo, flid);
                    ITsString newValue = ConvertMongoToFdoTsStrings.SpanStrToTsString(foundData, foundWsId, cache.WritingSystemFactory);
                    if (oldValue != null && TsStringUtils.GetDiffsInTsStrings(oldValue, newValue) == null) // GetDiffsInTsStrings() returns null when there are no changes
                        return false;
                    else
                    {
                        data.SetString(hvo, flid, newValue);
                        return true;
                    }
                }

            default:
                return false;
                // TODO: Maybe issue a proper warning (or error) log message for "field type not recognized"?
            }
        }
Пример #27
0
 public static string ToIndentedJson(this BsonValue value) => value.ToJson(JsonWriterSettings);
Пример #28
0
        public IUserProfileWinner AggregationResultAsUserProfileWinner(Object listitem)
        {
            UserProfileWinner up = new UserProfileWinner();

            try
            {
                var doc = listitem as BsonDocument;
                up.FirstName = doc["FirstName"].AsString;
                up.LastName  = doc["LastName"].AsString;
                if (doc.Contains("RegisteredOn"))
                {
                    up.RegisteredOn = new DateTime(doc["RegisteredOn"].AsInt64).ToLocalTime();
                }
                up.Email = doc["Email"].AsString;
                if (doc.Contains("PrizeCount"))
                {
                    up.User.PrizeCount = doc["PrizeCount"].ToDouble();
                }
                if (doc.Contains("Prizes"))
                {
                    BsonValue        ps    = doc["Prizes"];
                    List <UserPrize> plist = BsonSerializer.Deserialize <List <UserPrize> >(ps.ToJson());

                    foreach (var p in plist)
                    {
                        up.Prizes.Add(p);
                    }

                    up.User.PrizeCount = up.Prizes.Count;
                }
            }
            catch (Exception)
            {
            }

            return(up);
        }
Пример #29
0
 protected virtual void AssertResult()
 {
     throw new FormatException($"{GetType().Name} doesn't know how to assert expected result: {_expectedResult.ToJson()}.");
 }