예제 #1
0
        private static void BorrarPruebas(Crm crm, Comun co)
        {
            #region BORRAR PRODUCTOS
            var queprod = new QueryExpression("product");
            //quece.TopCount = 5000;

            var prods = new EntityCollection();
            while (true)
            {
                var res1 = crm.GetIOS().RetrieveMultiple(queprod);
                prods.Entities.AddRange(res1.Entities);
                if (res1.MoreRecords)
                {
                    queprod.PageInfo.PageNumber++;
                    queprod.PageInfo.PagingCookie = res1.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var ce in prods.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("product", ce.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion BORRAR PRODuCTOS
            co.LogText("\n=============================== PRODUCTOS  BORRADOS ===================================\n");
        }
예제 #2
0
        private void BorrarDirecciones()
        {
            var q = new QueryExpression("aen_direccion");

            q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            while (true)
            {
                var entidades = Crm.IOS.RetrieveMultiple(q);
                foreach (var t in entidades.Entities)
                {
                    Crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("aen_direccion", t.Id)
                    });
                }
                if (entidades.MoreRecords)
                {
                    q.PageInfo.PageNumber++;
                    q.PageInfo.PagingCookie = entidades.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            Crm.ProcesarUltimosEmr();
        }
예제 #3
0
        private static void BorrarPrueba()
        {
            var q = new QueryExpression("account");

            q.Criteria.Conditions.AddRange(
                new ConditionExpression("aen_nombrejuridico", ConditionOperator.BeginsWith, "ejemplo_cuenta_")
                );
            var terceros = new EntityCollection();

            while (true)
            {
                var res = IOS.RetrieveMultiple(q);
                terceros.Entities.AddRange(res.Entities);
                if (res.MoreRecords)
                {
                    q.PageInfo.PageNumber++;
                    q.PageInfo.PagingCookie = res.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var t in terceros.Entities)
            {
                Crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("account", t.Id)
                });
            }
            Crm.ProcesarUltimosEmr();
        }
예제 #4
0
        private static void BorrarPrueba(Crm crm)
        {
            var q = new QueryExpression("account");

            q.Criteria.Conditions.AddRange(
                new ConditionExpression("createdon", ConditionOperator.Today)
                );
            var terceros = new EntityCollection();

            while (true)
            {
                var res = crm.GetIOS().RetrieveMultiple(q);
                terceros.Entities.AddRange(res.Entities);
                if (res.MoreRecords)
                {
                    q.PageInfo.PageNumber++;
                    q.PageInfo.PagingCookie = res.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var t in terceros.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("account", t.Id)
                });
            }
            crm.ProcesarUltimosEmr();
        }
예제 #5
0
        private void SincronizarEmparentamiento()
        {
            var q = new QueryExpression("aen_comitenormalizacion");

            q.ColumnSet = new ColumnSet("aen_name", "aen_comitepadre");
            q.Criteria.Conditions.AddRange(
                new ConditionExpression("aen_name", ConditionOperator.NotNull));
            q.PageInfo = new PagingInfo()
            {
                Count = 5000, PageNumber = 1
            };
            while (true)
            {
                var entidades = Crm.IOS.RetrieveMultiple(q);
                foreach (var e in entidades.Entities)
                {
                    ComitesHijosPadreCRM.Add(e.Id,
                                             e.Contains("aen_comitepadre") ? ((EntityReference)e["aen_comitepadre"]).Id : Guid.Empty);
                    ComitesHijosPadreCRMNombres.Add((string)e["aen_name"],
                                                    e.Contains("aen_comitepadre") ? ((EntityReference)e["aen_comitepadre"]).Id : Guid.Empty);
                }
                if (entidades.MoreRecords)
                {
                    q.PageInfo.PageNumber++;
                    q.PageInfo.PagingCookie = entidades.PagingCookie;
                }
                else
                {
                    break;
                }
            }

            foreach (var c in ComitesNormalizacionOracle)
            {
                var idComitePadreOra = c.Value.Aen_ComitePadreId;
                var idComitepadreCrm = ComitesHijosPadreCRMNombres[c.Key];
                if (idComitepadreCrm != idComitePadreOra)
                {
                    var comite = new Entity("aen_comitenormalizacion");
                    comite["aen_comitepadre"] = idComitePadreOra == Guid.Empty ? null :
                                                new EntityReference("aen_comitenormalizacion", idComitepadreCrm);
                    Crm.AnadirElementoEmr(new UpdateRequest {
                        Target = comite
                    });
                }
            }
            Crm.ProcesarUltimosEmr();
        }
예제 #6
0
        static void Main(string[] args)
        {
            var Comun = new Comun();

            Comun.LogText("Inicio prueba");
            Comun.InicializarVariables();
            Crm       = new Crm();
            Crm.Comun = Comun;
            Crm.InicializarPFE();

            //GetD365_9x_Connection(ref IOS, RequestUrlDES, UserNameDES, UserPasswordDES);
            //IOS = InstanciaCRM(RequestUrlPRE, UserNamePRE, UserPasswordPRE);
            //InicializaEMR();
            //Connect655_SDK(ref IOS, RequestUrlPRE, UserNamePRE, UserPasswordPRE);

            //Uso de multihilo
            //ServicePointManager.UseNagleAlgorithm = true;
            //ServicePointManager.Expect100Continue = true;
            //ServicePointManager.CheckCertificateRevocationList = true;
            //ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;
            ServicePointManager.DefaultConnectionLimit = Comun.DefaultConnectionLimit;
            //BorrarPrueba();

            //1. Carga desde fichero 1000 registros en memoria
            cuentas_a_cargar = new List <Entity>();
            CargaCuentasFromArchivo(ref cuentas_a_cargar);

            //2. Esos registros, con MultipleRequest, incluirlos en 'Terceros' (Accounts)
            Stopwatch stopWatch2 = new Stopwatch();

            stopWatch2.Start();
            foreach (Entity ter in cuentas_a_cargar)
            {
                //AnadirElementoEmr(new CreateRequest { Target = ter });
                Crm.AnadirElementoEmr(new CreateRequest {
                    Target = ter
                });
            }
            //ProcesarUltimosEmr();
            Crm.ProcesarUltimosEmr();
            stopWatch2.Stop();
            Comun.LogText("Tamaño de buffer y tiempo " + BufferEmr + "\t" + stopWatch2.Elapsed.ToString());
        }
예제 #7
0
        private void DesactivarRecienCreadosInactivas()
        {
            var q = new QueryExpression("aen_comitenormalizacion");

            q.ColumnSet = new ColumnSet("aen_name");
            q.Criteria.AddCondition(
                new ConditionExpression("aen_name", ConditionOperator.NotNull));
            q.PageInfo = new PagingInfo()
            {
                Count = 5000, PageNumber = 1
            };
            while (true)
            {
                var entidades = Crm.IOS.RetrieveMultiple(q);
                foreach (var e in entidades.Entities)
                {
                    var claveInt = (string)e["aen_name"];
                    if (ComitesDesactivar.Contains(claveInt))
                    {
                        var dir = new Entity("aen_comitenormalizacion");
                        dir["aen_comitenormalizacionid"] = e.Id;
                        dir["statecode"]  = new OptionSetValue(1);
                        dir["statuscode"] = new OptionSetValue(2);
                        Crm.AnadirElementoEmr(new UpdateRequest {
                            Target = dir
                        });
                    }
                }
                if (entidades.MoreRecords)
                {
                    q.PageInfo.PageNumber++;
                    q.PageInfo.PagingCookie = entidades.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            Crm.ProcesarUltimosEmr();
        }
예제 #8
0
        public void Iniciar(Oracle oracleGlobal, Comun comunGlobal, Crm crmGlobal)
        {
            try
            {
                //Aquí no hay que hacer new, el lanzador orquestador lo pasará a las properties
                Comun = comunGlobal;
                Comun.LogText("----Iniciando sincronización comités normalizacion------");
                Crm = crmGlobal;
                ComitesDesactivar = new HashSet <string>();

                Oracle = oracleGlobal;
                Crm.InicializarPFE(oracleGlobal);

                LeerEntidades();
                LeerComitesOracle();
                if (!ComitesNormalizacionOracle.Any())
                {
                    Comun.LogText("No hay comités en origen, terminamos");
                    return;
                }


                foreach (var comiteOra in ComitesNormalizacionOracle)
                {
                    try
                    {
                        ClaveIntegracionActual = comiteOra.Key;
                        bool ok = ComitesNormalizacionCRM.TryGetValue(comiteOra.Key, out ComiteNormalizacion comiteCRM);
                        if (ok && ComitesIguales(comiteOra.Value, comiteCRM))
                        {
                            Crm.Iguales++;
                            continue;
                        }
                        var comite = GetEntity(comiteOra.Value);
                        if (ok)
                        {
                            comite["aen_comitenormalizacionid"] = comiteCRM.Aen_ComiteNormalizacionId;
                            Crm.AnadirElementoEmr(new UpdateRequest {
                                Target = comite
                            });
                        }
                        else
                        {
                            if (comiteOra.Value.StateCode == "Inactivo")
                            {
                                comite["statecode"]  = new OptionSetValue(0);
                                comite["statuscode"] = new OptionSetValue(1);
                                ComitesDesactivar.Add(comiteOra.Value.Aen_Name);
                            }
                            Crm.AnadirElementoEmr(new CreateRequest {
                                Target = comite
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Comun.EscribirExcepcion(e, "Error al procesar Comité: " + comiteOra.Key);
                    }
                }
                Crm.ProcesarUltimosEmr();

                SincronizarEmparentamiento();
                DesactivarRecienCreadosInactivas();
                Crm.MostrarEstadisticas("COMITES");
            }
            catch (Exception ex)
            {
                Comun.EscribirExcepcion(ex, "Error");
                if (ClaveIntegracionActual != "")
                {
                    Oracle.MandarErrorIntegracion(ClaveIntegracionActual, ex.Message,
                                                  Oracle.TipoEntidadDireccion, Oracle.TipoAccionValidacion, null);
                }
                if (Oracle != null && Oracle.OraConnParaLog.State == ConnectionState.Open)
                {
                    Oracle.OraConnParaLog.Dispose();
                }
            }
            finally
            {
                if (Oracle != null && Oracle.OraConnParaLog.State == ConnectionState.Open)
                {
                    Oracle.OraConnParaLog.Dispose();
                }
            }
        }
예제 #9
0
        private static void BorrarPruebas(Crm crm, Comun co)
        {
            #region BORRAR PRODUCTOS
            var queprod = new QueryExpression("product");
            //quece.TopCount = 5000;

            var prods = new EntityCollection();
            while (true)
            {
                var res1 = crm.GetIOS().RetrieveMultiple(queprod);
                prods.Entities.AddRange(res1.Entities);
                if (res1.MoreRecords)
                {
                    queprod.PageInfo.PageNumber++;
                    queprod.PageInfo.PagingCookie = res1.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var ce in prods.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("product", ce.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion BORRAR PRODuCTOS
            co.LogText("\n=============================== PRODUCTOS  BORRADOS ===================================\n");

            #region BORRAR ICS
            var queics = new QueryExpression("aen_ics");
            //quece.TopCount = 5000;

            var icss = new EntityCollection();
            while (true)
            {
                var res1 = crm.GetIOS().RetrieveMultiple(queics);
                icss.Entities.AddRange(res1.Entities);
                if (res1.MoreRecords)
                {
                    queics.PageInfo.PageNumber++;
                    queics.PageInfo.PagingCookie = res1.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var ce in icss.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("aen_ics", ce.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion BORRAR ICS
            co.LogText("\n=============================== ICS  BORRADOS ===================================\n");

            #region BORRAR VERSION
            var quever = new QueryExpression("aen_versin");
            //quece.TopCount = 5000;

            var vers = new EntityCollection();
            while (true)
            {
                var res1 = crm.GetIOS().RetrieveMultiple(quever);
                vers.Entities.AddRange(res1.Entities);
                if (res1.MoreRecords)
                {
                    quever.PageInfo.PageNumber++;
                    quever.PageInfo.PagingCookie = res1.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var ce in vers.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("aen_versin", ce.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion BORRAR VERSION
            co.LogText("\n=============================== VERSION  BORRADAS ===================================\n");

            #region BORRAR NORMA RAIZ
            var quenor = new QueryExpression("aen_norma");
            //quece.TopCount = 5000;

            var norm = new EntityCollection();
            while (true)
            {
                var res1 = crm.GetIOS().RetrieveMultiple(quenor);
                norm.Entities.AddRange(res1.Entities);
                if (res1.MoreRecords)
                {
                    quenor.PageInfo.PageNumber++;
                    quenor.PageInfo.PagingCookie = res1.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var ce in norm.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("aen_norma", ce.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion BORRAR VERSION
            co.LogText("\n=============================== NORMAS  BORRADAS ===================================\n");

            #region BORRAR COMITES
            var quecom = new QueryExpression("aen_comitetecnicodenormalizacion");
            //quece.TopCount = 5000;

            var com = new EntityCollection();
            while (true)
            {
                var res1 = crm.GetIOS().RetrieveMultiple(quecom);
                com.Entities.AddRange(res1.Entities);
                if (res1.MoreRecords)
                {
                    quecom.PageInfo.PageNumber++;
                    quecom.PageInfo.PagingCookie = res1.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var ce in com.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("aen_comitetecnicodenormalizacion", ce.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion BORRAR COMITES
            co.LogText("\n=============================== COMITES  BORRADAS ===================================\n");
        }
예제 #10
0
        public void Iniciar(Oracle ora, Comun com, Crm crm)
        {
            try
            {
                Stopwatch sW_TODO = new Stopwatch(), sW_SOLOCARGA = new Stopwatch();
                OracleGlobal = ora;
                ComunGlobal  = com;
                ComunGlobal.LogText("----Iniciando sincronización contactos------");
                CrmGlobal = crm;

                ContactosADesactivar = new List <string>();

                sW_TODO.Start();

                //1. Carga Maestros
                CargarMaestroCargos();
                //2.A Carga de Terceros para campo Parentcustomerid/aen_claveintegracionparent
                //2.B Carga de Contactos existentes
                CargarMaestroTercerosFromCRM();
                CargarMaestroContactos();


                //3. Lectura de Contactos de la tabla de Oracle (Query: oracleGlobal.QueryContactos)
                LeerContactosOracle();
                if (!ContactosOracle.Any())
                {
                    ComunGlobal.LogText("No hay contactos en origen, terminamos");
                    return;
                }


                //4. Inicializa PFECore
                CrmGlobal.InicializarPFE(OracleGlobal);


                //5. Procesamos Contactos de Oracle:
                //  -> Si existen, comprobamos campo a campo si hay que actualizar
                //  -> Sino existen, creamos el contacto nuevo.
                sW_SOLOCARGA.Start();
                #region Procesar CONTACTOS
                bool      ok;
                Contactos auxContCRM = new Contactos();
                Entity    contUpdate;

                foreach (var cont in ContactosOracle)
                {
                    ok = ContactosCRM.TryGetValue(cont.Key, out auxContCRM);

                    if (ok)
                    { //Existe, comprobamos actualizacion
                        try
                        {
                            contUpdate = new Entity("contact");

                            bool ret = cont.Value.ContactosIguales(auxContCRM, ref contUpdate);

                            if (ret)
                            {
                                EmparentaTercero(cont, ref contUpdate);
                                CrmGlobal.AnadirElementoEmr(new UpdateRequest {
                                    Target = contUpdate
                                });
                            }
                            else
                            {
                                CrmGlobal.Iguales++;
                            }
                        }
                        catch (Exception ex)
                        {
                            ComunGlobal.LogText("ERROR al ACTUALIZAR el Entity equivalente del Contacto " + cont.Value.Aen_ClaveIntegracion + " ::: " + ex.ToString());
                        }
                    }
                    else
                    { //No existe, creamos
                        try
                        {
                            //Guardamos los Terceros que a posteriori desactivaremos (en create no se puede mandar registro inactivo)
                            if (cont.Value.Statecode.Equals("Inactivo"))
                            {
                                ContactosADesactivar.Add(cont.Value.Aen_ClaveIntegracion);
                            }

                            Entity newContact = cont.Value.GetEntityFromContacto();

                            EmparentaTercero(cont, ref newContact);
                            CrmGlobal.AnadirElementoEmr(new CreateRequest {
                                Target = newContact
                            });
                        }
                        catch (Exception ex)
                        {
                            ComunGlobal.LogText("ERROR al CREAR el Entity equivalente del Contacto " + cont.Value.Aen_ClaveIntegracion + " ::: " + ex.ToString());
                        }
                    }
                }
                CrmGlobal.ProcesarUltimosEmr();

                #endregion Procesar CONTACTOS
                sW_SOLOCARGA.Stop();
                ComunGlobal.LogText(" -----> END; TIEMPO CARGA: " + sW_SOLOCARGA.Elapsed.ToString() + " <-----\n\n");


                //6. Desactivar contactos
                CargaDiccionarioContactosPostCarga();
                DesactivarContactos();

                sW_TODO.Stop();
                CrmGlobal.MostrarEstadisticas("CONTACTOS");
                ComunGlobal.LogText(" -----> END; TIEMPO TOTAL: " + sW_TODO.Elapsed.ToString() + " <-----\n\n");



                #region Limpieza diccionarios para liberar memoria
                ContactosOracle           = null; //.Clear();
                ContactosCRM              = null; //.Clear();
                MaestroCargos             = null; //.Clear();
                MaestroTerceros           = null; //.Clear();
                MaestroContactosPostCarga = null; //.Clear();
                #endregion Limpieza diccionarios para liberar memoria
            }
            catch (Exception ex)
            {
                ComunGlobal.LogText("ERROR en Lanzador de CONTACTOS ::: " + ex.ToString());
                if (OracleGlobal != null && OracleGlobal.OraConnParaLog.State == ConnectionState.Open)
                {
                    OracleGlobal.OraConnParaLog.Dispose();
                }
            }
        }
예제 #11
0
        public void Iniciar(Oracle oracleGlobal, Comun comunGlobal, Crm crmGlobal)
        {
            try
            {
                //Aquí no hay que hacer new, el lanzador orquestador lo pasará a las properties
                Comun = comunGlobal;
                Comun.LogText("----Iniciando sincronización direcciones------");
                Crm = crmGlobal;
                DireccionesDesactivar = new HashSet <string>();

                Oracle = oracleGlobal;
                Crm.InicializarPFE(oracleGlobal);

                Stopwatch sW_Dir = new Stopwatch(), sW_SoloCarga = new Stopwatch();
                sW_Dir.Start();

                //BorrarDirecciones();

                LeerEntidades();
                LeerDireccionesOracle();
                if (!DireccionesOracle.Any())
                {
                    Comun.LogText("No hay direcciones en origen, terminamos");
                    return;
                }


                sW_SoloCarga.Start();
                foreach (var dirOra in DireccionesOracle)
                {
                    try
                    {
                        ClaveIntegracionActual = dirOra.Key;
                        bool ok = DireccionesCRM.TryGetValue(dirOra.Key, out Direccion dirCRM);
                        if (ok && DireccionesIguales(dirOra.Value, dirCRM))
                        {
                            Crm.Iguales++;
                            continue;
                        }
                        var dir = GetEntity(dirOra.Value);
                        if (ok)
                        {
                            dir["aen_direccionid"] = dirCRM.Aen_DireccionId;
                            Crm.AnadirElementoEmr(new UpdateRequest {
                                Target = dir
                            });
                        }
                        else
                        {
                            if (dirOra.Value.StateCode == "Inactivo")
                            {
                                dir["statecode"]  = new OptionSetValue(0);
                                dir["statuscode"] = new OptionSetValue(1);
                                DireccionesDesactivar.Add(dirOra.Value.Aen_ClaveIntegracion);
                            }
                            Crm.AnadirElementoEmr(new CreateRequest {
                                Target = dir
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Comun.EscribirExcepcion(e, "Error al procesar Direccion: " + dirOra.Key);
                    }
                }
                Crm.ProcesarUltimosEmr();
                sW_SoloCarga.Stop();
                comunGlobal.LogText(" -----> END; TIEMPO SOLO CARGA: " + sW_SoloCarga.Elapsed.ToString() + " <-----\n\n");
                DesactivarRecienCreadasInactivas();
                sW_Dir.Stop();
                comunGlobal.LogText(" -----> END; TIEMPO TOTAL: " + sW_Dir.Elapsed.ToString() + " <-----\n\n");
                Crm.MostrarEstadisticas("DIRECCIONES");
            }
            catch (Exception ex)
            {
                //Aquí no podemos mandar clave al log de Oracle, puesto que no hay clave integración
                //Si hay error aquí es por motivo más genérico
                Comun.EscribirExcepcion(ex, "Error");
                if (ClaveIntegracionActual != "")
                {
                    Oracle.MandarErrorIntegracion(ClaveIntegracionActual, ex.Message,
                                                  Oracle.TipoEntidadDireccion, Oracle.TipoAccionValidacion, null);
                }
                if (Oracle != null && Oracle.OraConnParaLog.State == ConnectionState.Open)
                {
                    Oracle.OraConnParaLog.Dispose();
                }
            }
            finally
            {
                if (Oracle != null && Oracle.OraConnParaLog.State == ConnectionState.Open)
                {
                    Oracle.OraConnParaLog.Dispose();
                }
            }
        }
예제 #12
0
        private static void BorrarPruebas(Crm crm, Comun co)
        {
            #region CNAES Tercero
            var quece = new QueryExpression("aen_cnaetercero");
            //quece.TopCount = 5000;

            var cenaes = new EntityCollection();
            while (true)
            {
                var res1 = crm.GetIOS().RetrieveMultiple(quece);
                cenaes.Entities.AddRange(res1.Entities);
                if (res1.MoreRecords)
                {
                    quece.PageInfo.PageNumber++;
                    quece.PageInfo.PagingCookie = res1.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var ce in cenaes.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("aen_cnaetercero", ce.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion CNAES Tercero

            co.LogText("\n=============================== CNAES BORRADOS ===================================\n");

            #region DIRECCIONES
            var qdir = new QueryExpression("aen_direccion");
            //q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            //qdir.TopCount = 5000;

            while (true)
            {
                var entidadesdir = Crm.IOS.RetrieveMultiple(qdir);
                foreach (var t in entidadesdir.Entities)
                {
                    crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("aen_direccion", t.Id)
                    });
                }
                if (entidadesdir.MoreRecords)
                {
                    qdir.PageInfo.PageNumber++;
                    qdir.PageInfo.PagingCookie = entidadesdir.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            crm.ProcesarUltimosEmr();
            #endregion DIRECCIONES

            co.LogText("\n=============================== DIRECCIONES BORRADAS ===================================\n");

            #region CONTACTOS
            var qcon = new QueryExpression("contact");
            //q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            //qcon.TopCount = 5000;
            while (true)
            {
                var entidadescon = Crm.IOS.RetrieveMultiple(qcon);
                foreach (var t in entidadescon.Entities)
                {
                    crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("contact", t.Id)
                    });
                }
                if (entidadescon.MoreRecords)
                {
                    qcon.PageInfo.PageNumber++;
                    qcon.PageInfo.PagingCookie = entidadescon.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            crm.ProcesarUltimosEmr();
            #endregion CONTACTOS

            co.LogText("\n=============================== CONTACTOS BORRADAS ===================================\n");

            #region CERTIFICACION
            qcon = new QueryExpression("aen_certificacion");
            //q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            //qcon.TopCount = 5000;
            while (true)
            {
                var entidadescon = Crm.IOS.RetrieveMultiple(qcon);
                foreach (var t in entidadescon.Entities)
                {
                    crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("aen_certificacion", t.Id)
                    });
                }
                if (entidadescon.MoreRecords)
                {
                    qcon.PageInfo.PageNumber++;
                    qcon.PageInfo.PagingCookie = entidadescon.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            crm.ProcesarUltimosEmr();
            #endregion CERTIFICACION

            co.LogText("\n=============================== CERTIFICACION BORRADAS ===================================\n");

            #region aen_normacomprada
            qcon = new QueryExpression("aen_normacomprada");
            //q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            //qcon.TopCount = 5000;
            while (true)
            {
                var entidadescon = Crm.IOS.RetrieveMultiple(qcon);
                foreach (var t in entidadescon.Entities)
                {
                    crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("aen_normacomprada", t.Id)
                    });
                }
                if (entidadescon.MoreRecords)
                {
                    qcon.PageInfo.PageNumber++;
                    qcon.PageInfo.PagingCookie = entidadescon.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            crm.ProcesarUltimosEmr();
            #endregion aen_normacomprada

            co.LogText("\n=============================== aen_normacomprada BORRADAS ===================================\n");

            #region aen_publicacionesadquiridas
            qcon = new QueryExpression("aen_publicacionesadquiridas");
            //q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            //qcon.TopCount = 5000;
            while (true)
            {
                var entidadescon = Crm.IOS.RetrieveMultiple(qcon);
                foreach (var t in entidadescon.Entities)
                {
                    crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("aen_publicacionesadquiridas", t.Id)
                    });
                }
                if (entidadescon.MoreRecords)
                {
                    qcon.PageInfo.PageNumber++;
                    qcon.PageInfo.PagingCookie = entidadescon.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            crm.ProcesarUltimosEmr();
            #endregion aen_publicacionesadquiridas

            co.LogText("\n=============================== aen_publicacionesadquiridas BORRADAS ===================================\n");

            #region aen_potencialcliente
            qcon = new QueryExpression("aen_potencialcliente");
            //q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            //qcon.TopCount = 5000;
            while (true)
            {
                var entidadescon = Crm.IOS.RetrieveMultiple(qcon);
                foreach (var t in entidadescon.Entities)
                {
                    crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("aen_potencialcliente", t.Id)
                    });
                }
                if (entidadescon.MoreRecords)
                {
                    qcon.PageInfo.PageNumber++;
                    qcon.PageInfo.PagingCookie = entidadescon.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            crm.ProcesarUltimosEmr();
            #endregion aen_potencialcliente

            co.LogText("\n=============================== aen_potencialcliente BORRADAS ===================================\n");


            #region aen_suscripcionadquirida
            qcon = new QueryExpression("aen_suscripcionadquirida");
            //q.Criteria.AddCondition(new ConditionExpression("createdon", ConditionOperator.Today));
            //qcon.TopCount = 5000;
            while (true)
            {
                var entidadescon = Crm.IOS.RetrieveMultiple(qcon);
                foreach (var t in entidadescon.Entities)
                {
                    crm.AnadirElementoEmr(new DeleteRequest {
                        Target = new EntityReference("aen_suscripcionadquirida", t.Id)
                    });
                }
                if (entidadescon.MoreRecords)
                {
                    qcon.PageInfo.PageNumber++;
                    qcon.PageInfo.PagingCookie = entidadescon.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            crm.ProcesarUltimosEmr();
            #endregion aen_suscripcionadquirida

            co.LogText("\n=============================== aen_suscripcionadquirida BORRADAS ===================================\n");


            #region TERCEROS
            var qter = new QueryExpression("account");

            /*q.Criteria.Conditions.AddRange(
             *  new ConditionExpression("createdon", ConditionOperator.Today)
             *  );*/
            //qter.TopCount = 5000;
            var terceros = new EntityCollection();
            while (true)
            {
                var res2 = crm.GetIOS().RetrieveMultiple(qter);
                terceros.Entities.AddRange(res2.Entities);
                if (res2.MoreRecords)
                {
                    qter.PageInfo.PageNumber++;
                    qter.PageInfo.PagingCookie = res2.PagingCookie;
                }
                else
                {
                    break;
                }
            }
            foreach (var t in terceros.Entities)
            {
                crm.AnadirElementoEmr(new DeleteRequest()
                {
                    Target = new EntityReference("account", t.Id)
                });
            }
            crm.ProcesarUltimosEmr();
            #endregion TERCEROS

            co.LogText("\n=============================== TERCEROS BORRADOS ===================================\n");
        }
예제 #13
0
        internal void Iniciar(Oracle oracleGlobal, Comun comunGlobal, Crm crmGlobal)
        {
            Stopwatch sW_TODO = new Stopwatch(), sW_cacheoDatos = new Stopwatch(), sW_createUpdate = new Stopwatch(), sW_leeOra = new Stopwatch(),
                      sW_cnae = new Stopwatch(), sW_emparentar = new Stopwatch(), sW_desactivar = new Stopwatch(), sW_terguid = new Stopwatch(),
                      sW_borrado = new Stopwatch();

            sW_TODO.Start();

            try
            {
                crmGlobal.InicializarPFE(oracleGlobal);
                //TODO 0. Obtener de CRM los campos parametrizados que van a intervenir en el proceso (entidad de configuracion)


                //1. Bajar los terceros de CRM a un dictionary<string, Tercero>: solo el id_oracle si no comparamos, o bien todos los campos a sincronizar si comparamos
                //diccionarios.getAllTercerosFromCRM();
                sW_cacheoDatos.Start();
                crmGlobal.CachearInfoCRM();
                crmGlobal.CargaDiccionarioGuidsTercero();
                sW_cacheoDatos.Stop();
                comunGlobal.LogText(" ----->TIEMPO CACHEO DATOS: " + sW_cacheoDatos.Elapsed.ToString() + " <-----\n\n");


                //2. Leer la tabla del Oracle
                sW_leeOra.Start();
                oracleGlobal.LeerTerceros();
                sW_leeOra.Stop();
                comunGlobal.LogText(" ----->TIEMPO LECTURA ORACLE: " + sW_leeOra.Elapsed.ToString() + " <-----\n\n");


                //3. Por cada elemento del diccionario de oracle, comprobar contra el diccionario crm. Sino se encuentra, se crea. Si se
                //   encuentra, se comprueba campo a campo para validar si se machaca o no
                //4. Hacer las creates/ updates con PFE Core
                sW_createUpdate.Start();
                crmGlobal.InicializarPFE(oracleGlobal);
                #region Tratamiento de TERCEROS
                bool    ok;
                Tercero auxTerCRM = new Tercero();
                Entity  tercUpdate;


                foreach (var terceroORACLE in oracleGlobal.Terceros)
                {
                    ok = crmGlobal.TercerosCRM.TryGetValue(terceroORACLE.Key, out auxTerCRM);

                    if (ok) // Existe. Comprobar campo a campo
                    {
                        try
                        {
                            tercUpdate = new Entity("account");
                            bool ret = comunGlobal.ActualizarTercero(crmGlobal.TercerosCRM, terceroORACLE.Value, auxTerCRM, ref tercUpdate);

                            if (ret)
                            {
                                crmGlobal.AnadirElementoEmr(new UpdateRequest {
                                    Target = tercUpdate
                                });
                            }
                            else
                            {
                                crmGlobal.Iguales++;
                            }
                        }
                        catch (Exception e)
                        {
                            comunGlobal.LogText("ERROR al ACTUALIZAR el Entity equivalente del Tercero " + terceroORACLE.Value.Aen_claveintegracion + " ::: " + e.ToString());
                        }
                    }
                    else // No existe, se crea.
                    {
                        try
                        {
                            //Guardamos los Terceros que a posteriori desactivaremos (en create no se puede mandar registro inactivo)
                            if (terceroORACLE.Value.Statecode.Equals("Inactivo"))
                            {
                                crmGlobal.TercerosADesactivar.Add(terceroORACLE.Value.Aen_claveintegracion);
                            }

                            Entity newTercero = terceroORACLE.Value.GetEntityFromTercero();
                            crmGlobal.AnadirElementoEmr(new CreateRequest {
                                Target = newTercero
                            });
                        }
                        catch (Exception e)
                        {
                            comunGlobal.LogText("ERROR al CREAR el Entity equivalente del Tercero " + terceroORACLE.Value.Aen_claveintegracion + " ::: " + e.ToString());
                        }
                    }
                }
                crmGlobal.ProcesarUltimosEmr();
                #endregion Tratamiento de TERCEROS
                sW_createUpdate.Stop();
                crmGlobal.MostrarEstadisticas("TERCEROS");
                comunGlobal.LogText(" ----->TIEMPO CREATE/UPDATE TERCEROS: " + sW_createUpdate.Elapsed.ToString() + " <-----\n\n");


                //5. Carga de diccionario de terceros <Clave integración , Guid registro>
                sW_terguid.Start();
                crmGlobal.CargaDiccionarioGuidsTercero();
                sW_terguid.Stop();
                comunGlobal.LogText(" -----> END; TIEMPO CARGA DICCIONARIO GUIDS TERCERO: " + sW_terguid.Elapsed.ToString() + " <-----\n\n");



                //6. Carga de CNAES (TABLA CARGADA ANTERIORMENTE? A QUE ENTIDAD VA? SE PUEDE HACER EN ANTERIOR UPDATE/CREATE?)
                sW_cnae.Start();
                oracleGlobal.LeerCNAES();
                crmGlobal.CargaCNAEs(oracleGlobal.ListaCNAEs);
                //crmGlobal.EliminaOldCNAEs();
                crmGlobal.MostrarEstadisticas("CNAES");
                sW_cnae.Stop();
                comunGlobal.LogText(" -----> END; TIEMPO ACTUALIZACION CNAES (CREAR Y ELIMINAR LOS QUE NO VIENEN): " + sW_cnae.Elapsed.ToString() + " <-----\n\n");


                //7. Emparentar terceros pendientes
                sW_emparentar.Start();
                crmGlobal.EmparentaTerceros();
                crmGlobal.MostrarEstadisticas("EMPARENTACION");
                sW_emparentar.Stop();
                comunGlobal.LogText(" -----> END; TIEMPO EMPARENTACION TERCEROS: " + sW_emparentar.Elapsed.ToString() + " <-----\n\n");


                //8. Desactivar terceros que vienen como Inactivos
                sW_desactivar.Start();
                crmGlobal.DesactivarTerceros();
                crmGlobal.MostrarEstadisticas("DESACTIVACION TERCEROS");
                sW_desactivar.Stop();
                comunGlobal.LogText(" -----> END; TIEMPO DESACTIVAR TERCEROS INACTIVOS: " + sW_desactivar.Elapsed.ToString() + " <-----\n\n");


                //Liberamos diccionarios
                crmGlobal.LiberaDiccionarios();
                oracleGlobal.Terceros.Clear();//.Clear();

                sW_TODO.Stop();
                comunGlobal.LogText(" -----> END; TIEMPO TOTAL: " + sW_TODO.Elapsed.ToString() + " <-----\n\n");


                //var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
                //long totalBytesOfMemoryUsed = currentProcess.WorkingSet64 / 1048576;
                //comunGlobal.LogText("\n\n############################# TOP MEMORIA AL FINAL DE TERCEROS: " + totalBytesOfMemoryUsed.ToString() + " #############################\n\n");
            }
            catch (Exception e)
            {
                comunGlobal.LogText("ERROR en Lanzador de TERCEROS ::: " + e.ToString());
                if (oracleGlobal != null && oracleGlobal.OraConnParaLog.State == ConnectionState.Open)
                {
                    oracleGlobal.OraConnParaLog.Dispose();
                }
            }
        }
예제 #14
0
        internal void Iniciar()
        {
            Stopwatch sW_TODO = new Stopwatch(), sW_cacheoDatos = new Stopwatch(), sW_createUpdate = new Stopwatch(), sW_leeOra = new Stopwatch(),
                      sW_cnae = new Stopwatch(), sW_emparentar = new Stopwatch(), sW_desactivar = new Stopwatch();

            sW_TODO.Start();

            var comun = new Comun();

            //TODO 0. Obtener de CRM los campos parametrizados que van a intervenir en el proceso (entidad de configuracion)


            //1. Bajar los terceros de CRM a un dictionary<string, Tercero>: solo el id_oracle si no comparamos, o bien todos los campos a sincronizar si comparamos
            //diccionarios.getAllTercerosFromCRM();
            Crm crm = new Crm();

            sW_cacheoDatos.Start();
            crm.CachearInfoCRM();
            sW_cacheoDatos.Stop();
            comun.LogText(" ----->TIEMPO CACHEO DATOS: " + sW_cacheoDatos.Elapsed.ToString() + " <-----");

            //BorrarPrueba(crm);


            //2. Leer la tabla del Oracle
            Oracle oracle = new Oracle(crm);

            oracle.CadenaConOracle = comun.ConnStringOracle;
            sW_leeOra.Start();
            oracle.LeerTerceros();
            sW_leeOra.Stop();
            comun.LogText(" ----->TIEMPO LECTURA ORACLE: " + sW_leeOra.Elapsed.ToString() + " <-----");


            //3. Por cada elemento del diccionario de oracle, comprobar contra el diccionario crm. Sino se encuentra, se crea. Si se
            // encuentra, se comprueba campo a campo para validar si se machaca o no
            // 4.Hacer las creates/ updates con executemultiplerequest
            bool    ok;
            Tercero auxTerCRM = new Tercero();
            Entity  tercUpdate;

            sW_createUpdate.Start();

            foreach (var terceroORACLE in oracle.Terceros)
            {
                ok = crm.TercerosCRM.TryGetValue(terceroORACLE.Key, out auxTerCRM);

                //Guardamos los Terceros que a posteriori desactivaremos
                if (terceroORACLE.Value.Statecode.Equals("Inactivo"))
                {
                    crm.TercerosADesactivar.Add(terceroORACLE.Value.Aen_claveintegracion);
                }

                if (ok) // Existe. Comprobar campo a campo
                {
                    try
                    {
                        tercUpdate = new Entity("account");
                        bool ret = comun.ActualizarTercero(terceroORACLE.Value, auxTerCRM, ref tercUpdate);

                        if (ret)
                        {
                            crm.AnadirElementoEmr(new UpdateRequest {
                                Target = tercUpdate
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR al ACTUALIZAR el Entity equivalente del Tercero " + terceroORACLE.Value.Aen_claveintegracion + " ::: " + e.ToString());
                    }
                }
                else // No existe, se crea.
                {
                    try
                    {
                        Entity newTercero = terceroORACLE.Value.GetEntityFromTercero();
                        crm.AnadirElementoEmr(new CreateRequest {
                            Target = newTercero
                        });
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("ERROR al CREAR el Entity equivalente del Tercero " + terceroORACLE.Value.Aen_claveintegracion + " ::: " + e.ToString());
                    }
                }
            }
            crm.ProcesarUltimosEmr();
            sW_createUpdate.Stop();
            comun.LogText(" ----->TIEMPO CREATE/UPDATE TERCEROS: " + sW_createUpdate.Elapsed.ToString() + " <-----");


            //5. Carga de CNAES (TABLA CARGADA ANTERIORMENTE? A QUE ENTIDAD VA? SE PUEDE HACER EN ANTERIOR UPDATE/CREATE?)
            sW_cnae.Start();
            oracle.LeerCNAES();
            crm.CargaCNAEs(oracle.ListaCNAEs);
            sW_cnae.Stop();
            comun.LogText(" -----> END; TIEMPO CARGA CNAES: " + sW_cnae.Elapsed.ToString() + " <-----");


            //6. Emparentar terceros pendientes
            sW_emparentar.Start();
            crm.EmparentaTerceros();
            sW_emparentar.Stop();
            comun.LogText(" -----> END; TIEMPO EMPARENTACION TERCEROS: " + sW_emparentar.Elapsed.ToString() + " <-----");


            //7. Desactivar terceros que vienen como Inactivos
            sW_desactivar.Start();
            crm.DesactivarTerceros();
            sW_desactivar.Stop();
            comun.LogText(" -----> END; TIEMPO DESACTIVAR TERCEROS INACTIVOS: " + sW_desactivar.Elapsed.ToString() + " <-----");


            sW_TODO.Stop();
            comun.LogText(" -----> END; TIEMPO TOTAL: " + sW_TODO.Elapsed.ToString() + " <-----");
        }