Esempio n. 1
0
        public void Fetch_TimeUuid_List()
        {
            _session.Execute("CREATE TABLE tbl_timeuuid_list (id int primary key, my_list list<timeuuid>)");
            var map = new Map <PocoWithCollections <TimeUuid> >()
                      .Column(p => p.Id)
                      .Column(p => p.List, c => c.WithName("my_list"))
                      .PartitionKey(p => p.Id)
                      .TableName("tbl_timeuuid_list")
                      .ExplicitColumns();
            var mapper   = new Mapper(_session, new MappingConfiguration().Define(map));
            var inserted = new PocoWithCollections <TimeUuid>
            {
                Id   = 1,
                List = new List <TimeUuid> {
                    TimeUuid.NewId(), TimeUuid.NewId()
                }
            };

            mapper.Insert(inserted);
            var retrieved     = mapper.Fetch <PocoWithCollections <TimeUuid> >("WHERE id = ?", inserted.Id).First();
            var listRetrieved = retrieved.List.OrderBy(x => x);
            var listInserted  = inserted.List.OrderBy(x => x);

            CollectionAssert.AreEqual(listInserted, listRetrieved);
        }
Esempio n. 2
0
        public void DeserializationTests()
        {
            var          rowIdArray = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
            var          ticksArray = new[] { 35465410426481591, 63546500026481590, 70011723893288L, 1723893288L };
            const string format     = "yyyy-MM-dd HH:mm:ss.SSS";

            for (var i = 0; i < rowIdArray.Length; i++)
            {
                var rowId    = rowIdArray[i];
                var ticks    = ticksArray[i];
                var timeUuid = TimeUuid.NewId(new DateTimeOffset(ticks, TimeSpan.Zero));
                Session.Execute(_insertPrepared.Bind(rowId, timeUuid));
                var row = Session.Execute(_selectPrepared.Bind(rowId)).FirstOrDefault();
                Assert.NotNull(row);
                var resultTimeUuidValue = row.GetValue <TimeUuid>("timeuuid_sample");
                Assert.AreEqual(timeUuid, resultTimeUuidValue);
                Assert.AreEqual(timeUuid.GetDate(), resultTimeUuidValue.GetDate());
                if (row.GetColumn("timeuuid_date_value") != null)
                {
                    // the timestamp retrieved by the cql function has lower precision than timeuuid
                    const long precision = 10000L;
                    Assert.AreEqual(
                        timeUuid.GetDate().Ticks / precision,
                        row.GetValue <DateTimeOffset>("timeuuid_date_value").Ticks / precision);
                }
                //Still defaults to Guid
                var boxedValue = row.GetValue <object>("timeuuid_sample");
                Assert.IsInstanceOf <Guid>(boxedValue);
                Assert.AreEqual(resultTimeUuidValue, (TimeUuid)(Guid)boxedValue);
                //The precision is lost, up to milliseconds is fine
                Assert.AreEqual(timeUuid.GetDate().ToString(format), row.GetValue <DateTimeOffset>(2).ToString(format));
            }
        }
Esempio n. 3
0
        public void UpdatePost(ISession session)
        {
            TimeUuid updatedAt = TimeUuid.NewId(DateTimeOffset.Now);


            Console.Write("Enter post_id : ");
            string strPostId = Console.ReadLine();
            Guid   postId    = new Guid(strPostId);


            Console.Write("Edit post : ");
            string content = Console.ReadLine();

            TimeUuid updatedAtPrev = new TimeUuid();
            var      getLastUpdate = session.Prepare("Select updated_at from posts where post_id = ? ");
            var      ex            = session.Execute(getLastUpdate.Bind(postId));

            foreach (var lastUpdateAt in ex)
            {
                updatedAtPrev = lastUpdateAt.GetValue <TimeUuid>("updated_at");
            }


            var updatedPost = session.Prepare(
                "Update posts set content = ?, updated_at=?  where post_id = ?");

            session.Execute(updatedPost.Bind(content, updatedAt, postId));


            _userStream.SyncUserStream(session, postId, updatedAtPrev);
        }
