Exemple #1
0
        internal virtual DbSet <TEntityAux> GetDbSet <TEntityAux>(bool checkPermisos = true) where TEntityAux : class
        {
            DbSet dbSet = GenericEntity.Select(typeof(TEntityAux));
            DbSet <TEntityAux> dbSetEntity = dbSet.Cast <TEntityAux>();

            return(dbSetEntity);
        }
Exemple #2
0
        public ResultInfo SaveInventor(GenericEntity <Inventor> model, Auditoria auditoria)
        {
            var result = new ResultInfo()
            {
                Succeeded = false
            };

            var inventor = model.Generic as Inventor; //inventor data

            if (inventor.ExpedienteId == 0)
            {
                return(result);
            }

            if (inventor.Id == 0)
            {
                DbContext.Inventores.Add(inventor);
                DbContext.SaveChanges();
            }
            auditoria.Evento += "-" + inventor.Id.ToString();
            SaveAuditoria(auditoria);

            result.Result    = inventor;
            result.Succeeded = true;
            return(result);
        }
Exemple #3
0
        ///
        /// PRIORIDADES
        ///
        public ResultInfo SaveReferencia(GenericEntity <Prioridad> model)
        {
            var result = new ResultInfo()
            {
                Succeeded = false
            };

            var auditoria = model.Extra as Auditoria;
            var prioridad = model.Generic as Prioridad; //prioridad data

            if (prioridad.ExpedienteId <= 0)
            {
                return(result);
            }


            DbContext.Prioridades.Add(prioridad);
            DbContext.SaveChanges();
            SaveAuditoria(auditoria);

            var referencia = (from pr in DbContext.Prioridades
                              join p in DbContext.Paises on pr.PaisId equals p.Id
                              where pr.Id == prioridad.Id
                              select new ModelPrioridad()
            {
                Prioridad = pr,
                PaisCodigo = p.Codigo
            }).First();

            result.Succeeded = true;
            result.Result    = referencia;
            return(result);
        }
        private GenericEntity GetUserEntity(Guid id
                                            , string title
                                            , string firstName
                                            , string lastName
                                            , int age
                                            , decimal salary
                                            , DateTime bornOnDate
                                            , string department
                                            , string emailAddress
                                            , short employeeNumber
                                            , long universalId
                                            , double vacationDaysInHours)
        {
            var userEntity = new GenericEntity {
                EntityName = "User", PropertyList = new Dictionary <string, object>()
            };

            userEntity.PropertyList.Add("id", id);
            userEntity.PropertyList.Add("Title", title);
            userEntity.PropertyList.Add("FirstName", firstName);
            userEntity.PropertyList.Add("LastName", lastName);
            userEntity.PropertyList.Add("Age", age);
            userEntity.PropertyList.Add("Salary", salary);
            userEntity.PropertyList.Add("BornOn", bornOnDate);
            userEntity.PropertyList.Add("Department", department);
            userEntity.PropertyList.Add("EmailAddress", emailAddress);
            userEntity.PropertyList.Add("EmployeeNumber", employeeNumber);
            userEntity.PropertyList.Add("UniversalId", universalId);
            userEntity.PropertyList.Add("VacationDaysInHours", vacationDaysInHours);
            return(userEntity);
        }
