Пример #1
0
        static Document <Person> InsertDocument(IBucket bucket)
        {
            var document = new Document <Person>
            {
                Id      = "P1",
                Content = new Person
                {
                    FirstName = "John",
                    LastName  = "Adams",
                    Age       = 21
                }
            };

            var result = bucket.Insert(document);

            if (result.Success)
            {
                Console.WriteLine("Inserted document '{0}'", document.Id);
            }
            return(document);
        }
Пример #2
0
        static void Main(string[] args)
        {
            InitializeCouchbase();

            // create a new document in Couchbase Server
            var document = new Document <dynamic>
            {
                Id      = Guid.NewGuid().ToString(),
                Content = new
                {
                    firstName = "Connie",
                    lastName  = Path.GetRandomFileName(), // used to get random string
                    city      = Path.GetRandomFileName() + ", Ohio",
                    country   = "The United States of " + Path.GetRandomFileName(),
                    type      = "person"
                }
            };

            _bucket.Insert(document);
            Console.WriteLine($"Inserted document, key: {document.Id}");

            // query all the keys and documents using N1QL
            var queryText = "SELECT META(p).id AS documentKey, p.* FROM `default` AS p WHERE type='person'";
            var query     = QueryRequest.Create(queryText);

            query.ScanConsistency(ScanConsistency.RequestPlus);
            var result = _bucket.Query <dynamic>(query);

            foreach (var doc in result.Rows)
            {
                Console.WriteLine("----------");
                Console.WriteLine($"Key: {doc.documentKey}");
                Console.WriteLine($"\tfirstName: {doc.firstName}");
                Console.WriteLine($"\tlastName: {doc.lastName}");
                Console.WriteLine($"\tcity: {doc.city}");
                Console.WriteLine($"\tcountry: {doc.country}");
            }

            CloseCouchbase();
        }
Пример #3
0
        /// <summary>
        /// Inserts or replaces the item at the specified index.
        /// </summary>
        /// <param name="bucket">The bucket on which to operate.</param>
        /// <param name="index">The index.</param>
        /// <param name="itemFactory">The item factory to create the item to set.</param>
        /// <param name="check">A predicate to decide if a particular item should be replaced.</param>
        /// <param name="isNew">if set to <c>true</c> the index was not previously used.</param>
        /// <returns>
        ///   <c>true</c> if the item or repalced inserted; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="System.ArgumentOutOfRangeException">index;index must be greater or equal to 0 and less than capacity</exception>
        /// <remarks>
        /// The operation will be attempted as long as check returns true - this operation may starve.
        /// </remarks>
        public static bool InsertOrUpdate <T>(this IBucket <T> bucket, int index, Func <T> itemFactory, Predicate <T> check, out bool isNew)
        {
            if (bucket == null)
            {
                throw new ArgumentNullException("bucket");
            }
            isNew = true;
            var factoryUsed = false;
            var created     = default(T);

            while (true)
            {
                if (isNew)
                {
                    T stored;
                    if (!factoryUsed)
                    {
                        created     = itemFactory.Invoke();
                        factoryUsed = true;
                    }
                    if (bucket.Insert(index, created, out stored))
                    {
                        return(true);
                    }
                    isNew = false;
                }
                else
                {
                    var result = itemFactory.Invoke();
                    if (bucket.Update(index, _ => result, check, out isNew))
                    {
                        return(true);
                    }
                    if (!isNew)
                    {
                        return(false); // returns false only when check returns false
                    }
                }
            }
        }