Esempio n. 4
0
        public void EncodeDecodeSingleValuesFactoryTest()
        {
            var initialValues = new object[]
            {
                new object[] { "just utf8 text olé!", ColumnTypeCode.Text },
                new object[] { "just ascii text", ColumnTypeCode.Ascii },
                new object[] { 123, ColumnTypeCode.Int },
                new object[] { Int64.MinValue + 100, ColumnTypeCode.Bigint },
                new object[] { 44F, ColumnTypeCode.Float },
                new object[] { -320D, ColumnTypeCode.Double },
                new object[] { 99.89770M, ColumnTypeCode.Decimal },
                new object[] { Decimal.MaxValue, ColumnTypeCode.Decimal },
                new object[] { new DateTime(2010, 4, 29), ColumnTypeCode.Timestamp },
                new object[] { new DateTimeOffset(new DateTime(2010, 4, 29)), ColumnTypeCode.Timestamp },
                new object[] { new IPAddress(new byte[] { 10, 0, 5, 5 }), ColumnTypeCode.Inet },
                new object[] { Guid.NewGuid(), ColumnTypeCode.Uuid },
                new object[] { Guid.NewGuid(), ColumnTypeCode.Timeuuid },
                new object[] { TimeUuid.NewId(), ColumnTypeCode.Timeuuid },
                new object[] { false, ColumnTypeCode.Boolean },
                new object[] { new byte [] { 1, 2 }, ColumnTypeCode.Blob }
            };

            foreach (var version in _protocolVersions)
            {
                foreach (object[] value in initialValues)
                {
                    byte[] encoded = TypeCodec.Encode(version, value[0]);
                    Assert.AreEqual(value[0], TypeCodec.Decode(version, encoded, (ColumnTypeCode)value[1], null, value[0].GetType()));
                }
            }
        }
Esempio n. 5
0
        public void CreatePost(ISession session, string Text, Guid UserID, List <string> Followers)
        {
            Guid postID = Guid.NewGuid();

            TimeUuid UpdTime = TimeUuid.NewId(DateTimeOffset.Now);



            var insertPost = session.Prepare(
                "INSERT INTO Post (PostID, UserID, Text, UpdTime) VALUES(?,?,?, ?)");

            session.Execute(insertPost.Bind(postID, UserID, Text, UpdTime));



            var insertPostFollowers = session.Prepare(
                "INSERT INTO post_followers (PostID, followers) VALUES(?,?)");

            session.Execute(insertPostFollowers.Bind(postID, Followers));

            PostC post = new PostC
            {
                PostID  = postID,
                UserID  = UserID,
                Text    = Text,
                UpdTime = UpdTime
            };

            _stream.SynchronizeStream(session, post);
        }
Esempio n. 6
0
        public void AddComment(ISession session)
        {
            TimeUuid comment_id = TimeUuid.NewId(DateTimeOffset.Now);
            Guid     userId     = Guid.NewGuid();

            Console.Write("Enter post_id : ");
            string strPostId = Console.ReadLine();
            Guid   postId    = new Guid(strPostId);

            Console.Write("Enter post : ");
            string comment = Console.ReadLine();

            var addComment = session.Prepare(
                "INSERT INTO comments (post_id, comment_id , comment, user_id) VALUES(?,?,?, ?)");

            session.Execute(addComment.Bind(postId, comment_id, comment, userId));

            var updatedPost = session.Prepare(
                "Update posts set updated_at=?  where post_id = ?");

            session.Execute(updatedPost.Bind(comment_id, postId));

            TimeUuid updatedAtPrev = new TimeUuid();
            var      getLastUpdate = session.Prepare("Select updated_at from posts where post_id = ? ");
            var      ex            = session.Execute(getLastUpdate.Bind(postId));

            foreach (var lastUpdateAt in ex)
            {
                updatedAtPrev = lastUpdateAt.GetValue <TimeUuid>("updated_at");
            }

            _userStream.SyncUserStream(session, postId, updatedAtPrev);
        }