Exemple #5
0
    /// <summary>
    /// Handles outputting to things with the inventory interface.
    /// </summary>
    /// <param name="OUT_INV"></param>
    public void OutputToInventory(IInventory OUT_INV)
    {
        //If the inventory is completely full, then just return.
        if (OUT_INV.IsFull())
        {
            return;
        }
        else
        {
            //Get the item list with all its counts.
            List <ItemAmount> ITEM_LIST = INV.GetItemAmountList();

            //For each unique item, attempt to add its count.
            foreach (ItemAmount ITEM_INFO in ITEM_LIST)
            {
                //If attempting to add the items would be successful,
                if (OUT_INV.AttemptAddItem(ITEM_INFO.Item, ITEM_INFO.Amount))
                {
                    GenericEntity      OUT_INFO     = OUT_INV.GetEntity();
                    List <GenericItem> UNIQUE_ITEMS = INV.GetUniqueItemsList();
                    if (UNIQUE_ITEMS.Contains(ITEM_INFO.Item))
                    {
                        UNIQUE_ITEMS.Add(ITEM_INFO.Item);
                    }

                    //Check if it is valid for us to place these items into the given entity.
                    if (GameManager.Instance.isItemPlacementValid(UNIQUE_ITEMS, OUT_INV.GetEntity().FLAGS))
                    {
                        OUT_INV.AddItem(ITEM_INFO.Item, ITEM_INFO.Amount);
                        INV.ExtractItem(ITEM_INFO.Item, ITEM_INFO.Amount);
                    }
                }
            }
        }
    }
        /// <summary>
        /// Método que llama al servicio
        /// </summary>
        /// <param name="datos">parametro que contiene los datos que necesita el servicio</param>
        /// <returns>retorna el total de coincidencias</returns>
        public string callApi(GenericEntity datos)
        {
            var matches = string.Empty;

            try
            {
                WebRequest request = HttpWebRequest.Create(datos.fullUrl);
                if (datos.name == "Bing")
                {
                    request.Headers["Ocp-Apim-Subscription-Key"] = datos.key;
                }
                HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
                string          json     = new StreamReader(response.GetResponseStream()).ReadToEnd();

                if (datos.name == "Bing")
                {
                    BingEntity.BingObject bingJson = JsonConvert.DeserializeObject <BingEntity.BingObject>(json);
                    matches = bingJson.webPages.totalEstimatedMatches.ToString();
                }
                else
                {
                    GoogleEntity.GoogleObject googleJson = JsonConvert.DeserializeObject <GoogleEntity.GoogleObject>(json);
                    matches = googleJson.queries.request[0].totalResults;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(matches);
        }
Exemple #7
0
        public JsonResult SaveSolicitud(GenericEntity <ExpedienteDAutor> model)
        {
            var doc = model.Generic as ExpedienteDAutor; //nombre, pais

            if (doc.Expediente.Id == -1)
            {
                var cronologia = new ModelCronologia(); // footprint separate table
                cronologia.Fecha              = doc.Expediente.FechaDeSolicitud;
                doc.Expediente.EstatusId      = cronologia.EstatusId = (int)DAExpedienteEstatus.Solicitud_Ingresada;
                doc.Expediente.FechaDeEstatus = DateTime.Now;
                cronologia.Referencia         = "";
                cronologia.UsuarioId          = sessionToken.UsuarioId;
                doc.Cronologia = new List <ModelCronologia>();
                doc.Cronologia.Add(cronologia);
            }

            doc.Expediente.ModuloId = (int)Modulos.DERECHO_DE_AUTOR;
            model.Extra             = makeAuditoria(model.Auditoria, (doc.Expediente.Id == 0 ? "Agregó" : "Modificó") + "Expediente", doc.Expediente.Id);

            result = _derechoDeAutorManager.SaveSolicitud(model);
            var expedienteId = (int)result.Result;

            //var solicitud = _expedienteManager.GetExpedienteDerechoAutorPorId(expedienteId);

            //result.Result = new
            //{
            //    documento = solicitud
            //};
            return(new JsonNetResult()
            {
                Data = result
            });
        }
Exemple #8
0
    public IEntity CreateEntity(EntityData ed)
    {
        IEntity entity = new GenericEntity();

        entity.entityPrefabIndex = ed.entityPrefabIndex;

        entity.id     = ed.id;
        entity.health = ed.health;

        GameObject g = Instantiate(entityPrefabs[ed.entityPrefabIndex]);

        entity.gameObject = g;

        g.transform.position    = ed.pos.GetValue();
        g.transform.eulerAngles = ed.rot.GetValue();

        entities.Add(entity);

        if (mode == EntityManagerMode.CLIENT)
        {
            DisableServerSideEntityLogic(g);
        }

        return(entity);
    }
Exemple #9
0
        protected internal virtual ActionResult Edit <TEntityAux>(TEntityAux entityObject) where TEntityAux : class
        {
            if (db.Entry(entityObject).State == EntityState.Detached)
            {
                int        idModel  = GenericEntity.PrimaryKey(entityObject);
                TEntityAux modelAux = this.Find <TEntityAux>(idModel);

                if (db.Set <TEntityAux>().Local.Contains(modelAux))
                {
                    db.Entry(modelAux).CurrentValues.SetValues(entityObject);
                    entityObject = modelAux;
                }
                else
                {
                    db.Set <TEntityAux>().Attach(entityObject);
                    //DbContext.Set(model.GetType()).Attach(model);
                }
            }

            TEntityAux originalValues = (TEntityAux)this.db.Entry <TEntityAux>(entityObject).OriginalValues.ToObject();

            if (!_setting.HandlePermisosEntity(Accion.Edit, originalValues))
            {
                ModelState.AddModelError("Exception", _invalidPermisosText);
            }

            ModelState.Merge(GenericEntity.EditModel(entityObject));
            if (ModelState.IsValid)
            {
                return(RedirectToAction("Index"));
            }

            return(View(entityObject));
        }
Exemple #10
0
        public void GenericEntityListTest()
        {
            GenericEntity <IEntity> genericEntity = new GenericEntity <IEntity>();

            genericEntity.MyList = new List <IEntity>();

            //Brave Sir Robin Security Company
            Entity top1 = new Entity();

            top1.Description = "Brave Sir Robin Security Company";
            top1.Parent      = null;
            top1.EntityLevel = Level.Company;
            genericEntity.MyList.Add(top1);

            GenericEntity <IEntity> genericEntityCopy = new GenericEntity <IEntity>();

            genericEntityCopy.MyList = new List <IEntity>();

            //Brave Sir Robin Security Company
            Entity top2 = new Entity();

            top2.Description = "Brave Sir Robin Security Company";
            top2.Parent      = null;
            top2.EntityLevel = Level.Company;
            genericEntityCopy.MyList.Add(top2);

            Assert.IsTrue(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);

            genericEntityCopy.MyList[0].Description = "When danger reared its ugly head Brave Sir Robin fled.";

            Assert.IsFalse(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);
        }
Exemple #11
0
        /// <summary>
        /// 新增/編輯時, 初始Auditable欄位
        /// </summary>
        /// <returns></returns>
        public override int SaveChanges()
        {
            var modifiedEntries = ChangeTracker.Entries().Where(x => x.Entity is GenericEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));

            foreach (var entry in modifiedEntries)
            {
                GenericEntity entity = entry.Entity as GenericEntity;
                // LogTo.Debug("entity is null:" + (entity == null) + ", entity:" + entity);
                if (entity != null)
                {
                    // 參考: https://stackoverflow.com/questions/36641338/how-get-current-user-in-asp-net-core/36641907
                    string   identityName = GetLoginUser();// httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                    DateTime now          = DateTime.UtcNow;

                    if (entry.State == EntityState.Added)
                    {
                        entity.CreatedUser = identityName;
                        entity.CreatedTime = now;
                    }
                    else
                    {
                        base.Entry(entity).Property(x => x.CreatedUser).IsModified = false;
                        base.Entry(entity).Property(x => x.CreatedTime).IsModified = false;
                    }

                    entity.ModifiedUser = identityName;
                    entity.ModifiedTime = now;
                }
            }

            return(base.SaveChanges());
        }
Exemple #12
0
        public JsonResult SaveTitulares(GenericEntity <TitularEnPatentes> model)
        {
            if (IsAuth)
            {
                var titular = model.Generic as TitularEnPatentes; //nombre, pais
                model.Extra = JObject.Parse(model.jsExtra);

                var patenteTitular = new TitularDeLaPatente()
                {
                    ExpedienteId = model.Extra.ExpedienteId,
                    Direccion    = model.Extra.Direccion,
                    PaisId       = titular.PaisId,
                    TitularId    = titular.Id
                };
                var auditoria = new Auditoria()
                {
                    UsuarioId    = sessionToken.UsuarioId,
                    Evento       = "Agregó Titular",
                    ExpedienteId = patenteTitular.ExpedienteId,
                    Fecha        = DateTime.Now,
                    Historial    = model.Auditoria
                };

                model.Extra = patenteTitular;

                result = _patenteManager.SaveTitulares(model, auditoria);
            }
            return(Json(result, JsonRequestBehavior.DenyGet));
        }
Exemple #13
0
 /// <summary>
 /// Get <see cref="MessageEntity"/> from <see cref="GenericEntity"/>.
 /// </summary>
 /// <param name="rec"></param>
 /// <returns></returns>
 public static DbLiteMessage GetItem(GenericEntity rec)
 {
     using (DbLiteMessageContext db = new DbLiteMessageContext())
     {
         db.Set(rec.Record);
         return(db.Entity);
     }
 }
Exemple #14
0
 public ResultInfo SaveAnualidad(GenericEntity <Anualidad> model)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IPatenteRepository)Repository).SaveAnualidad(model);
         return result;
     }));
 }