Пример #4
0
        public IActionResult Add([FromBody] WishlistItem item)
        {
            var idd = "";

            var n1ql = @" SELECT count (*) as id FROM   `travel-sample`;";

            var query = QueryRequest.Create(n1ql);

            query.ScanConsistency(ScanConsistency.RequestPlus);
            var res = _buckate.Query <WishlistItem>(query);
            var cnt = res.Rows[0].ToString();

            foreach (var row in res.Rows)
            {
                idd = (row.id);
            }

            var document = new Document <dynamic>
            {
                Id      = idd.ToString(),
                Content = new
                {
                    //name = "Polar Ice",
                    //brewery_id = "Polar"
                    id      = item.id,
                    country = item.country,
                    name    = item.name,
                    type    = item.type
                }
            };
            var result = _buckate.Insert(document);

            if (result.Success)
            {
                return(Ok(item));
                // Console.WriteLine("Inserted document '{0}'", document.Id);
            }
            return(Ok("Not Success"));
        }
Пример #5
0
        public ActionResult Insert()
        {
            string id = "user::" + Guid.NewGuid().ToString();

            var document = new Document <dynamic>
            {
                Id      = id,
                Content = new
                {
                    Id    = id,
                    Hello = "World",
                    Time  = DateTime.Now.ToLongTimeString(),
                    Type  = "user"
                }
            };

            bucket.Insert <dynamic>(id, document);

            var loaded = bucket.Get <dynamic>(id);

            return(Content(loaded.Value.ToString()));
        }
Пример #6
0
        public static bool TryGetOrInsert <T>(this IBucket <T> bucket, int index, Func <T> itemFactory, out T stored)
        {
            if (bucket == null)
            {
                throw new ArgumentNullException(nameof(bucket));
            }

            if (bucket.TryGet(index, out stored))
            {
                return(false);
            }

            var created = itemFactory.Invoke();

            if (!bucket.Insert(index, created, out stored))
            {
                return(false);
            }

            stored = created;
            return(true);
        }
Пример #7
0
        public IActionResult AddToken([FromBody] Token JwdToken)
        {
            var idd = "";

            var n1ql = @" SELECT count (*) as id FROM   `test`;";

            var query = QueryRequest.Create(n1ql);

            query.ScanConsistency(ScanConsistency.RequestPlus);
            var res = _buckate2.Query <WishlistItem>(query);
            var cnt = res.Rows[0].ToString();

            foreach (var row in res.Rows)
            {
                idd = (row.id);
            }

            var document = new Document <dynamic>
            {
                Id      = idd.ToString(),
                Content = new
                {
                    //name = "Polar Ice",
                    //brewery_id = "Polar"
                    Id     = idd.ToString(),
                    UserId = JwdToken.UserId,
                    token  = JwdToken.token,
                }
            };
            var result = _buckate2.Insert(document);

            if (result.Success)
            {
                return(Ok(JwdToken));
                // Console.WriteLine("Inserted document '{0}'", document.Id);
            }
            return(Ok("Not Success"));
        }
Пример #8
0
        /// <summary>
        ///     Inserts or replaces the item at the specified index.
        /// </summary>
        /// <param name="bucket">The bucket on which to operate.</param>
        /// <param name="index">The index.</param>
        /// <param name="item">The item set.</param>
        /// <param name="check">A predicate to decide if a particular item should be replaced.</param>
        /// <param name="isNew">if set to <c>true</c> the index was not previously used.</param>
        /// <returns>
        ///     <c>true</c> if the item or replaced inserted; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">index;index must be greater or equal to 0 and less than capacity</exception>
        /// <remarks>
        ///     The operation will be attempted as long as check returns true - this operation may starve.
        /// </remarks>
        public static bool InsertOrUpdateChecked <T>(this IBucket <T> bucket, int index, T item, Predicate <T> check, out bool isNew)
        {
            if (bucket == null)
            {
                throw new ArgumentNullException(nameof(bucket));
            }

            if (check == null)
            {
                throw new ArgumentNullException(nameof(check));
            }

            isNew = true;
            while (true)
            {
                if (isNew)
                {
                    if (bucket.Insert(index, item, out _))
                    {
                        return(true);
                    }

                    isNew = false;
                }
                else
                {
                    if (bucket.Update(index, _ => item, check, out isNew))
                    {
                        return(true);
                    }

                    if (!isNew)
                    {
                        return(false); // returns false only when check returns false
                    }
                }
            }
        }