Esempio n. 7
0
        public static void ObradiNarudzbinu(String narId, Guid restId)
        {
            ISession          session    = SessionManager.GetSession();
            List <Narudzbina> narudzbine = new List <Narudzbina>();
            object            pom        = new object();

            if (session == null)
            {
                return;
            }

            DateTimeOffset date    = new DateTimeOffset();
            RowSet         narRest = session.Execute("select * from narudzbinerestorana where restoran_id=" + restId);

            foreach (Row nr in narRest)
            {
                if (nr["narudzbina_id"].ToString() == narId)
                {
                    date = DateTimeOffset.Parse(nr["datum"].ToString());
                }
            }

            Row      nar  = session.Execute("select * from narudzbina where narudzbina_id=" + narId).FirstOrDefault();
            TimeUuid tuid = TimeUuid.NewId(date);

            session.Execute("update narudzbina set status_obrade='Obradjena' where narudzbina_id=" + narId + " and datum = toTimestamp(" + tuid + ")"); //DateTimeOffset.Parse(nar["datum"].ToString()).DateTime.ToUniversalTime().ToString("yyyy-mm-dd HH:MM:ss.ffffff") + "+0000'");
            session.Execute("update narudzbinekorisnika set status_obrade ='Obradjena' where user_id=" + narId + " and datum = toTimestamp(" + tuid + ")");
            session.Execute("update narudzbinerestorana set status_obrade ='Obradjena' where restoran_id=" + narId + " and datum = toTimestamp(" + tuid + ")");
        }
Esempio n. 8
0
        public void UuidEqualityTest()
        {
            var date   = new DateTimeOffset(12021020116L, TimeSpan.Zero);
            var node1  = new byte[] { 0, 1, 2, 3, 4, 5 };
            var clock1 = new byte[] { 0xff, 0x01 };
            var id1    = TimeUuid.NewId(node1, clock1, date);
            var id2    = TimeUuid.NewId(node1, clock1, date);
            var id3    = TimeUuid.NewId(new byte[] { 0, 0, 0, 0, 0, 0 }, new byte[] { 0xff, 0x02 }, date);
            var id4    = TimeUuid.NewId(node1, clock1, new DateTimeOffset());

            Assert.AreEqual(id1, id2);
            Assert.True(id1 == id2);
            Assert.IsTrue(id1.Equals(id2));
            Assert.IsTrue(id1.Equals((object)id2));
            Assert.IsFalse(id1.Equals(string.Empty));
            Assert.IsFalse(id1.Equals(null));
            Assert.AreNotEqual(id1, id3);
            Assert.True(id1 != id3);
            Assert.AreNotEqual(id1, id4);
            Assert.True(id1 != id4);
            Assert.AreNotEqual(id3, id4);
            Assert.True(id3 != id4);
            //Check implicit conversion operators
            var id4Id     = (Guid)id4;
            var id4TimeId = (TimeUuid)id4Id;

            Assert.AreEqual(id4, id4TimeId);
            Assert.AreEqual(id4.ToByteArray(), id4Id.ToByteArray());
        }
Esempio n. 9
0
        public void EliminaProdPrecDarien(TimeUuid idNota, int pos, decimal montoTotal)
        {
            try
            {
                conectarDarien();
                string qry;

                string query = "DELETE objetos[{0}] FROM nota_compra WHERE idNota = {1};";
                qry = string.Format(query, pos, idNota);
                _session.Execute(qry);
                qry = "DELETE costo[{0}] FROM nota_compra WHERE idNota = {1};";
                qry = string.Format(qry, pos, idNota);
                _session.Execute(qry);
                qry = "UPDATE nota_compra SET montoFinal = {0} WHERE idNota = {1};";
                qry = string.Format(qry, montoTotal, idNota);
                _session.Execute(qry);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // desconectar o cerrar la conexión
            }
        }
Esempio n. 10
0
        public async Task <JsonNetResult> Add(AddCommentViewModel model)
        {
            // Shouldn't throw because of the Authorize attribute
            Guid userId = User.GetCurrentUserId().Value;

            var commentTimestamp = DateTimeOffset.UtcNow;

            // Add the new comment
            var commentOnVideo = new CommentOnVideo
            {
                UserId    = userId,
                VideoId   = model.VideoId,
                CommentId = TimeUuid.NewId(commentTimestamp),
                Comment   = model.Comment
            };

            await _comments.CommentOnVideo(commentOnVideo);

            // Lookup the current user's information to include in the return data
            UserProfile userInfo = await _userManagement.GetUserProfile(userId);

            return(JsonSuccess(new VideoCommentViewModel
            {
                CommentId = commentOnVideo.CommentId,
                Comment = commentOnVideo.Comment,
                CommentTimestamp = commentTimestamp,
                UserProfileUrl = Url.Action("Info", "Account", new { userId }),
                UserFirstName = userInfo.FirstName,
                UserLastName = userInfo.LastName,
                UserGravatarImageUrl = GravatarHasher.GetImageUrlForEmailAddress(userInfo.EmailAddress)
            }));
        }