Exemple #15
0
 public ResultInfo SaveResumenClasificacion(GenericEntity <Auditoria> model)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IPatenteRepository)Repository).SaveResumenClasificacion(model);
         return result;
     }));
 }
Exemple #16
0
 public ResultInfo DeleteFonogramaArtista(GenericEntity <FonogramaArtista> model)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IDerechoDeAutorRepository)Repository).DeleteFonogramaArtista(model);
         return result;
     }));
 }
Exemple #17
0
 public ResultInfo SaveFonogramaTituloDeObra(GenericEntity <FonogramaTituloDeObra> model)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IDerechoDeAutorRepository)Repository).SaveFonogramaTituloDeObra(model);
         return result;
     }));
 }
Exemple #18
0
 public ResultInfo SaveAutor(GenericEntity <Autor> model)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IDerechoDeAutorRepository)Repository).SaveAutor(model);
         return result;
     }));
 }
Exemple #19
0
 public ResultInfo SaveTitulares(GenericEntity <TitularEnPatentes> model, Auditoria auditoria)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IPatenteRepository)Repository).SaveTitulares(model, auditoria);
         return result;
     }));
 }
Exemple #20
0
 public ResultInfo DeleteReferencia(GenericEntity <Prioridad> model)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IPatenteRepository)Repository).DeleteReferencia(model);
         return result;
     }));
 }