Пример #9
0
        public void SaveResonseAuditLog(HttpActionExecutedContext context)
        {
            string    requestParameter  = context.Request.Content.ReadAsStringAsync().Result;
            string    responseParameter = context.Response.Content.ReadAsStringAsync().Result;
            AuditLogs auditLogs         = new AuditLogs();

            auditLogs.Method           = context.Request.Method.ToString();
            auditLogs.URL              = context.Request.RequestUri.AbsoluteUri;
            auditLogs.ControllerName   = context.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
            auditLogs.Action           = context.ActionContext.ActionDescriptor.ActionName;
            auditLogs.StatusCode       = context.Response.ToString().Split(',')[0].ToString().Split(':')[1];
            auditLogs.Status           = context.Response.ReasonPhrase;
            auditLogs.RequestParameter = JSONHelper.ToJSON(requestParameter);
            auditLogs.Response         = JSONHelper.ToJSON(responseParameter);
            auditLogs.LogDate          = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());
            auditLogs.LogTime          = DateTime.Now.ToLongTimeString();
            var auditLogsDoc = new Document <AuditLogs>()
            {
                Id      = "Log_Response_" + DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                Content = auditLogs
            };
            var result = _bucket.Insert(auditLogsDoc);
        }
Пример #10
0
        public void Add(Patient entity)
        {
            var model = new PatientDb()
            {
                Id           = entity.Id,
                FirstName    = entity.FirstName,
                MiddleName   = entity.MiddleName,
                LastName     = entity.LastName,
                DateOfBirth  = entity.DateOfBirth.Value,
                PlaceOfBirth = entity.PlaceOfBirth.Value,
                Occupation   = entity.Occupation,
                Sex          = entity.Sex.Value,
                PatientType  = entity.PatientType.Value
            };

            var patient = new Document <PatientDb>()
            {
                Id      = entity.Id.ToString(),
                Content = model
            };

            _bucket.Insert(patient);
        }
Пример #11
0
        // end::ShoppingCartMigratorTop[]

        // tag::ShoppingCartMigratorGo[]
        public bool Go()
        {
            var carts = _context.ShoppingCarts
                        .Include(x => x.Items)
                        .ToList();

            foreach (var cart in carts)
            {
                var cartDocument = new Document <dynamic>
                {
                    Id      = cart.Id.ToString(),
                    Content = MapCart(cart)
                };
                var result = _bucket.Insert(cartDocument);
                if (!result.Success)
                {
                    Console.WriteLine($"There was an error migrating Shopping Cart {cart.Id}");
                    return(false);
                }
                Console.WriteLine($"Successfully migrated Shopping Cart {cart.Id}");
            }
            return(true);
        }
Пример #12
0
        public static bool UpdateJson(this IBucket client, string key, object value, Type objType)
        {
            var current = client.Get <string>(key);

            if (!current.Success)
            {
                throw new CouchbaseException("Item was not found.");
            }

            // Deletes old item
            var deleteResult = client.Remove(key);

            if (!deleteResult.Success)
            {
                return(false);
            }

            // Inserts to replace with new data
            var json   = JsonConvert.SerializeObject(value);
            var result = client.Insert(key, json);

            return(result.Success);
        }