Esempio n. 11
0
        /// <summary>
        /// Increase the URL hit counter by one. URL is identified by a UUID.
        /// </summary>
        /// <param name="uuid">URL's TimeUUID</param>
        /// <param name="check">Check if UUID exists before incrementing the counter.</param>
        /// <returns>Returns true if operation was successful.</returns>
        public bool HitURL(TimeUuid uuid, bool check = true)
        {
            // Whether to check if entity exists or not
            if (check)
            {
                QueryURLHitCount query = new QueryURLHitCount(this.session);
                if (!query.GetURLHitCount(uuid, out long hits))
                {
                    // Return false if entity does not exists
                    return(false);
                }
            }

            // Increase the URL popularity by one
            var cql = string.Format("UPDATE {0} SET {1} = {1} + 1 WHERE {2} = ? ;",
                                    CassandraSchema.TABLE_HITS.TBL_HITS,
                                    CassandraSchema.TABLE_HITS.HIT,
                                    CassandraSchema.TABLE_HITS.UUID);

            var prep = this.session.Prepare(cql);
            var stmt = prep.Bind(uuid);
            var rows = this.session.Execute(stmt);

            if (rows == null)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 12
0
 public override object CreateNewEntity()
 {
     return(new AllColumnsClass
     {
         /* 01 */ Id = Guid.NewGuid(),
         /* 02 */ Ascii = "simple ascii string.",
         /* 03 */ BigInt = 0,
         /* 04 */ Blob = File.ReadAllBytes(Directory.GetCurrentDirectory() + "\\Mocks\\Data\\small_image.png"),
         /* 05 */ Boolean = true,
         /* 06 */ Date = new DateTime(2017, 10, 10),
         /* 07 */ Decimal = 0,
         /* 08 */ Double = 0,
         /* 09 */ Float = 0,
         /* 10 */ Inet = new IPAddress(new byte[] { 127, 0, 0, 1 }),
         /* 11 */ Int = 0,
         /* 12 */ SmallInt = 0,
         /* 13 */ Text = "trying some text.",
         /* 14 */ Time = new TimeSpan(10, 0, 0),
         /* 15 */ Timestamp = new DateTime(2017, 10, 10, 12, 0, 0, 0),
         /* 16 */ TimeUuid = TimeUuid.NewId(DateTime.Now),
         /* 17 */ TinyInt = 0,
         /* 18 */ VarChar = "Text var char.",
         /* 19 */ VarInt = new BigInteger(0)
     });
 }
Esempio n. 13
0
        private void dgvModifProductosPrecios_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DialogResult dialog = new DialogResult();

            dialog = MessageBox.Show("¿Seguro que desea eliminar?", "Alerta!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dialog == DialogResult.Yes)
            {
                if (e.RowIndex > -1)
                {
                    DataGridViewRow row = this.dgvModifProductosPrecios.Rows[e.RowIndex];
                    if (row.Cells[0].Value != null)
                    {
                        decimal precio     = Convert.ToDecimal(row.Cells[1].Value.ToString());
                        decimal montoFinal = Convert.ToDecimal(textModifMontoTotal.Text);
                        montoFinal -= precio;
                        TimeUuid idNota = TimeUuid.Parse(cbModifID.Text);

                        var conn = new EnlaceCassandraDarien();
                        conn.EliminaProdPrecDarien(idNota, e.RowIndex, montoFinal);
                        dgvModifProductosPrecios.Rows.RemoveAt(e.RowIndex);
                        textModifMontoTotal.Text = montoFinal.ToString();
                        //actualizarDatosPantalla();
                    }
                }
            }
        }
Esempio n. 14
0
        private void dgvMostrar_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            dgvMostrarProductosPrecios.Rows.Clear();
            dgvMostrarProductosPrecios.Refresh();

            if (e.RowIndex > -1)
            {
                DataGridViewRow row = this.dgvMostrar.Rows[e.RowIndex];
                if (row.Cells[0].Value != null)
                {
                    string   id     = row.Cells[0].Value.ToString();
                    TimeUuid idNota = TimeUuid.Parse(id);

                    var conn = new EnlaceCassandraDarien();
                    IEnumerable <notaCompra> lst1;
                    lst1 = conn.Get_ProductoPrecioDarien(idNota);
                    int n = 0;

                    foreach (var lst in lst1)
                    {
                        foreach (var lst2 in lst.objetos)
                        {
                            n = dgvMostrarProductosPrecios.Rows.Add();
                            dgvMostrarProductosPrecios.Rows[n].Cells[0].Value = lst.objetos[n];
                            dgvMostrarProductosPrecios.Rows[n].Cells[1].Value = lst.costo[n];
                        }
                    }
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 取得页面信息中的环境变量值
        /// </summary>
        /// <param name="field">环境变量名称</param>
        /// <param name="page">页面信息</param>
        /// <param name="index">当前属性在所有属性中的索引</param>
        /// <returns>环境变量值</returns>
        public static object GetEnviromentValue(string field, Page page, int index)
        {
            var key = field.ToLower();

            switch (key)
            {
            case "timeuuid":
            {
                return(TimeUuid.NewId());
            }

            case "url":
            {
                return(page.Url);
            }

            case "targeturl":
            {
                return(page.TargetUrl);
            }

            case "now":
            {
                return(DateTime.Now);
            }

            case "monday":
            {
                return(DateTimeUtil.Monday);
            }

            case "today":
            {
                return(DateTime.Now.Date);
            }

            case "monthly":
            {
                return(DateTimeUtil.FirstDayOfTheMonth);
            }

            case "index":
            {
                return(index);
            }

            default:
            {
                var v1 = page.Request.GetExtra(field);
                if (v1 == null)
                {
                    var v2 = page.Request.GetExtra(key);
                    return(v2);
                }
                return(v1);
            }
            }
        }
Esempio n. 16
0
        public static dynamic GetEnviromentValue(string field, Page page, int index)
        {
            switch (field.ToLower())
            {
            case "timeuuid":
            {
                return(TimeUuid.NewId());
            }

            case "url":
            {
                return(page.Url);
            }

            case "targeturl":
            {
                return(page.TargetUrl);
            }

            case "now":
            {
                return(DateTime.Now);
            }

            case "monday":
            {
                return(DateTimeUtils.MondayOfCurrentWeek);
            }

            case "today":
            {
                return(DateTime.Now.Date);
            }

            case "monthly":
            {
                return(DateTimeUtils.FirstDayOfCurrentMonth);
            }

            case "index":
            {
                return(index);
            }

            default:
            {
                if (!page.Request.ExistExtra(field))
                {
                    return(field);
                }
                else
                {
                    return(page.Request.GetExtra(field)?.ToString());
                }
            }
            }
        }
Esempio n. 17
0
        public void Min_Test()
        {
            var timestamp = DateTimeOffset.Now;
            var timeuuid  = TimeUuid.Min(timestamp);

            Assert.AreEqual(timestamp, timeuuid.GetDate());
            Assert.AreEqual(new byte[] { 0x80, 0x80 }, timeuuid.ToByteArray().Skip(8).Take(2));
            Assert.AreEqual(new byte[] { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }, timeuuid.ToByteArray().Skip(10).Take(6));
        }
Esempio n. 18
0
        public void Parse_Test()
        {
            const string stringUuid = "3d555680-9886-11e4-8101-010101010101";
            var          timeuuid   = TimeUuid.Parse(stringUuid);

            Assert.AreEqual(TimeUuid.Parse(stringUuid), timeuuid);
            Assert.AreEqual(DateTimeOffset.Parse("2015-01-10 5:05:05 +0"), timeuuid.GetDate());
            Assert.AreEqual(stringUuid, timeuuid.ToString());
        }
Esempio n. 19
0
        public async Task <Guid> CreateAsync(Guid shopId, WorkOrder workOrder)
        {
            var time = await storage.TimestampService.NextTimestamp("WorkerOrderUuid");

            workOrder.Id = TimeUuid.NewId(time);
            await WriteAsync(shopId, workOrder);

            return(workOrder.Id);
        }
 public Notification(string userPhoneNumber, int appId, string title, string message)
 {
     UserPhoneNumber = userPhoneNumber;
     AppId           = appId;
     Id      = TimeUuid.NewId();
     Title   = title;
     Message = message;
     Status  = NotificationStatus.Waiting;
 }
Esempio n. 21
0
        private void cbModifCliente_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbModifEmpresa.Enabled = true;

            dgvModifProductosPrecios.Rows.Clear();
            dgvModifProductosPrecios.Refresh();
            lbModifProductos.Items.Clear();
            lbModifPrecios.Items.Clear();

            int index = cbModifCliente.SelectedIndex;

            cbModifID.SelectedIndex = index;

            string   id     = cbModifID.Text;
            TimeUuid idNota = TimeUuid.Parse(id);

            var conn = new EnlaceCassandraDarien();
            IEnumerable <notaCompra> lst1;

            lst1 = conn.Get_OneDarien(idNota);
            int    n       = 0;
            string empresa = "";


            foreach (var lst in lst1)
            {
                foreach (var lst2 in lst.objetos)
                {
                    n = dgvModifProductosPrecios.Rows.Add();
                    dgvModifProductosPrecios.Rows[n].Cells[0].Value = lst.objetos[n];
                    dgvModifProductosPrecios.Rows[n].Cells[1].Value = lst.costo[n];
                }
                textModifMontoTotal.Text = lst.montoFinal.ToString();
                textFechaGenerada.Text   = lst.fechaGenerada.ToString();
                textModifCliente.Text    = lst.nomCliente.ToString();
                empresa = lst.nomEmpresa;
            }
            n = 0;
            foreach (string item in lbModifEmpresa.Items)
            {
                if (item.ToString() == empresa)
                {
                    lbModifEmpresa.SelectedIndex = n;
                    break;
                }
                n++;
            }



            lbModifProductos.Items.Clear();
            lbModifPrecios.Items.Clear();


            fillComboEmpresa(lbModifProductos, lbModifPrecios, empresa);
            modEmpresa = true;
        }
Esempio n. 22
0
 public static CqlConnectorDeliveryContext GetCqlConnectorDeliveryContext([NotNull] ISerializer serializer) => new CqlConnectorDeliveryContext
 {
     ContextId            = TimeUuid.NewId(),
     TimeSliceId          = new DateTimeOffset(2010, 10, 10, 10, 10, 10, 10, TimeSpan.Zero),
     TimeSliceShardNumber = 42,
     ContextContent       = serializer.Serialize(new ConnectorDeliveryContext {
         ContextId = Guid.NewGuid().ToString()
     }),
 };
Esempio n. 23
0
 public Post(Row row)
 {
     post_id          = TimeUuid.Parse(row["post_id"].ToString());
     user_name        = row["user_name"].ToString();
     post_description = row["post_description"].ToString();
     post_blob        = (byte[])row["post_blob"];
     user_image_blob  = (byte[])row["user_image_blob"];
     date_posted      = DateTime.Parse(row["date_posted"].ToString()); //(DateTime)row["date_posted"] new DateTime
 }
Esempio n. 24
0
 public static bool TryParse(string value, out TimeUuid result)
 {
     result = default;
     if (!Guid.TryParse(value, out var guid))
     {
         return(false);
     }
     result = guid;
     return(true);
 }
Esempio n. 25
0
 public PostDTO GetPostById(Guid id)
 {
     using (ISession session = _cluster.Connect(_keyspace))
     {
         IMapper mapper = new Mapper(session);
         session.UserDefinedTypes.Define(new CommentProfile().Definitions);
         var post = mapper.FirstOrDefault <PostDTO>("where \"Post_Id\" = ? ", TimeUuid.Parse(id.ToString()));
         return(post);
     }
 }
Esempio n. 26
0
        public void Max_Test()
        {
            var timestamp = DateTimeOffset.Now;
            var timeuuid  = TimeUuid.Max(timestamp);

            Assert.AreEqual(timestamp, timeuuid.GetDate());
            // Variant Byte at index 8: 0x7f is changed into 0xbf
            Assert.AreEqual(new byte[] { 0xbf, 0x7f }, timeuuid.ToByteArray().Skip(8).Take(2));
            Assert.AreEqual(new byte[] { 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f }, timeuuid.ToByteArray().Skip(10).Take(6));
        }
Esempio n. 27
0
        public void First_With_Enum_Collections()
        {
            var expectedCollection = new[] { HairColor.Blonde, HairColor.Gray };
            var expectedMap        = new SortedDictionary <HairColor, TimeUuid>
            {
                { HairColor.Brown, TimeUuid.NewId() },
                { HairColor.Red, TimeUuid.NewId() }
            };
            var collectionValues = expectedCollection.Select(x => (int)x).ToArray();
            var mapValues        =
                new SortedDictionary <int, Guid>(expectedMap.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value));

            const string insertQuery =
                "INSERT INTO tbl_with_enum_collections (id, list1, list2, array1, set1, set2, set3, map1, map2, map3)" +
                " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

            Session.Execute(new SimpleStatement(insertQuery, 2000L, collectionValues, collectionValues,
                                                collectionValues, collectionValues, collectionValues, collectionValues, mapValues, mapValues,
                                                mapValues));
            Session.Execute(new SimpleStatement(insertQuery, 2001L, null, null, null, null, null, null, null, null,
                                                null));

            var config =
                new MappingConfiguration().Define(
                    PocoWithEnumCollections.DefaultMapping.TableName("tbl_with_enum_collections"));
            var mapper = new Mapper(Session, config);
            var result = mapper
                         .First <PocoWithEnumCollections>("SELECT * FROM tbl_with_enum_collections WHERE id = ?", 2000L);

            Assert.NotNull(result);
            Assert.AreEqual(2000L, result.Id);
            Assert.AreEqual(expectedCollection, result.List1);
            Assert.AreEqual(expectedCollection, result.List2);
            Assert.AreEqual(expectedCollection, result.Array1);
            Assert.AreEqual(expectedCollection, result.Set1);
            Assert.AreEqual(expectedCollection, result.Set2);
            Assert.AreEqual(expectedCollection, result.Set3);
            Assert.AreEqual(expectedMap, result.Dictionary1);
            Assert.AreEqual(expectedMap, result.Dictionary2);
            Assert.AreEqual(expectedMap, result.Dictionary3);

            result = mapper
                     .First <PocoWithEnumCollections>("SELECT * FROM tbl_with_enum_collections WHERE id = ?", 2001L);
            Assert.NotNull(result);
            Assert.AreEqual(2001L, result.Id);
            Assert.AreEqual(new HairColor[0], result.List1);
            Assert.AreEqual(new HairColor[0], result.List2);
            Assert.AreEqual(new HairColor[0], result.Array1);
            Assert.AreEqual(new HairColor[0], result.Set1);
            Assert.AreEqual(new HairColor[0], result.Set2);
            Assert.AreEqual(new HairColor[0], result.Set3);
            Assert.AreEqual(new Dictionary <HairColor, TimeUuid>(), result.Dictionary1);
            Assert.AreEqual(new Dictionary <HairColor, TimeUuid>(), result.Dictionary2);
            Assert.AreEqual(new Dictionary <HairColor, TimeUuid>(), result.Dictionary3);
        }
Esempio n. 28
0
        public void SerializationTests()
        {
            //TimeUuid and Guid are valid values for a timeuuid column value
            Assert.DoesNotThrow(() =>
                                Session.Execute(_insertPrepared.Bind(Guid.NewGuid(), TimeUuid.NewId())));

            var validUuidV1Bytes = TimeUuid.NewId().ToByteArray();

            Assert.DoesNotThrow(() =>
                                Session.Execute(_insertPrepared.Bind(Guid.NewGuid(), new Guid(validUuidV1Bytes))));
        }
        public void TimeUuid_Set_Insert_Select_Test()
        {
            const string columnName = "set1";

            InsertSelectTest <IEnumerable <TimeUuid> >(new[] { TimeUuid.NewId() }, columnName, TableTimeUuidCollections);
            InsertSelectTest(new[] { TimeUuid.NewId() }, columnName, TableTimeUuidCollections);
            InsertSelectTest(new SortedSet <TimeUuid> {
                TimeUuid.NewId(), TimeUuid.NewId()
            }, columnName,
                             TableTimeUuidCollections);
        }
        public void Uuid_List_Insert_Select_Test()
        {
            const string columnName = "list1";

            InsertSelectTest <IEnumerable <Guid> >(new[] { TimeUuid.NewId().ToGuid() }, columnName,
                                                   TableTimeUuidCollections);
            InsertSelectTest(new[] { TimeUuid.NewId().ToGuid() }, columnName, TableTimeUuidCollections);
            InsertSelectTest(new List <Guid> {
                TimeUuid.NewId().ToGuid()
            }, columnName, TableTimeUuidCollections);
        }