Exemple #21
0
 private void Start()
 {
     // Set INV to our inventory.
     ID_UTIL  = GameManager.Instance.ID_UTILITY;
     ENT_UTIL = GameManager.Instance.ENTITY_UTILITY;
     INFO     = GetComponent <EntityController>().INFO;
     INV      = GetComponent <Inventory>();
 }
Exemple #22
0
 public ResultInfo SaveInventor(GenericEntity <Inventor> model, Auditoria auditoria)
 {
     return(_transaction.ExecuteInTransactionScope <ResultInfo>(() =>
     {
         var result = ((IInventorRepository)Repository).SaveInventor(model, auditoria);
         return result;
     }));
 }
Exemple #23
0
        public JsonResult DeleteComposicionAutor(GenericEntity <ComposicionAutor> model)
        {
            var entry = model.Generic as ComposicionAutor; //ComposicionAutor data

            model.Extra = makeAuditoria(model.Auditoria, "Eliminó ComposicionAutor", entry.ExpedienteId);

            result = _derechoDeAutorManager.DeleteComposicionAutor(model);
            return(Json(result, JsonRequestBehavior.DenyGet));
        }
        /// <summary>
        /// Método que ayuda a añadir motores de busqueda
        /// </summary>
        /// <param name="name">nombre del motor de busqueda</param>
        /// <param name="word">palabra a buscar</param>
        /// <returns>retorna el tipo  que se añadira a la lista</returns>
        public GenericEntity addList(string name, string word)
        {
            GenericEntity genericEntity = new GenericEntity();

            genericEntity.name = name;
            genericEntity.q    = word;

            return(genericEntity);
        }
Exemple #25
0
        public JsonResult DeleteFonogramaArtista(GenericEntity <FonogramaArtista> model)
        {
            var entry = model.Generic as FonogramaArtista; //FonogramaArtista data

            model.Extra = makeAuditoria(model.Auditoria, "Eliminó FonogramaArtista", entry.ExpedienteId);

            result = _derechoDeAutorManager.DeleteFonogramaArtista(model);
            return(Json(result, JsonRequestBehavior.DenyGet));
        }
Exemple #26
0
        public JsonResult DeleteAutor(GenericEntity <Autor> model)
        {
            var autor = model.Generic as Autor; //Autor data

            model.Extra = makeAuditoria(model.Auditoria, "Eliminó Autor", autor.ExpedienteId);

            result = _derechoDeAutorManager.DeleteAutor(model);
            return(Json(result, JsonRequestBehavior.DenyGet));
        }