Пример #13
0
        /// <summary>
        ///     Inserts or replaces the item at the specified index.
        /// </summary>
        /// <param name="bucket">The bucket on which to operate.</param>
        /// <param name="index">The index.</param>
        /// <param name="itemFactory">The item factory to create the item to insert.</param>
        /// <param name="itemUpdateFactory">The item factory to create the item to replace with.</param>
        /// <param name="isNew">if set to <c>true</c> the index was not previously used.</param>
        /// <exception cref="ArgumentOutOfRangeException">index;index must be greater or equal to 0 and less than capacity</exception>
        /// <remarks>
        ///     The operation will be attempted as long as check returns true - this operation may starve.
        /// </remarks>
        public static void InsertOrUpdate <T>(this IBucket <T> bucket, int index, Func <T> itemFactory, Func <T, T> itemUpdateFactory, out bool isNew)
        {
            if (bucket == null)
            {
                throw new ArgumentNullException(nameof(bucket));
            }

            isNew = true;
            var factoryUsed = false;
            var created     = default(T);

            while (true)
            {
                if (isNew)
                {
                    if (!factoryUsed)
                    {
                        created     = itemFactory.Invoke();
                        factoryUsed = true;
                    }

                    if (bucket.Insert(index, created, out _))
                    {
                        return;
                    }

                    isNew = false;
                }
                else
                {
                    if (bucket.Update(index, itemUpdateFactory, Tautology, out isNew))
                    {
                        return;
                    }
                }
            }
        }
        public Task Append(string eventId, string eventJsonString)
        {
            try
            {
                var result = _bucket.Insert(eventId, eventJsonString);
                if (!result.Success)
                {
                    throw new Exception("append event to store exception", result.Exception);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(TaskDone.Done);
            //return Task.Run(() =>
            //{
            //    if (!task.Result.Success)
            //    {
            //        throw new Exception("append event to store exception", task.Result.Exception);
            //    }
            //});
        }
        private void Acquire(TimeSpan timeout)
        {
            logger.Trace($"Trying to acquire lock for {resource} within {timeout.TotalSeconds} seconds");

            System.Diagnostics.Stopwatch acquireStart = new System.Diagnostics.Stopwatch();
            acquireStart.Start();

            string id = $"{resource}:{DocumentTypes.Lock}".GenerateHash();

            while (string.IsNullOrEmpty(resourceId))
            {
                // default ttl for lock document
                TimeSpan ttl = DateTime.UtcNow.Add(timeout).AddMinutes(1).TimeOfDay;

                // read the document
                IDocumentResult <Lock> document = bucket.GetDocument <Lock>(id);

                // false means the document does not exists got ahead and create
                if (document.Success == false)
                {
                    Lock @lock = new Lock
                    {
                        Id       = id,
                        Name     = resource,
                        ExpireOn = DateTime.UtcNow.Add(timeout).ToEpoch()
                    };

                    IOperationResult <Lock> result = bucket.Insert(@lock.Id, @lock, ttl);
                    if (result.Success)
                    {
                        resourceId = id;
                        break;
                    }
                }
                else if (document.Content != null)
                {
                    if (document.Content.ExpireOn < DateTime.UtcNow.ToEpoch())
                    {
                        IDocumentFragment <Lock> result = bucket.MutateIn <Lock>(id)
                                                          .WithCas(document.Document.Cas)
                                                          .WithExpiry(ttl)
                                                          .Upsert(l => l.ExpireOn, DateTime.UtcNow.Add(timeout).ToEpoch(), false)
                                                          .Execute();

                        if (result.Success)
                        {
                            resourceId = id;
                            break;
                        }
                    }
                }

                // check the timeout
                if (acquireStart.ElapsedMilliseconds > timeout.TotalMilliseconds)
                {
                    throw new CouchbaseDistributedLockException($"Could not place a lock on the resource '{resource}': Lock timeout.");
                }

                // sleep for 2000 millisecond
                logger.Trace($"Unable to acquire lock for {resource}. Will check try after 2 seconds");
                System.Threading.Thread.Sleep(2000);
            }

            logger.Trace($"Acquired lock for {resource} in {acquireStart.Elapsed.TotalSeconds} seconds");
        }
Пример #16
0
        static void Main(string[] args)
        {
            var _dbContext = new UserBehaviorDbContext();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfigurationRoot configuration = builder.Build();


            ClusterHelper.Initialize(new ClientConfiguration {
                Servers = new List <Uri> {
                    new Uri(configuration.GetSlnConfig("CouchbaseEndpoint"))
                }
            }, new PasswordAuthenticator(configuration.GetSlnConfig("CouchbaseUserName"), configuration.GetSlnConfig("CouchbasePassword")));

            var factory = new ConnectionFactory()
            {
                HostName = configuration.GetSlnConfig("RabbitMQEndpoint")
            };

            IBucket _bucket = ClusterHelper.GetBucket("TesteViajaNetUserBehavior");


            try
            {
                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        channel.QueueDeclare(queue: "UserBehavior",
                                             durable: false,
                                             exclusive: false,
                                             autoDelete: false,
                                             arguments: null);

                        var consumer = new EventingBasicConsumer(channel);
                        consumer.Received += (model, ea) =>
                        {
                            var body    = ea.Body;
                            var message = Encoding.UTF8.GetString(body);

                            PageAccess pageAccess = JsonConvert.DeserializeObject <PageAccess>(message);

                            pageAccess.Id          = Guid.NewGuid();
                            pageAccess.DateCreated = DateTime.Now;


                            _dbContext.PageAccesses.Add(pageAccess);
                            _dbContext.SaveChanges();

                            _bucket.Insert <PageAccess>(pageAccess.Id.ToString(), pageAccess);
                        };
                        channel.BasicConsume(queue: "UserBehavior",
                                             autoAck: true,
                                             consumer: consumer);

                        Console.WriteLine(" Press [enter] to exit.");
                        Console.ReadLine();
                    }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
            finally
            {
                ClusterHelper.Close();
            }
        }
Пример #17
0
        public IHttpActionResult EmployeeRegister(Individual model)
        {
            try
            {
                if (model.fullName == null)
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "224-Full name is required"), new JsonMediaTypeFormatter()));
                }
                else
                {
                    if (string.IsNullOrEmpty(model.fullName.Ar_SA) && string.IsNullOrEmpty(model.fullName.En_US))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "224-Full name is required"), new JsonMediaTypeFormatter()));
                    }
                }
                // Validate Model
                if (!ModelState.IsValid)
                {
                    var modelErrors = new List <string>();
                    foreach (var modelState in ModelState.Values)
                    {
                        foreach (var modelError in modelState.Errors)
                        {
                            modelErrors.Add(modelError.ErrorMessage == "" ? modelError.Exception.Message : modelError.ErrorMessage);
                        }
                    }
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), modelErrors[0].ToString()), new JsonMediaTypeFormatter()));
                }

                var userDocumentEmail = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where email= '" + model.Email + "' and isActive=true").ToList();
                if (userDocumentEmail.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "105-The e-mail already exists"), new JsonMediaTypeFormatter()));
                }

                if (model.LoginDetails != null)
                {
                    if (string.IsNullOrEmpty(model.LoginDetails.Password))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "158-Password is required"), new JsonMediaTypeFormatter()));
                    }
                }

                var userDocumentPhone = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where " + _bucket.Name + ".mobNum.num= '" + model.MobNum.NumM + "'").ToList();

                if (userDocumentPhone.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "Mobile number already exists"), new JsonMediaTypeFormatter()));
                }

                Address address = new Address();
                address.City    = model.Address.City;
                address.State   = model.Address.State;
                address.Area    = model.Address.Area;
                address.Street  = model.Address.Street;
                address.BldgNum = model.Address.BldgNum;
                address.FlatNum = model.Address.FlatNum;

                MobNum mobNum = new MobNum();
                mobNum.CountryCodeM = model.MobNum.CountryCodeM;
                mobNum.NumM         = model.MobNum.NumM;
                mobNum.AreaM        = model.MobNum.AreaM;

                TelNum telNum = new TelNum();
                if (model.TelNum != null)
                {
                    telNum.CountryCodeT = model.TelNum.CountryCodeT;
                    telNum.NumT         = model.TelNum.NumT;
                    telNum.AreaT        = model.TelNum.AreaT;
                }

                List <AuditInfo> lstauditInfo = new List <AuditInfo>();
                AuditInfo        auditInfo    = new AuditInfo();
                auditInfo.Version        = "1";
                auditInfo.Status         = "true";
                auditInfo.LastChangeDate = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());
                auditInfo.LastChangeBy   = model.Email;
                lstauditInfo.Add(auditInfo);

                List <Roles> lstRoles = new List <Roles>();
                if (model.Roles != null)
                {
                    foreach (var role in model.Roles)
                    {
                        Roles roles = new Roles();
                        roles.RoleID = role.RoleID;
                        roles.Name   = role.Name;
                        roles.Link   = role.Link;
                        lstRoles.Add(roles);
                    }
                }

                #region MyRegion
                List <Fines>        lstFines        = new List <Fines>();
                List <Documents>    lstDocuments    = new List <Documents>();
                List <Vehicles>     lstVehicles     = new List <Vehicles>();
                List <Incidents>    lstIncident     = new List <Incidents>();
                List <ScoreCards>   lstScoreCard    = new List <ScoreCards>();
                List <DriverStatus> lstdriverStatus = new List <DriverStatus>();
                #endregion

                FullName fullName = new FullName();
                fullName.En_US = model.fullName.En_US;
                fullName.Ar_SA = model.fullName.Ar_SA;

                Status status = new Status();
                if (model.Status != null)
                {
                    status.StatusID = model.Status.StatusID;
                    status.DateTime = model.Status.DateTime;
                }



                //DataConversion.ConvertYMDHMS(DateTime.Now.AddDays(Convert.ToInt16(ConfigurationManager.AppSettings.Get("ValidToProfilePhotoDays"))).ToString())
                ProfilePhoto profilePhoto = new ProfilePhoto();
                if (model.ProfilePhoto != null)
                {
                    profilePhoto.DocFormat = model.ProfilePhoto.DocFormat;
                    profilePhoto.Photo     = model.ProfilePhoto.Photo;
                    profilePhoto.ValidFrom = DataConversion.ConvertYMDHMS(DateTime.Now.ToString());
                    profilePhoto.ValidTo   = DataConversion.ConvertYMDHMS(DateTime.Now.AddDays(Convert.ToInt16(ConfigurationManager.AppSettings.Get("ValidToProfilePhotoDays"))).ToString());
                }
                string docId = string.Empty;
                if (string.IsNullOrEmpty(model.KeyID))
                {
                    docId = "individual_" + Guid.NewGuid();
                }
                else
                {
                    docId = "individual_" + model.KeyID;
                }

                var employeeDoc = new Document <Individual>()
                {
                    Id      = docId,
                    Content = new Individual
                    {
                        KeyID         = docId,
                        fullName      = fullName,
                        DOB           = DataConversion.ConvertDateYMD(model.DOB),
                        Nationality   = model.Nationality,
                        Gender        = model.Gender,
                        Fines         = lstFines,
                        Language      = model.Language,
                        MaritalStatus = model.MaritalStatus,
                        MobNum        = mobNum,
                        AuditInfo     = lstauditInfo,
                        Vehicles      = lstVehicles,
                        Roles         = lstRoles,
                        TelNum        = telNum,
                        DocType       = ("Individual").ToLower(),
                        Documents     = lstDocuments,
                        Email         = model.Email,
                        ProfilePhoto  = profilePhoto,
                        Notes         = model.Notes,
                        ScoreCards    = lstScoreCard,
                        Address       = address,
                        Religion      = model.Religion,
                        Status        = status,
                        Incidents     = lstIncident,
                        DriverStatus  = lstdriverStatus,
                    },
                };
                var result = _bucket.Insert(employeeDoc);
                if (!result.Success)
                {
                    return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter()));
                }
                return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Id), new JsonMediaTypeFormatter()));
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
Пример #18
0
        public void Test_Get()
        {
            var key   = "Test_Get";
            var value = "thevalue";

            _bucket.Remove(key);
            _bucket.Insert(key, value);
            var result = _bucket.Get <string>(key);

            Assert.AreEqual(ResponseStatus.Success, result.Status);
        }