Exemple #27
0
        public static IEnumerable <GenericEntity> QueryGeneric2(this DbConnection connection, string commandText, object paramaters, DbTransaction transaction = null, IExceptionProcessor exceptionProcessor = null)
        {
            using (var command = connection.CreateCommand())
            {
                command.CommandText = commandText;
                command.AddParams(paramaters);

                using (var reader = connection.ExecuteReader(command, transaction: transaction, exceptionProcessor: exceptionProcessor))
                {
                    while (reader.Read())
                    {
                        var fieldCount = reader.FieldCount;
                        var fields     = new string[fieldCount];
                        for (int i = 0; i < fieldCount; i++)
                        {
                            fields[i] = reader.GetName(i);
                        }

                        var data = new GenericEntity(fieldCount);

                        try
                        {
                            foreach (var x in fields.Select((field, i) => new { field, i }))
                            {
                                try
                                {
                                    var value = reader.GetValue(x.i);
                                    data.Add(x.field, value);
                                }
                                catch (FormatException)
                                {
                                    // if a value is saved as a string
                                    // but the column type of different

                                    var value = reader.GetString(x.i);
                                    data.Add(x.field, value);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            if (exceptionProcessor is null)
                            {
                                throw;
                            }
                            else
                            {
                                throw exceptionProcessor.ProcessException(e, connection, commandText, transaction);
                            }
                        }

                        yield return(data);
                    }
                }
            }
        }
 public void SuccessTest()
 {
     using (var session = Domain.OpenSession())
         using (var tx = session.OpenTransaction()) {
             var entity = new GenericEntity <long>();
             entity.Name  = entity.Id.ToString();
             entity.Value = 5;
             tx.Complete();
         }
 }
Exemple #29
0
        protected internal virtual ActionResult Delete <TEntityAux>(TEntityAux entityObject) where TEntityAux : class
        {
            if (!_setting.HandlePermisosEntity(Accion.Delete, entityObject))
            {
                ModelState.AddModelError("Exception", _invalidPermisosText);
            }

            ModelState.Merge(GenericEntity.DeleteModel(entityObject));
            return(ModelStateToJSonResult());
        }
        public void CreateInstanceFromProperties_TargetTypeDecoratedWithRowAndPartitionKeyAttributes_RowAndPartitionKeySetCorrectly()
        {
            var genericEntity = new GenericEntity();
             genericEntity.PartitionKey = "foo";
             genericEntity.RowKey = "bar";
             genericEntity["Age"] = new EntityPropertyInfo( 42, typeof( int ), false );

             var item = genericEntity.CreateInstanceFromProperties<DecoratedItem>();
             Assert.AreEqual<string>( "foo", item.Id, "Incorrect partition key" );
             Assert.AreEqual<string>( "bar", item.Name, "Incorrect row key" );
        }
Exemple #31
0
        public static void StringTo <T>(T value)
        {
            var srcEntity = new GenericEntity <string>
            {
                Val = GetString(value)
            };

            var destEntity = new Mapper().Map <GenericEntity <string>, GenericEntity <T> >(srcEntity);

            destEntity.Val.Should().Be(value);
        }
Exemple #32
0
        public void Update( string partitionKey, string rowKey, Guid callerInstanceId, GenericEntity entity )
        {
            bool entityExists = HasEntity( partitionKey, rowKey );
             if ( !entityExists )
             {
            throw new EntityDoesNotExistException();
             }

             var actualEntity = TableEntries.Single( e => EntryKeysMatch( partitionKey, rowKey, e ) );

             Dictionary<string, object> serializedData = entity.GetProperties().ToDictionary( kp => kp.Key, kp => kp.Value.Value );
             actualEntity.Value.Modify( callerInstanceId, serializedData );
        }
Exemple #33
0
        public void Add( string partitionKey, string rowKey, Guid callerInstanceId, GenericEntity entity )
        {
            Dictionary<string, object> properties = entity.GetProperties().ToDictionary( kp => kp.Key, kp => kp.Value.Value );

             var tableServiceEntity = new TableServiceEntity( partitionKey, rowKey );

             var entry = new MemoryTableEntry( properties, callerInstanceId );

             if ( HasEntity( partitionKey, rowKey ) )
             {
            throw new EntityAlreadyExistsException();
             }
             _tableEntries[tableServiceEntity] = entry;
        }
        public void TestNullable()
        {
            IQueryable<GenericEntity> entities = new GenericEntity[]
            {
                new GenericEntity { Key = 1, Title = "Manager", NullableInt = null },
                new GenericEntity { Key = 2, Title = "Supervisor", NullableInt = -5 },
                new GenericEntity { Key = 3, Title = "Supervisor", NullableInt = 5 }
            }.AsQueryable();

            // We don't currently support the delegate syntax. Once we add support for this, we should 
            // uncomment the following code.
            /*// Where (item.NullableInt > 0)
            IQueryable<GenericEntity> q = (IQueryable<GenericEntity>)Expressions.NullComparison1(entities);
            List<ServiceQueryPart> queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.NullableInt>0)", queryParts.Single().Expression);
            IQueryable<GenericEntity> q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            
            // We don't execute the 'q' query because it'll fail when there are null ints. That's by-VB-design.
            Assert.AreEqual(1, q2.Count());
            Assert.AreEqual(5, q2.First().NullableInt);*/

            // Where (item.NullableInt > 0) (uses LINQ syntax)
            IQueryable<GenericEntity> q = (IQueryable<GenericEntity>)Expressions.NullComparison2(entities);
            List<ServiceQueryPart> queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.NullableInt>0)", queryParts.Single().Expression);
            IQueryable<GenericEntity> q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            int c1 = q.Count();
            int c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);
            Assert.AreEqual(5, q2.First().NullableInt);

            // Where (item.NullableInt > item.Key) (uses LINQ syntax)
            q = (IQueryable<GenericEntity>)Expressions.NullComparison3(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.NullableInt>it.Key)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);
            Assert.AreEqual(5, q2.First().NullableInt);
        }
        public void TestVBCompareString()
        {
            IQueryable<GenericEntity> entities = new GenericEntity[]
            {
                new GenericEntity { Title = "Manager" },
                new GenericEntity { Title = "Peon" },
                new GenericEntity { Title = "Supreme Leader" },
                new GenericEntity { Title = "X" },
                new GenericEntity { Title = null }
            }.AsQueryable();

            // VB string comparison EQ
            IQueryable<GenericEntity> q = (IQueryable<GenericEntity>)StringComparisons.CompareStringEqual(entities);
            List<ServiceQueryPart> queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.Title==\"Supreme Leader\")", queryParts.Single().Expression);
            IQueryable<GenericEntity> q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            int c1 = q.Count();
            int c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // VB string comparison EQ (case insensitive)
            q = (IQueryable<GenericEntity>)StringComparisonsCaseInsensitive.CompareStringEqualCaseInsensitive(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(String.Compare(it.Title, \"peon\", StringComparison.OrdinalIgnoreCase)==0)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // VB string comparison NE
            q = (IQueryable<GenericEntity>)StringComparisons.CompareStringNotEqual(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.Title!=\"Supreme Leader\")", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // VB string comparison GT
            q = (IQueryable<GenericEntity>)StringComparisons.CompareStringGreaterThan(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(String.Compare(it.Title, \"Supreme Leader\")>0)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // VB string comparison GTE
            q = (IQueryable<GenericEntity>)StringComparisons.CompareStringGreaterThanOrEqual(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(String.Compare(it.Title, \"Supreme Leader\")>=0)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // VB string comparison LT
            q = (IQueryable<GenericEntity>)StringComparisons.CompareStringLessThan(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(String.Compare(it.Title, \"Supreme Leader\")<0)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // VB string comparison LTE
            q = (IQueryable<GenericEntity>)StringComparisons.CompareStringLessThanOrEqual(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(String.Compare(it.Title, \"Supreme Leader\")<=0)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);
        }
        public void Put(string tableName, string id, Dictionary<string, string> properties, bool replace = false)
        {
            _serviceContext.WritingEntity += OnWritingEntity;

            var entity = new GenericEntity();
            foreach (var propertyPair in properties)
            {
                entity[propertyPair.Key] = propertyPair.Value;
            }

            entity.PartitionKey = "SomePartition";
            entity.RowKey = id;

            _serviceContext.AddObject(tableName, entity);
            _serviceContext.SaveChanges();

            _serviceContext.WritingEntity -= OnWritingEntity;
        }
        public void GenericEntityListMultipleItemsTest()
        {
            GenericEntity<IEntity> genericEntity = new GenericEntity<IEntity>();
            genericEntity.MyList = new List<IEntity>();

            //Brave Sir Robin Security Company
            Entity top1 = new Entity();
            top1.Description = "Brave Sir Robin Security Company";
            top1.Parent = null;
            top1.EntityLevel = Level.Company;

            GenericEntity<IEntity> genericEntityCopy = new GenericEntity<IEntity>();
            genericEntityCopy.MyList = new List<IEntity>();

            //Brave Sir Robin Security Company
            Entity top2 = new Entity();
            top2.Description = "Brave Sir Robin Security Company";
            top2.Parent = null;
            top2.EntityLevel = Level.Company;


            Entity top3 = new Entity();
            top3.Description = "May I obey all your commands with equal pleasure, Sire!";
            top3.Parent = null;
            top3.EntityLevel = Level.Department;


            genericEntity.MyList.Add(top1);
            genericEntity.MyList.Add(top3);
            genericEntityCopy.MyList.Add(top2);
            genericEntityCopy.MyList.Add(top3);

            Assert.IsTrue(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);

            genericEntityCopy.MyList[0].Description = "When danger reared its ugly head Brave Sir Robin fled.";

            Assert.IsFalse(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);
        }
        public void GenericEntityListTest()
        {
            GenericEntity<IEntity> genericEntity = new GenericEntity<IEntity>();
            genericEntity.MyList = new List<IEntity>();

            //Brave Sir Robin Security Company
            Entity top1 = new Entity();
            top1.Description = "Brave Sir Robin Security Company";
            top1.Parent = null;
            top1.EntityLevel = Level.Company;
            genericEntity.MyList.Add(top1);

            GenericEntity<IEntity> genericEntityCopy = new GenericEntity<IEntity>();
            genericEntityCopy.MyList = new List<IEntity>();

            //Brave Sir Robin Security Company
            Entity top2 = new Entity();
            top2.Description = "Brave Sir Robin Security Company";
            top2.Parent = null;
            top2.EntityLevel = Level.Company;
            genericEntityCopy.MyList.Add(top2);

            Assert.IsTrue(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);

            genericEntityCopy.MyList[0].Description = "When danger reared its ugly head Brave Sir Robin fled.";

            Assert.IsFalse(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);
        }
Exemple #39
0
        private static void UpdateTaskFields(ClarizenUtils utils, string csvReadFile, string targetType)
        {
            try
            {
                using (var csv = new CsvParser(new StreamReader(csvReadFile)))
                {
                    int rowIndex = 0;
                    while (csv.ReadNextRecord())
                    {
                        foreach (string field in csv.HeaderFields)
                        {
                            if (field.Equals("TASKID", StringComparison.InvariantCultureIgnoreCase)) continue;

                            object newValue = ParseValue(csv.CurrentDic[field], field);

                            var task = new GenericEntity
                                           {
                                               Id =
                                                   new EntityId
                                                       {TypeName = targetType, Value = csv.CurrentDic["TASKID"]}
                                           };
                            //Create a FieldValue representing the Manager field
                            var managerField = new FieldValue {FieldName = field, Value = newValue};
                            //Set the field value to the external identifier of the new manager
                            task.Values = new[] {managerField};
                            var updateMsg = new UpdateMessage {Entity = task};
                            //Update the entity
                            Result result = utils.ExecuteQuery(new BaseMessage[] {updateMsg});

                            string dir = Path.GetDirectoryName(csvReadFile);
                            if (dir == null) throw new ArgumentNullException("csvReadFile");
                            dir = Path.Combine(dir, "Handled");
                            if (!Directory.Exists(dir))
                                Directory.CreateDirectory(dir);
                            string resultFileName = Path.Combine(dir,
                                                                 string.Format("{0}_Result_{1}.csv",
                                                                               Path.GetFileNameWithoutExtension(
                                                                                   csvReadFile),
                                                                               rowIndex));
                            string combineText = result.Success ? "Success" : "Failure";
                            File.WriteAllText(resultFileName, combineText);
                            string p = Path.GetDirectoryName(csvReadFile);
                            string d = Path.GetFileName(csvReadFile);
                            if (p != null)
                            {
                                if (d != null)
                                {
                                    string destFileName = Path.Combine(Path.Combine(p, "Handled"), d);
                                    if (File.Exists(destFileName))
                                        File.Delete(destFileName);
                                    File.Move(csvReadFile, destFileName);
                                }
                            }
                        }
                        rowIndex++;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("File:{0}\r\n{1}\r\n", csvReadFile, ex));
            }
        }
        public void GenericEntityListMultipleItemsOddOrderTest()
        {
            GenericEntity<IEntity> genericEntity = new GenericEntity<IEntity>();
            genericEntity.MyList = new List<IEntity>();

            GenericEntity<IEntity> genericEntityCopy = new GenericEntity<IEntity>();
            genericEntityCopy.MyList = new List<IEntity>();

            //Brave Sir Robin Security Company
            Entity top1 = new Entity();
            top1.Description = "Brave Sir Robin Security Company";
            top1.Parent = null;
            top1.EntityLevel = Level.Company;

            //Brave Sir Robin Security Company
            Entity top2 = new Entity();
            top2.Description = "Brave Sir Robin Security Company";
            top2.Parent = null;
            top2.EntityLevel = Level.Company;

            //Brave Sir Robin Security Company
            Entity top5 = new Entity();
            top5.Description = "Brave Sir Robin Security Company";
            top5.Parent = null;
            top5.EntityLevel = Level.Company;

            Entity top3 = new Entity();
            top3.Description = "May I obey all your commands with equal pleasure, Sire!";
            top3.Parent = null;
            top3.EntityLevel = Level.Department;

            Entity top4 = new Entity();
            top4.Description = "Overtaxed, overworked and paid off with a knife, a club or a rope.";
            top4.Parent = null;
            top4.EntityLevel = Level.Department;


            genericEntity.MyList.Add(top4);
            genericEntity.MyList.Add(top3);
            genericEntity.MyList.Add(top5);
            genericEntity.MyList.Add(top2);
            genericEntityCopy.MyList.Add(top2);
            genericEntityCopy.MyList.Add(top1);
            genericEntityCopy.MyList.Add(top3);
            genericEntityCopy.MyList.Add(top4);

            _compare.Config.IgnoreCollectionOrder = true;

            var result = _compare.Compare(genericEntity, genericEntityCopy);

            Console.WriteLine(result.DifferencesString);

            Assert.IsTrue(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);

            genericEntity.MyList[2].Description = "When danger reared its ugly head Brave Sir Robin fled.";

            Assert.IsFalse(_compare.Compare(genericEntity, genericEntityCopy).AreEqual);
        }
        public void TestVBCheckedExpressions()
        {
            IQueryable<GenericEntity> entities = new GenericEntity[]
            {
                new GenericEntity { Key = 1, Title = "Manager" },
                new GenericEntity { Key = 2, Title = "Supervisor" }
            }.AsQueryable();

            // Where (item.Key + -1 = 0)
            IQueryable<GenericEntity> q = (IQueryable<GenericEntity>)Expressions.AddAndNegateChecked(entities);
            List<ServiceQueryPart> queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("((it.Key+-1)==0)", queryParts.Single().Expression);
            IQueryable<GenericEntity> q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            int c1 = q.Count();
            int c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);
            Assert.AreEqual("Manager", q2.First().Title);

            // Where (item.Key - 1 = 0)
            q = (IQueryable<GenericEntity>)Expressions.SubtractChecked(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("((it.Key-1)==0)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);
            Assert.AreEqual("Manager", q2.First().Title);

            // Where (item.Key * 1 = 1)
            q = (IQueryable<GenericEntity>)Expressions.MultiplyChecked(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("((it.Key*1)==1)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);
            Assert.AreEqual("Manager", q2.First().Title);

            // Where (CType(item.Key, Single) = 1)
            q = (IQueryable<GenericEntity>)Expressions.ConvertChecked(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.Key==1F)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);
            Assert.AreEqual("Manager", q2.First().Title);
        }
        public void TestVBIIf()
        {
            IQueryable<GenericEntity> entities = new GenericEntity[]
            {
                new GenericEntity { Title = "Manager" },
                new GenericEntity { Title = "Peon" },
                new GenericEntity { Title = "Supreme Leader" },
                new GenericEntity { Title = "X" },
                new GenericEntity { Title = null }
            }.AsQueryable();

            // Where (IIf(item.Title = "Supreme Leader", 1, 0) = 1)
            IQueryable<GenericEntity> q = (IQueryable<GenericEntity>)Expressions.IIfWithEqualComparison(entities);
            List<ServiceQueryPart> queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(iif((it.Title==\"Supreme Leader\"),1,0)==1)", queryParts.Single().Expression);
            IQueryable<GenericEntity> q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            int c1 = q.Count();
            int c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // Where (IIf(item.Title = "Supreme Leader", True, False))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithEqualComparisonWithBools(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("iif((it.Title==\"Supreme Leader\"),True,False)", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // Where (1 <> IIf(item.Title = "Supreme Leader", 1, 0))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithNotEqualComparison(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(1!=iif((it.Title==\"Supreme Leader\"),1,0))", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // Where (1 < IIf(item.Title = "Supreme Leader", 1, 0))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithLessThanComparison(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(1<iif((it.Title==\"Supreme Leader\"),1,0))", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // Where (1 >= IIf(item.Title = "Supreme Leader", 1, 0))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithGreaterThanOrEqualComparison(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(1>=iif((it.Title==\"Supreme Leader\"),1,0))", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // Where (1 > IIf(item.Title = "Supreme Leader", 1, 0))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithGreaterThanComparison(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(1>iif((it.Title==\"Supreme Leader\"),1,0))", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // Where (1 <= IIf(item.Title = "Supreme Leader", 1, 0))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithLessThanOrEqualComparison(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(1<=iif((it.Title==\"Supreme Leader\"),1,0))", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);

            // Where ("1" < IIf(item.Title = "Supreme Leader", "1", "0"))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithLessThanStringComparison(entities);
            ExceptionHelper.ExpectInvalidOperationException(delegate
            {
                QuerySerializer.Serialize(q);
            }, "The binary operator LessThan is not defined for the types 'System.String' and 'System.String'.");

            // Where ("1" = IIf(item.Title = "Supreme Leader", "1", "0"))
            q = (IQueryable<GenericEntity>)Expressions.IIfWithEqualStringComparison(entities);
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(\"1\"==iif((it.Title==\"Supreme Leader\"),\"1\",\"0\"))", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(c1, c2);
        }
        public void TestEscapingInStrings()
        {
            IQueryable<GenericEntity> entities = new GenericEntity[]
            {
                new GenericEntity { Title = "Supreme \"Leader\"" },
                new GenericEntity { Title = "Supreme \\\"Leader\\\"" },
                new GenericEntity { Title = "Supreme \'Leader\'" },
                new GenericEntity { Title = null }
            }.AsQueryable();

            IQueryable<GenericEntity> q = entities.Where(e => e.Title == "Supreme \"Leader\"");
            List<ServiceQueryPart> queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.Title==\"Supreme \\\"Leader\\\"\")", queryParts.Single().Expression);
            IQueryable<GenericEntity> q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            int c1 = q.Count();
            int c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);

            q = entities.Where(e => e.Title == "Supreme \\\"Leader\\\"");
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.Title==\"Supreme \\\\\\\"Leader\\\\\\\"\")", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);

            q = entities.Where(e => e.Title == "Supreme \'Leader\'");
            queryParts = QuerySerializer.Serialize(q);
            Assert.AreEqual("(it.Title==\"Supreme \'Leader\'\")", queryParts.Single().Expression);
            q2 = (IQueryable<GenericEntity>)RoundtripQuery(q, entities);
            c1 = q.Count();
            c2 = q2.Count();
            Assert.AreEqual(1, c1);
            Assert.AreEqual(c1, c2);
        }