Пример #19
0
        public async Task <IHttpActionResult> InsertUser(Login model)
        {
            //string ppp = EncryptDecryptString.DecodePasswordToFrom64("MTIzNDU2OTk5");
            try
            {
                if (string.IsNullOrEmpty(model.Name))
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "224-name is required"), new JsonMediaTypeFormatter()));
                }
                if (string.IsNullOrEmpty(model.Email))
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "112-email is required"), new JsonMediaTypeFormatter()));
                }
                if (string.IsNullOrEmpty(model.Password))
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "158-Password is required"), new JsonMediaTypeFormatter()));
                }
                var userDocumentEmail = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where email= '" + model.Email + "'  and isActive=true and isActive=true and meta().id like'%login_%'").ToList();
                if (userDocumentEmail.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "105-The e-mail already exists"), new JsonMediaTypeFormatter()));
                }
                if (model.MobNum == null)
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "199-mobnum is required"), new JsonMediaTypeFormatter()));
                }
                else
                {
                    if (string.IsNullOrEmpty(model.MobNum.AreaM))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "200-areaM is required"), new JsonMediaTypeFormatter()));
                    }
                    if (string.IsNullOrEmpty(model.MobNum.NumM))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "201-NumM is required"), new JsonMediaTypeFormatter()));
                    }
                    if (string.IsNullOrEmpty(model.MobNum.CountryCodeM))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "202-CountryCodeM is required"), new JsonMediaTypeFormatter()));
                    }
                }
                if (model.Roles == null)
                {
                    return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "203-roles is required"), new JsonMediaTypeFormatter()));
                }
                else
                {
                    if (string.IsNullOrEmpty(model.Roles.PrimaryRole))
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "204-PrimaryRole is required"), new JsonMediaTypeFormatter()));
                    }
                    if (model.Roles.OtherRoles == null)
                    {
                        return(Content(HttpStatusCode.BadRequest, MessageResponse.Message(HttpStatusCode.BadRequest.ToString(), "205-OtherRoles is required"), new JsonMediaTypeFormatter()));
                    }
                }

                var userDocumentPhone = _bucket.Query <object>(@"SELECT * From " + _bucket.Name + " where " + _bucket.Name + ".mobNum.num= '" + model.MobNum.NumM + "' and isActive=true and meta().id like'%login_%'").ToList();

                if (userDocumentPhone.Count > 0)
                {
                    return(Content(HttpStatusCode.Conflict, MessageResponse.Message(HttpStatusCode.Conflict.ToString(), "Mobile number already exists"), new JsonMediaTypeFormatter()));
                }

                try
                {
                    List <PrevPassword> prevPassword = new List <PrevPassword>();
                    var    loginDocumentId           = "login_" + Guid.NewGuid();
                    MobNum mobNum = new MobNum();
                    mobNum.CountryCodeM = model.MobNum.CountryCodeM;
                    mobNum.NumM         = model.MobNum.NumM;
                    mobNum.AreaM        = model.MobNum.AreaM;
                    TelNum telNum = new TelNum();
                    if (model.TelNum != null)
                    {
                        telNum.CountryCodeT = model.TelNum.CountryCodeT;
                        telNum.NumT         = model.TelNum.NumT;
                        telNum.AreaT        = model.TelNum.AreaT;
                    }
                    var loginDocument = new Document <Login>()
                    {
                        Id      = loginDocumentId,
                        Content = new Login
                        {
                            Lang        = model.Lang,
                            DocType     = "user",
                            Name        = model.Name,
                            PassSetDate = DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                            Password    = EncryptDecryptString.EncodePasswordToBase64(model.Password),
                            Email       = model.Email,
                            EmirateId   = model.EmirateId,
                            //Mobile = model.Mobile,
                            MobNum     = mobNum,
                            TelNum     = telNum,
                            Department = model.Department,
                            Roles      = model.Roles,
                            PrevPass   = prevPassword,
                            IsActive   = true,
                            Created_By = model.Email,
                            UserPhoto  = model.UserPhoto,
                            Created_On = DataConversion.ConvertYMDHMS(DateTime.Now.ToString()),
                        },
                    };
                    var result = _bucket.Insert(loginDocument);
                    if (!result.Success)
                    {
                        //_bucket.Remove(loginResult.Document.Content.Email);
                        return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), result.Message), new JsonMediaTypeFormatter()));
                    }
                    return(Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result.Document.Content.Email), new JsonMediaTypeFormatter()));
                }
                catch (Exception ex)
                {
                    //_bucket.Remove(result.Document.Id);
                    return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.Message), new JsonMediaTypeFormatter()));
                }

                //}
                // return Content(HttpStatusCode.OK, MessageResponse.Message(HttpStatusCode.OK.ToString(), MessageDescriptions.Add, result..Id), new JsonMediaTypeFormatter());
                //}
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, MessageResponse.Message(HttpStatusCode.InternalServerError.ToString(), ex.StackTrace), new JsonMediaTypeFormatter()));
            }
        }
 public void PersistEvent(string actorName, int eventIndex, IMessage @event)
 {
     var envelope = new Envelope(actorName, eventIndex, @event, "event");
     var res      = _bucket.Insert(envelope.Key, envelope);
 }
        public void PrepareTest()
        {
            var a = _bucket.Get <dynamic>("a");
            var b = _bucket.Get <dynamic>("b");
            var c = _bucket.Exists("c");

            Assert.AreEqual(ResponseStatus.KeyNotFound, a.Status);
            Assert.AreEqual(ResponseStatus.KeyNotFound, b.Status);
            Assert.IsTrue(c);

            a = _bucket.Insert("a", new { });
            Assert.IsTrue(a.Success);

            var increment = _bucket.Increment("counter");

            Assert.IsTrue(increment.Success);

            var aMeta = _bucket.MutateIn <dynamic>("a").
                        Insert("tx", new
            {
                ts    = increment.Value,
                md    = new[] { b.Id },
                value = new { name = "jeff" }
            }, SubdocPathFlags.Xattr);

            var execute = aMeta.Execute();

            Assert.IsTrue(execute.Success);

            a = _bucket.Get <dynamic>("a");
            Assert.AreEqual("", a.Value);

            b = _bucket.Insert("b", new { });
            Assert.IsTrue(b.Success);

            var bMeta = _bucket.MutateIn <dynamic>("b").
                        Insert("tx", new
            {
                ts    = increment.Value,
                md    = new[] { a.Id },
                value = new { name = "mike" }
            }, SubdocPathFlags.Xattr);

            execute = bMeta.Execute();
            Assert.IsTrue(execute.Success);

            b = _bucket.Get <dynamic>("b");
            Assert.AreEqual("", b.Value);

            dynamic aTx = _bucket.LookupIn <dynamic>("a").Get("tx", SubdocPathFlags.Xattr).Execute().Content("tx");
            dynamic bTx = _bucket.LookupIn <dynamic>("b").Get("tx", SubdocPathFlags.Xattr).Execute().Content("tx");

            //ts
            Assert.AreEqual(increment.Value, aTx.ts.Value);
            Assert.AreEqual(increment.Value, bTx.ts.Value);

            //md
            Assert.AreEqual(a.Id, bTx.md[0].Value);
            Assert.AreEqual(b.Id, aTx.md[0].Value);

            //value
            Assert.AreEqual("jeff", aTx.value.name.Value);
            Assert.AreEqual("mike", bTx.value.name.Value);
        }
        public void Insert_DocumentAlreadyExistsException()
        {
            //setup
            var key = "Insert_DocumentAlreadyExistsException";

            _bucket.Remove(new Document <dynamic> {
                Id = key
            });
            _bucket.Insert(new Document <dynamic> {
                Id = key, Content = new { name = "foo" }
            });

            //act
            var result = _bucket.Insert(new Document <dynamic> {
                Id = key, Content = new { name = "foo" }
            });

            //assert
            Assert.AreEqual(result.Exception.GetType(), typeof(DocumentAlreadyExistsException));
        }