Beispiel #1
0
        public void Dispose()
        {
            this.pluginUri = null;
            this.importId  = null;
            this.packageId = null;

            if (this.userData != null)
            {
                userData.Dispose();
            }
            this.userData = null;

            if (this.package != null)
            {
                this.package.Dispose();
            }
            this.package = null;


            if (this.db != null)
            {
                this.db.closeDB();
            }
            if (this.dbAux != null)
            {
                this.dbAux.closeDB();
            }
        }
Beispiel #2
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            String lastStep = "";

            try
            {
                GetLoginToken(config);

                setUserGrp(config);

                //List<string> methods = invoker.EnumerateServiceMethods("JiraSoapServiceService");

                //A versão atual do JIRA não permite busca dos usuários sem um grupo/role, desta forma vamos utilizar o grupo padrão para listar os usuários
                //Busca o grupo padrão
                foreach (String g in defaultGroups)
                {
                    WebServiceObjectInterface oGroup = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getGroup", new Object[] { this.loginToken, g });
                    if ((oGroup.BaseObject != null) && (oGroup.GetType().Name == "RemoteGroup"))
                    {
                        Object[] users = oGroup.GetPropertyValue <Object[]>("users");
                        foreach (Object c in users)
                        {
                            PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                            try
                            {
                                package.AddProperty("name", (String)GetPropertyValue(c, "name"), "string");
                                package.AddProperty("email", (String)GetPropertyValue(c, "email"), "string");
                                package.AddProperty("fullname", (String)GetPropertyValue(c, "fullname"), "string");

                                ImportPackageUser(package);
                            }
                            catch { }
                            finally
                            {
                                package.Dispose();
                                package = null;
                            }
                        }
                    }
                }

                //WebServiceObjectInterface oIssue = new WebServiceObjectInterface(invoker, "JiraSoapServiceService", "getUser", new Object[] { this.loginToken, "*****@*****.**" });
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, "Erro on import (" + lastStep + "): " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""));
                Log2(this, PluginLogType.Error, 0, 0, "Erro on import (" + lastStep + "): " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""), "");
                throw ex;
            }
        }
Beispiel #3
0
        /// <summary>
        /// Process Import, this Method is called when the system is Import all users from replicated system
        /// </summary>
        /// <param name="cacheId">Unique ID to cache</param>
        /// <param name="importId">Unique ID to import package</param>
        /// <param name="config">Dictionary with all configuration filled by Admin</param>
        /// <param name="fieldMapping">Fields mapping filled by Admin at "Web Console > Resource x Plugin > Fields Mapping"</param>
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            String lastStep = "CheckInputConfig";

            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            StringBuilder processLog = new StringBuilder();
            StringBuilder debugLog   = new StringBuilder();
            PluginLogType logType    = PluginLogType.Information;

            try
            {
                lastStep = "Get user List";

                for (Int32 user = 0; user <= 10; user++)
                {
                    //One package by user
                    PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);

                    package.AddProperty("username", "test-" + user, "string");                      // User Login from replicated system
                    package.AddProperty("full_name", "Test Name to Sample User " + user, "string"); // User Full Name from replicated system

                    ImportPackageUser(package);
                }
            }
            catch (Exception ex)
            {
                logType = PluginLogType.Error;
                processLog.AppendLine("Error on process import (" + lastStep + "): " + ex.Message);

                Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "Last step: " + lastStep);
            }
            finally
            {
                if (logType != PluginLogType.Information)
                {
                    processLog.AppendLine(debugLog.ToString());
                }

                Log2(this, logType, 0, 0, "Import executed", processLog.ToString());
                processLog.Clear();
                processLog = null;

                debugLog.Clear();
                debugLog = null;
            }
        }
Beispiel #4
0
        /// <summary>
        /// Process Import After User Deploy, this Method is called when the system is Import only deployed user from replicated system
        /// </summary>
        /// <param name="cacheId">Unique ID to cache</param>
        /// <param name="package">Deployed package</param>
        /// <param name="config">Dictionary with all configuration filled by Admin</param>
        /// <param name="fieldMapping">Fields mapping filled by Admin at "Web Console > Resource x Plugin > Fields Mapping"</param>
        public override void ProcessImportAfterDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            String lastStep = "CheckInputConfig";

            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }


            StringBuilder processLog = new StringBuilder();
            StringBuilder debugLog   = new StringBuilder();
            PluginLogType logType    = PluginLogType.Information;
            String        importId   = Guid.NewGuid().ToString();

            try
            {
                lastStep = "Get User Data";

                PluginConnectorBaseImportPackageUser packageImport = new PluginConnectorBaseImportPackageUser(importId);
                //package.AddProperty(key, u[key], "string");
                ImportPackageUser(packageImport);
            }
            catch (Exception ex)
            {
                logType = PluginLogType.Error;
                processLog.AppendLine("Error on process import (" + lastStep + "): " + ex.Message);

                Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "Last step: " + lastStep);
            }
            finally
            {
                if (logType != PluginLogType.Information)
                {
                    processLog.AppendLine(debugLog.ToString());
                }

                Log2(this, logType, 0, 0, "Import executed", processLog.ToString());
                processLog.Clear();
                processLog = null;

                debugLog.Clear();
                debugLog = null;
            }
        }
Beispiel #5
0
        private void iRegistryProcess(PluginConfig pluginConfig, RegistryProcessStarter starter)
        {
            this.pluginUri        = starter.pluginUri;
            this.resourcePluginId = starter.resourcePluginId;
            this.resourceId       = starter.resourceId;
            this.pluginId         = starter.pluginId;
            this.importId         = starter.importId;
            this.packageId        = starter.packageId;
            this.enterpriseId     = starter.enterpriseId;
            //this.conn = new SqlConnection(;
            this.pluginConfig = pluginConfig;
            this.contextId    = starter.contextId;

            this.internalLog = new StringBuilder();

            TestTimer tmp = new TestTimer("RegistryProcess->Deserialize package", null);

            try
            {
                this.package = JSON.Deserialize <PluginConnectorBaseImportPackageUser>(starter.package);
            }
            catch (Exception ex)
            {
                throw new Exception("Error on deserialize package", ex);
            }
            tmp.Stop(dbAux.Connection, null);


#if DEBUG
            //this.db.Debug = true;
#endif

            if (pluginConfig == null)
            {
                throw new Exception("Resource x plugin not found");
            }
        }
Beispiel #6
0
 static void pg_ImportPackage(PluginConnectorBaseImportPackageUser pckage)
 {
 }
Beispiel #7
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            String lastStep = "";

            try
            {
                lastStep = "0";
                if (!CheckInputConfig(config, true, Log))
                {
                    return;
                }

                lastStep = "1";
                Uri serverUri = new Uri(config["server_uri"].ToString());

                lastStep = "2";
                try
                {
                    String mail_domain = "";

                    try
                    {
                        if (config["iam_mail_domain"] != null)
                        {
                            if (!String.IsNullOrWhiteSpace(config["iam_mail_domain"].ToString()))
                            {
                                mail_domain = config["iam_mail_domain"].ToString().ToLower();
                            }
                        }
                    }
                    catch { }

                    Log(this, PluginLogType.Debug, "mail_domain: " + mail_domain);

                    lastStep = "3";
                    cPanelLogin login = JSON.JsonWebRequest <cPanelLogin>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + "/login/?login_only=1"), "user="******"username"].ToString() + "&pass="******"password"].ToString(), "application/x-www-form-urlencoded", null, "POST", null);
                    if (login == null)
                    {
                        Log2(this, PluginLogType.Error, 0, 0, "Unexpected error on cPannel authentication", "");
                        return;
                    }

                    lastStep = "4";

                    if (login.status != 1)
                    {
                        throw new Exception("error on login: "******""));
                    }

                    lastStep = "5";
                    string authInfo = config["username"].ToString() + ":" + config["password"].ToString();
                    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                    Dictionary <string, string> headers = new Dictionary <string, string>();
                    headers.Add("Authorization", "Basic " + authInfo);

                    lastStep = "6";
                    cPanelResultBase accounts = JSON.JsonWebRequest <cPanelResultBase>(new Uri(serverUri.Scheme + "://" + serverUri.Host + ":" + serverUri.Port + login.security_token + "/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_func=listpopswithdisk&cpanel_jsonapi_module=Email&api2_paginate=1&api2_paginate_size=100000&api2_paginate_start=1&api2_sort=1&api2_sort_column=user&api2_sort_method=alphabet&api2_sort_reverse=0"), "", "application/x-www-form-urlencoded", headers, "GET");
                    if (accounts.cpanelresult == null)
                    {
                        Log2(this, PluginLogType.Error, 0, 0, "Unexpected error on get cPannel user list", "");
                        return;
                    }

                    lastStep = "7";
                    if (accounts.cpanelresult.error != null)
                    {
                        Log2(this, PluginLogType.Error, 0, 0, "Error on get cPannel users list: " + accounts.cpanelresult.error, "");
                        return;
                    }

                    lastStep = "8";
                    foreach (cPanelResultData u in accounts.cpanelresult.data)
                    {
                        lastStep = "8.1";
                        if ((!String.IsNullOrWhiteSpace(mail_domain)) && (u.domain.ToLower().Trim() != mail_domain.Trim()))
                        {
                            continue;
                        }

                        PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                        try
                        {
                            package.AddProperty("user", u.user, "string");
                            package.AddProperty("email", u.email, "string");
                            package.AddProperty("domain", u.domain, "string");

                            ImportPackageUser(package);
                        }catch {}
                        finally
                        {
                            package.Dispose();
                            package = null;
                        }
                        //   Console.WriteLine(u.name.fullName);
                    }
                }
                catch (Exception ex)
                {
                    Log2(this, PluginLogType.Error, 0, 0, "Error on get cPannel users list: " + ex.Message, "");
                }
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, "Erro on import (" + lastStep + "): " + ex.Message);
                Log2(this, PluginLogType.Error, 0, 0, "Erro on import (" + lastStep + "): " + ex.Message, "");
                throw ex;
            }
        }
Beispiel #8
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            List <String> prop = new List <String>();

            try
            {
                LocalWindows lWin = new LocalWindows(config["server"].ToString(), config["username"].ToString(), config["password"].ToString());

                try
                {
                    lWin.Bind();
                }
                catch (Exception ex)
                {
                    Log2(this, PluginLogType.Error, 0, 0, "Error on connect to Windows '" + config["server"].ToString() + "': " + ex.Message + (ex.InnerException != null ? ex.InnerException.Message : ""), "");
                    lWin = null;
                    return;
                }

                Log(this, PluginLogType.Information, "Successfully connected on " + config["server"].ToString());

                Log(this, PluginLogType.Information, "Trying to list the users...");
                foreach (DirectoryEntry user in lWin.ListAllUsers())
                {
                    PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                    try
                    {
                        object obGroups = user.Invoke("Groups");
                        foreach (object ob in (IEnumerable)obGroups)
                        {
                            // Create object for each group.
                            DirectoryEntry obGpEntry = new DirectoryEntry(ob);
                            package.AddProperty("memberOf", obGpEntry.Name, (fieldMapping.Exists(f => (f.dataName == "memberOf")) ? fieldMapping.Find(f => (f.dataName == "memberOf")).dataType : "string"));

                            //Registry(importId, regId, "memberOf", obGpEntry.Name, (fieldMapping.Exists(f => (f.dataName == "memberOf")) ? fieldMapping.Find(f => (f.dataName == "memberOf")).dataType : "string"));
                        }

                        foreach (String p in user.Properties.PropertyNames)
                        {
                            //Separa os itens que mecessita algum tratamento
                            switch (p.ToLower())
                            {
                            case "lastlogin":
                                try
                                {
                                    foreach (Object p1 in user.Properties[p])
                                    {
                                        DateTime tmp2 = DateTime.Parse(p1.ToString());

                                        if (tmp2.Year > 1970)    //Se a data for inferior nem envia
                                        {
                                            package.AddProperty(p, tmp2.ToString("yyyy-MM-dd HH:mm:ss"), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                        }
                                    }
                                }
                                catch (Exception ex)
                                { }
                                break;

                            case "loginhours":
                                break;

                            case "objectsid":
                                try
                                {
                                    Byte[] tmp2 = (Byte[])user.Properties[p][0];
                                    package.AddProperty(p, BitConverter.ToString(tmp2).Replace("-", ""), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                }
                                catch (Exception ex)
                                { }
                                break;

                            default:
                                foreach (Object p1 in user.Properties[p])
                                {
                                    package.AddProperty(p, p1.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                }
                                break;
                            }
                        }

                        ImportPackageUser(package);
                    }
                    catch (Exception ex)
                    {
                        Log(this, PluginLogType.Error, "Erro ao importar o registro (" + user.Path + "): " + ex.Message);
                    }
                    finally
                    {
                        package.Dispose();
                        package = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, ex.Message);
            }
        }
Beispiel #9
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            List <String> prop = new List <String>();

            String ldapServer = config["ldap_server"].ToString();
            String username   = config["username"].ToString();
            String password   = config["password"].ToString();
            String ou_base    = (config.ContainsKey("ou_base") ? config["ou_base"].ToString() : "");
            String _dnBase    = "";

            LDAP ldap = new LDAP(ldapServer, username, password, _dnBase);

            LDAP.DebugLog reg = new LDAP.DebugLog(delegate(String text)
            {
#if DEBUG
                //Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "LDAP log: " + text, "");
#endif
            });

            ldap.Log += reg;

            try
            {
                ldap.Bind();
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, "Error on connect to ActiveDirectory: " + ex.Message);
                Log2(this, PluginLogType.Error, 0, 0, "Error on connect to ActiveDirectory: " + ex.Message, "");
                ldap = null;
                return;
            }

            DirectoryEntry entry = null;
            try
            {
                //Caso haja o ou_base, buscar/criar a OU para listar os usuários
                if (!String.IsNullOrWhiteSpace(ou_base))
                {
                    entry = ldap.AddContainerTree(ou_base);
                }
            }
            catch { }

            //Realiza a busca de todas as OUs e grupos
            if (ImportPackageStruct != null)
            {
                PluginConnectorBaseImportPackageStruct structPackage = new PluginConnectorBaseImportPackageStruct(importId);

                try
                {
                    if (entry == null)
                    {
                        entry = ldap.DirectoryEntryRoot;
                    }

                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.SearchScope = SearchScope.Subtree;
                    search.Filter      = "(objectCategory=group)";
                    search.PropertiesToLoad.Add("distinguishedName");
                    search.PropertiesToLoad.Add("name");

                    SearchResultCollection result = search.FindAll();

                    if (result != null)
                    {
                        foreach (SearchResult sr in result)
                        {
                            try
                            {
                                structPackage.AddGroup(sr.Properties["name"][0].ToString());
                            }
                            catch (Exception ex)
                            {
                                Log(this, PluginLogType.Error, "Erro ao listar o grupo (" + sr.Path + "): " + ex.Message);
                            }
                            finally
                            {
                            }
                        }
                    }

                    search.Dispose();
                }
                catch (Exception ex)
                {
                    Log(this, PluginLogType.Error, ex.Message);
                }


                try
                {
                    if (entry == null)
                    {
                        entry = ldap.DirectoryEntryRoot;
                    }

                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.SearchScope = SearchScope.Subtree;
                    search.Filter      = "(objectClass=organizationalUnit)";
                    search.PropertiesToLoad.Add("distinguishedName");
                    search.PropertiesToLoad.Add("name");

                    SearchResultCollection result = search.FindAll();

                    if (result != null)
                    {
                        foreach (SearchResult sr in result)
                        {
                            try
                            {
                                /*
                                 * String dn = sr.Properties["distinguishedName"][0].ToString();
                                 * //String name = sr.Properties["name"][0].ToString();
                                 * String[] ou = dn.Replace(entry.Properties["distinguishedName"][0].ToString(), "").Replace(",", "").Replace("OU=", "\\").Trim(" ,".ToCharArray()).Split("\\".ToCharArray());
                                 *
                                 * Array.Reverse(ou);
                                 *
                                 * String path = "\\" + String.Join("\\", ou);*/

                                structPackage.AddContainer(DNToPath(sr.Properties["distinguishedName"][0].ToString(), entry));
                            }
                            catch (Exception ex)
                            {
                                Log(this, PluginLogType.Error, "Erro ao listar a OU (" + sr.Path + "): " + ex.Message);
                            }
                            finally
                            {
                            }
                        }
                    }

                    search.Dispose();
                }
                catch (Exception ex)
                {
                    Log(this, PluginLogType.Error, ex.Message);
                }

                //Envia o pacote da estrutura
                ImportPackageStruct(structPackage);
            }

            //Realiza a busca dos usuários
            try
            {
                //DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapServer, username, password, AuthenticationTypes.Secure);
                if (entry == null)
                {
                    entry = ldap.DirectoryEntryRoot;
                }

                DirectorySearcher search = new DirectorySearcher(entry);
                search.SearchScope = SearchScope.Subtree;
                //search.Filter = "(&(objectClass=user)(sAMAccountName=helvio.junior))";
                search.Filter = "(samAccountType=805306368)";
                search.PropertiesToLoad.Add("useraccountcontrol");
                search.PropertiesToLoad.Add("distinguishedName");
                search.PropertiesToLoad.Add("company");
                search.PropertiesToLoad.Add("department");
                search.PropertiesToLoad.Add("memberOf");

                foreach (PluginConnectorBaseDeployPackageMapping m in fieldMapping)
                {
                    if (!search.PropertiesToLoad.Contains(m.dataName))
                    {
                        search.PropertiesToLoad.Add(m.dataName);
                    }
                }

                /*
                 * search.PropertiesToLoad.Add("displayName");
                 * search.PropertiesToLoad.Add("mail");
                 * search.PropertiesToLoad.Add("sAMAccountName");
                 * search.PropertiesToLoad.Add("objectClass");
                 * search.PropertiesToLoad.Add("distinguishedName");
                 * search.PropertiesToLoad.Add("lastLogonTimestamp");
                 * search.PropertiesToLoad.Add("whenCreated");
                 *
                 * search.PropertiesToLoad.Add("lockoutTime");
                 * search.PropertiesToLoad.Add("proxyAddresses");
                 * search.PropertiesToLoad.Add("mailNickname");
                 * search.PropertiesToLoad.Add("telephoneNumber");
                 * search.PropertiesToLoad.Add("userPrincipalName");
                 * search.PropertiesToLoad.Add("memberOf");*/

                SearchResultCollection result = search.FindAll();

                if (result != null)
                {
                    foreach (SearchResult sr in result)
                    {
                        PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);

                        try
                        {
                            using (DirectoryEntry entry1 = new DirectoryEntry("LDAP://" + ldapServer + "/" + sr.Properties["distinguishedName"][0].ToString(), username, password))
                            {
                                entry1.AuthenticationType = AuthenticationTypes.Secure;
                                String ou = entry1.Parent.Path;
                                ou = ou.Replace("LDAP://" + ldapServer + "/", "");

                                package.container = DNToPath(ou, entry);

                                if (fieldMapping.Exists(f => (f.dataName == "organizationslUnit")) || fieldMapping.Exists(f => (f.dataName == "organizationslunit")))
                                {
                                    package.AddProperty("organizationslUnit", ou, "string");
                                }
                            }


                            foreach (String p in sr.Properties.PropertyNames)
                            {
                                //Separa os itens que mecessita algum tratamento
                                switch (p.ToLower())
                                {
                                case "lastlogon":
                                case "whencreated":
                                case "lockouttime":
                                    try
                                    {
                                        Int64    tmp  = Int64.Parse(sr.Properties[p][0].ToString());
                                        DateTime tmp2 = DateTime.FromFileTime(tmp);

                                        if (tmp2.Year > 1970)    //Se a data for inferior nem envia
                                        {
                                            package.AddProperty(p, tmp2.ToString("o"), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "datetime"));
                                        }
                                    }
                                    catch (Exception ex)
                                    { }
                                    break;

                                case "useraccountcontrol":
                                    foreach (Object p1 in sr.Properties[p])
                                    {
                                        UserAccountControl ctrl = (UserAccountControl)p1;

                                        foreach (UserAccountControl c in Enum.GetValues(typeof(UserAccountControl)))
                                        {
                                            //Verifica se está utilizando
                                            if ((ctrl & c) == c)
                                            {
                                                package.AddProperty(p, c.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                            }
                                        }
                                    }

                                    break;

                                case "memberof":
                                    foreach (Object p1 in sr.Properties[p])
                                    {
                                        //Trata o grupo
                                        try
                                        {
                                            using (DirectoryEntry entry1 = new DirectoryEntry("LDAP://" + ldapServer + "/" + p1.ToString(), username, password))
                                            {
                                                entry1.AuthenticationType = AuthenticationTypes.Secure;
                                                package.AddGroup(entry1.Properties["name"][0].ToString());
                                            }
                                        }
                                        catch { }


                                        if (fieldMapping.Exists(m => (m.dataName == "memberOf")))
                                        {
                                            package.AddProperty(p, p1.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                        }
                                    }

                                    break;

                                default:
                                    foreach (Object p1 in sr.Properties[p])
                                    {
                                        package.AddProperty(p, p1.ToString(), (fieldMapping.Exists(f => (f.dataName == p)) ? fieldMapping.Find(f => (f.dataName == p)).dataType : "string"));
                                    }
                                    break;
                                }
                            }

                            ImportPackageUser(package);
                        }
                        catch (Exception ex)
                        {
                            Log(this, PluginLogType.Error, "Erro ao importar o registro (" + sr.Path + "): " + ex.Message);
                        }
                        finally
                        {
                            package.Dispose();
                            package = null;
                        }
                    }
                }

                search.Dispose();
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, ex.Message);
            }
        }
Beispiel #10
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            DirectoryInfo importDir = null;;

            try
            {
                importDir = new DirectoryInfo(config["import_folder"].ToString());
                if (!importDir.Exists)
                {
                    throw new DirectoryNotFoundException();
                }
            }
            catch (Exception ex)
            {
                Log(this, PluginLogType.Error, "Erro ao localizar o diretório de importação (" + config["import_folder"].ToString() + "): " + ex.Message);
                return;
            }

            foreach (FileInfo f in importDir.GetFiles("*.csv"))
            {
                Log(this, PluginLogType.Information, "Iniciando importação do arquivo '" + f.Name + "'");

                try
                {
                    String[] firstLineData = new String[0];
                    Boolean  firstLine     = true;

                    using (FileStream fs = f.OpenRead())
                        using (StreamReader reader = new StreamReader(fs, Encoding.UTF8))
                        {
                            while (!reader.EndOfStream)
                            {
                                String line = reader.ReadLine();

                                PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                                try
                                {
                                    String[] parts = line.Split(config["delimiter"].ToString().ToCharArray());

                                    if (firstLine)
                                    {
                                        firstLineData = parts;
                                        firstLine     = false;
                                    }
                                    else
                                    {
                                        if (firstLineData.Length != parts.Length)
                                        {
                                            throw new Exception("Linha com número diferente de colunas");
                                        }


                                        for (Int32 c = 0; c < firstLineData.Length; c++)
                                        {
                                            package.AddProperty(firstLineData[c], parts[c], "string");
                                        }
                                    }

                                    ImportPackageUser(package);
                                }
                                catch (Exception ex)
                                {
                                    Log(this, PluginLogType.Error, "Falha ao importar a linha '" + line + "' do arquivo '" + f.Name + "': " + ex.Message);
                                }
                                finally
                                {
                                    package.Dispose();
                                    package = null;
                                }
                            }
                        }

                    f.MoveTo(f.FullName + ".imported");

                    Log(this, PluginLogType.Information, "Importação do arquivo '" + f.Name + "' concluida");
                }
                catch (Exception ex)
                {
                    Log(this, PluginLogType.Error, "Falha ao importar os dados do arquivo '" + f.Name + "': " + ex.Message);
                }
            }

            //realiza o processo de importação do txt
        }
Beispiel #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Request.InputStream.Position = 0;

            try
            {
                JSONRequest req = JSON.GetRequest(Request.InputStream);

                using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()))
                {
                    ProxyConfig config = new ProxyConfig(true);
                    config.GetDBConfig(database.Connection, ((EnterpriseData)Page.Session["enterprise_data"]).Id, req.host);

                    if (config.fqdn != null) //Encontrou o proxy
                    {
                        DirectoryInfo inDir = null;

                        using (ServerDBConfig c = new ServerDBConfig(IAMDatabase.GetWebConnection()))
                            inDir = new DirectoryInfo(c.GetItem("inboundFiles"));

                        if (!inDir.Exists)
                        {
                            inDir.Create();
                        }

                        req.enterpriseid = ((EnterpriseData)Page.Session["enterprise_data"]).Id.ToString();

                        String filename = config.proxy_name + "-" + DateTime.Now.ToString("yyyyMMddHHmmss-ffffff") + ".iamreq";


                        if (String.IsNullOrEmpty(req.filename))
                        {
                            req.filename = "Empty";
                        }

                        StringBuilder trackData = new StringBuilder();
                        trackData.AppendLine("Proxy: " + req.host);
                        trackData.AppendLine("Enterprise ID: " + req.enterpriseid);
                        trackData.AppendLine("Proxy filename: " + req.filename);
                        trackData.AppendLine("Saved filename: " + filename);

                        UserLogLevel level = UserLogLevel.Info;

                        trackData.AppendLine("");
                        trackData.AppendLine("Checking package...");

                        if (String.IsNullOrEmpty(req.data))
                        {
                            throw new Exception("Request data is empty");
                        }

                        Byte[] rData = Convert.FromBase64String(req.data);

                        if (!String.IsNullOrEmpty(req.sha1hash))
                        {
                            if (!CATools.SHA1CheckHash(rData, req.sha1hash))
                            {
                                throw new Exception("SHA1 Checksum is not equal");
                            }
                        }

                        String type = "";
                        try
                        {
                            JsonGeneric jData = new JsonGeneric();
                            try
                            {
                                String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn));
                                if (String.IsNullOrEmpty(config.server_pkcs12_cert))
                                {
                                    throw new Exception("Server PKCS12 from proxy config is empty");
                                }

                                using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), rData))
                                    jData.FromJsonBytes(cApi.clearData);
                            }
                            catch (Exception ex)
                            {
                                jData = null;
                                trackData.AppendLine("Error decrypting package data for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message);

#if DEBUG
                                trackData.AppendLine(ex.StackTrace);
#endif
                            }

                            if (jData != null)
                            {
#if DEBUG
                                trackData.AppendLine("");
                                trackData.AppendLine("Request data:");
                                trackData.AppendLine(jData.ToJsonString());

                                trackData.AppendLine("");
#endif

                                type = jData.function;

                                trackData.AppendLine("Type: " + type);
                                trackData.AppendLine("Data array length: " + (jData.data == null ? "0" : jData.data.Count.ToString()));

                                if (type.ToLower() == "processimportv2")
                                {
                                    Int32 d = 1;
                                    foreach (String[] dr in jData.data)
                                    {
                                        try
                                        {
                                            Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin");
                                            Int32 pkgCol            = jData.GetKeyIndex("package");

                                            if (resourcePluginCol == -1)
                                            {
                                                trackData.AppendLine("[Package data " + d + "] Erro finding column 'resource_plugin'");
                                            }

                                            if (pkgCol == -1)
                                            {
                                                trackData.AppendLine("[Package data " + d + "] Erro finding column 'package'");
                                            }

                                            if ((resourcePluginCol != -1) && (pkgCol != -1))
                                            {
                                                PluginConnectorBaseImportPackageUser pkg = JSON.DeserializeFromBase64 <PluginConnectorBaseImportPackageUser>(dr[pkgCol]);
                                                trackData.AppendLine("[Package data " + d + "] Import id: " + pkg.importId);
                                                trackData.AppendLine("[Package data " + d + "] Package id: " + pkg.pkgId);

                                                Int64 trackId = 0;
                                                try
                                                {
                                                    String tpkg = JSON.Serialize2(pkg);

                                                    DbParameterCollection par = new DbParameterCollection();
                                                    par.Add("@entity_id", typeof(Int64)).Value = 0;
                                                    par.Add("@date", typeof(DateTime)).Value   = pkg.GetBuildDate();
                                                    par.Add("@flow", typeof(String)).Value     = "inbound";
                                                    par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId;
                                                    par.Add("@filename", typeof(String)).Value             = req.filename;
                                                    par.Add("@package", typeof(String), tpkg.Length).Value = tpkg;

                                                    trackId = database.ExecuteScalar <Int64>("sp_new_package_track", System.Data.CommandType.StoredProcedure, par, null);

                                                    trackData.AppendLine("[Package data " + d + "] Package track id: " + trackId);

                                                    tpkg = null;

                                                    if (trackId > 0)
                                                    {
                                                        database.AddPackageTrack(trackId, "ProxyAPI", "Package received from proxy and saved at " + filename);
                                                    }
                                                }
                                                catch (Exception ex3) {
                                                    trackData.AppendLine("[Package data " + d + "] Erro generating package track: " + ex3.Message);
                                                }


                                                pkg.Dispose();
                                                pkg = null;
                                            }
                                        }
                                        catch (Exception ex2)
                                        {
                                            trackData.AppendLine("[Package data " + d + "] Erro parsing package data " + ex2.Message);
                                        }
                                        d++;
                                    }
                                }
                            }
                        }
                        catch (Exception ex1) {
                            trackData.AppendLine("Erro parsing package " + ex1.Message);
                            level = UserLogLevel.Error;
                        }

                        database.AddUserLog(LogKey.API_Log, DateTime.Now, "ProxyAPI", level, 0, ((EnterpriseData)Page.Session["enterprise_data"]).Id, 0, 0, 0, 0, 0, "File received from proxy " + req.host + (String.IsNullOrEmpty(type) ? "" : " (" + type + ")"), trackData.ToString());


                        File.WriteAllBytes(Path.Combine(inDir.FullName, filename), Encoding.UTF8.GetBytes(JSON.Serialize <JSONRequest>(req)));

                        ReturnHolder.Controls.Add(new LiteralControl(JSON.GetResponse(true, "", "Request received and proxy finded (" + (req.data != null ? req.data.Length.ToString() : "0") + ")")));
                    }
                }
            }
            catch (Exception ex) {
                Tools.Tool.notifyException(ex);
                throw ex;
            }
        }
Beispiel #12
0
        public override void ProcessImportAfterDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            String lastStep = "CheckInputConfig";

            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            StringBuilder processLog = new StringBuilder();
            StringBuilder debugLog   = new StringBuilder();
            PluginLogType logType    = PluginLogType.Information;
            SeniorAPI     api        = new SeniorAPI(config["username"].ToString(), config["password"].ToString(), config["numemp"].ToString(), new Uri(config["server_uri"].ToString()));


            XML.DebugMessage dbgC = new XML.DebugMessage(delegate(String data, String debug)
            {
                debugLog.AppendLine("######");
                debugLog.AppendLine("## JSON Debug message: " + data);
                debugLog.AppendLine(debug);
            });

            try
            {
                String importID = "ImpAfDep-" + Guid.NewGuid().ToString();

                lastStep = "Checa CPF no pacote";

                String cpf = "";

                //Busca o e-mail nas propriedades específicas desto usuário
                foreach (PluginConnectorBasePackageData dt in package.entiyData)
                {
                    if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower()))
                    {
                        cpf = dt.dataValue;
                    }
                }

                //Busca o e-mail nas propriedades específicas deste plugin
                if ((cpf == null) || (cpf == ""))
                {
                    foreach (PluginConnectorBasePackageData dt in package.pluginData)
                    {
                        if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower()))
                        {
                            cpf = dt.dataValue;
                        }
                    }
                }

                //Se não encontrou o e-mail testa nas propriedades maracas como ID
                if ((cpf == null) || (cpf == ""))
                {
                    foreach (PluginConnectorBasePackageData dt in package.ids)
                    {
                        if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower()))
                        {
                            cpf = dt.dataValue;
                        }
                    }
                }

                //Se não encontrou o e-mail testa nas propriedades gerais
                if ((cpf == null) || (cpf == ""))
                {
                    foreach (PluginConnectorBasePackageData dt in package.properties)
                    {
                        if (dt.dataName.ToLower() == "numcpf" && !String.IsNullOrEmpty(dt.dataValue.ToLower()))
                        {
                            cpf = dt.dataValue;
                        }
                    }
                }

#if DEBUG
                try
                {
                    String jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package);
                    if (package.password != "")
                    {
                        jData = jData.Replace(package.password, "Replaced for user security");
                    }

                    Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Package data", jData);
                }
                catch { }
#endif

                if (cpf == "")
                {
                    String jData = "";

                    try
                    {
                        jData = JSON.Serialize <PluginConnectorBaseDeployPackage>(package);
                        if (package.password != "")
                        {
                            jData = jData.Replace(package.password, "Replaced for user security");
                        }
                    }
                    catch { }

                    logType = PluginLogType.Error;
                    processLog.AppendLine("CPF (numCpf) not found in properties list. " + jData);
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "CPF (numCpf) not found in properties list", jData);
                    return;
                }

                lastStep = "Resgata informações do colaborador";

                List <Dictionary <String, String> > users = api.GetUserData(cpf, dbgC);

                if (users == null)
                {
                    throw new Exception("User data is empty");
                }

                foreach (Dictionary <String, String> u in users)
                {
                    String cNumCad = "";//Data de admissao

                    if (u.ContainsKey("numCad"))
                    {
                        cNumCad = u["numCad"];
                    }
                    else if (u.ContainsKey("numcad"))
                    {
                        cNumCad = u["numcad"];
                    }


                    PluginConnectorBaseImportPackageUser packageImp = new PluginConnectorBaseImportPackageUser(importID);
                    try
                    {
                        foreach (String key in u.Keys)
                        {
                            if (key.ToLower() == "numcpf")
                            {
                                packageImp.AddProperty(key, u[key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string");
                            }
                            else
                            {
                                packageImp.AddProperty(key, u[key], "string");
                            }
                        }


                        Dictionary <String, Dictionary <String, String> > cData = GetComplementatyData(api, u, dbgC);
                        if (cData.ContainsKey(cNumCad))
                        {
                            foreach (String key in cData[cNumCad].Keys)
                            {
                                if (key.ToLower() == "numcpf")
                                {
                                    packageImp.AddProperty(key, cData[cNumCad][key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string");
                                }
                                else
                                {
                                    packageImp.AddProperty(key, cData[cNumCad][key], "string");
                                }
                            }
                        }
                    }
                    catch (Exception ex2)
                    {
                        processLog.AppendLine("Error: " + ex2.Message);
                    }
                    finally
                    {
                        processLog.AppendLine("Import (after deploy) package generated:");
                        processLog.AppendLine("\tImport ID: " + importID);
                        processLog.AppendLine("\tPackage ID: " + packageImp.pkgId);
                        processLog.AppendLine("");
                        processLog.AppendLine("Package data:");
                        processLog.AppendLine(JSON.Serialize(packageImp));

                        ImportPackageUser(packageImp);
                    }
                }
            }
            catch (Exception ex)
            {
                logType = PluginLogType.Error;
                processLog.AppendLine("Error processing import (" + lastStep + "): " + ex.Message);

                if (ex is SafeTrend.Xml.ResultEmptyException)
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Network erro or API lock error importing user data", ex.Message + Environment.NewLine + debugLog.ToString());
                }

                try
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error processing import after deploy: " + ex.Message, debugLog.ToString());
                }
                catch
                {
                    Log2(this, PluginLogType.Error, 0, 0, "Error processing import after deploy: " + ex.Message, debugLog.ToString());
                }
            }
            finally
            {
#if DEBUG
                processLog.AppendLine(debugLog.ToString());

                Log2(this, PluginLogType.Debug, 0, 0, "Import debug log", debugLog.ToString());

                Log2(this, PluginLogType.Debug, package.entityId, package.identityId, "Import debug log", debugLog.ToString());
#else
                if (logType != PluginLogType.Information)
                {
                    processLog.AppendLine(debugLog.ToString());
                }
#endif

                Log2(this, logType, package.entityId, package.identityId, "Import executed", processLog.ToString());

                processLog.Clear();
                processLog = null;

                debugLog.Clear();
                debugLog = null;
            }
        }
Beispiel #13
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            String lastStep = "CheckInputConfig";

            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            StringBuilder processLog = new StringBuilder();
            StringBuilder debugLog   = new StringBuilder();
            PluginLogType logType    = PluginLogType.Information;
            SeniorAPI     api        = new SeniorAPI(config["username"].ToString(), config["password"].ToString(), config["numemp"].ToString(), new Uri(config["server_uri"].ToString()));


            XML.DebugMessage dbgC = new XML.DebugMessage(delegate(String data, String debug)
            {
                debugLog.AppendLine("######");
                debugLog.AppendLine("## [" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] JSON Debug message: " + data);
                debugLog.AppendLine(debug);
            });

            try
            {
                lastStep = "Resgata os colaboradores contratados nos últimos 365 dias";

                List <Dictionary <String, String> > users = api.GetUsers(dbgC);

                if (users == null)
                {
                    throw new Exception("User data is empty");
                }


                foreach (Dictionary <String, String> u in users)
                {
                    StringBuilder userDebugLog = new StringBuilder();

                    //userDebugLog.AppendLine(debugLog.ToString());

                    try
                    {
                        userDebugLog.AppendLine("######");
                        userDebugLog.AppendLine("### User Data");
                        userDebugLog.AppendLine(JSON.Serialize <Dictionary <String, String> >(u));
                    }
                    catch { }

                    userDebugLog.AppendLine("");

                    String cNumCad = "";//Data de admissao

                    if (u.ContainsKey("numCad"))
                    {
                        cNumCad = u["numCad"];
                    }
                    else if (u.ContainsKey("numcad"))
                    {
                        cNumCad = u["numcad"];
                    }

                    PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                    userDebugLog.AppendLine("######");
                    userDebugLog.AppendLine("### Package id: " + package.pkgId);
                    foreach (String key in u.Keys)
                    {
                        if (key.ToLower() == "numcpf")
                        {
                            package.AddProperty(key, u[key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string");
                        }
                        else
                        {
                            package.AddProperty(key, u[key], "string");
                        }
                    }

                    userDebugLog.AppendLine("");

                    XML.DebugMessage userDbgC = new XML.DebugMessage(delegate(String data, String debug)
                    {
                        userDebugLog.AppendLine("######");
                        userDebugLog.AppendLine("## [" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] JSON Debug message: " + data);
                        userDebugLog.AppendLine(debug);
                    });


                    Dictionary <String, Dictionary <String, String> > cData = GetComplementatyData(api, u, userDbgC);
                    if (cData.ContainsKey(cNumCad))
                    {
                        foreach (String key in cData[cNumCad].Keys)
                        {
                            if (key.ToLower() == "numcpf")
                            {
                                package.AddProperty(key, cData[cNumCad][key].Replace("-", "").Replace(".", "").Replace(" ", ""), "string");
                            }
                            else
                            {
                                package.AddProperty(key, cData[cNumCad][key], "string");
                            }
                        }
                    }

#if DEBUG
                    Log2(this, PluginLogType.Debug, 0, 0, "Import debug log for pachage " + package.pkgId, userDebugLog.ToString());
#endif

                    ImportPackageUser(package);
                }
            }
            catch (Exception ex)
            {
                logType = PluginLogType.Error;
                processLog.AppendLine("Error on process import (" + lastStep + "): " + ex.Message);


                if (ex is SafeTrend.Xml.ResultEmptyException)
                {
                    Log2(this, PluginLogType.Error, 0, 0, "Network erro or API lock error importing user data", ex.Message + Environment.NewLine + "Last step: " + lastStep);
                }
                else
                {
                    Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "Last step: " + lastStep);
                }
            }
            finally
            {
#if DEBUG
                Log2(this, PluginLogType.Debug, 0, 0, "Import debug log", debugLog.ToString());
#endif

                if (logType != PluginLogType.Information)
                {
                    processLog.AppendLine(debugLog.ToString());
                }

                Log2(this, logType, 0, 0, "Import executed", processLog.ToString());
                processLog.Clear();
                processLog = null;

                debugLog.Clear();
                debugLog = null;
            }
        }
Beispiel #14
0
        private void ImportRegistersV2(ProxyConfig config, JsonGeneric jData, FileInfo f, JSONRequest req, IAMDatabase db)
        {
            Int32 resourcePluginCol = jData.GetKeyIndex("resource_plugin");
            Int32 pkgCol            = jData.GetKeyIndex("package");


            if (resourcePluginCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportRegistersV2] Erro on find column 'resource_plugin' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }


            if (pkgCol == -1)
            {
                TextLog.Log("Inbound", "\t[ImportRegistersV2] Erro on find column 'package' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host);
                return;
            }

            //Realiza a importação no modelo BulkInsert por melhor desempenho do banco
            DataTable dtBulk = new DataTable();

            dtBulk.Columns.Add(new DataColumn("date", typeof(DateTime)));
            dtBulk.Columns.Add(new DataColumn("file_name", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("resource_plugin", typeof(Int64)));
            dtBulk.Columns.Add(new DataColumn("import_id", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("package_id", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("package", typeof(String)));
            dtBulk.Columns.Add(new DataColumn("status", typeof(String)));

            foreach (String[] dr in jData.data)
            {
                PluginConnectorBaseImportPackageUser pkg = JSON.DeserializeFromBase64 <PluginConnectorBaseImportPackageUser>(dr[pkgCol]);
                dtBulk.Rows.Add(new Object[] { DateTime.Now, f.Name, dr[resourcePluginCol], pkg.importId, pkg.pkgId, JSON.Serialize2(pkg), 'F' });

                try
                {
                    DbParameterCollection par = new DbParameterCollection();

                    par.Add("@date", typeof(DateTime)).Value = pkg.GetBuildDate();
                    par.Add("@package_id", typeof(String), pkg.pkgId.Length).Value = pkg.pkgId;

                    Int64 trackId = db.ExecuteScalar <Int64>("select id from st_package_track where flow = 'inbound' and date = @date and package_id = @package_id", System.Data.CommandType.Text, par, null);

                    db.AddPackageTrack(trackId, "inbound", "Package imported to process queue");
                }
                catch { }
            }

            db.BulkCopy(dtBulk, "collector_imports");

            //Apaga todos os registros da tabela temporaria

            /*
             * Procedimento desabiliato em 2018-08-29 por suspeita de problema
             * db.ExecuteNonQuery("delete from collector_imports_temp", System.Data.CommandType.Text, null, null);
             *
             * db.BulkCopy(dtBulk, "collector_imports_temp");
             *
             * //Proteção contra reimportação de pacotes (loop)
             * db.ExecuteNonQuery("delete from collector_imports_temp where exists (select 1 from collector_imports_old o where o.date >= dateadd(day,-1,getdate()) and o.file_name = file_name and o.resource_plugin_id = resource_plugin_id and o.import_id = import_id and o.package_id = package_id)", System.Data.CommandType.Text, null, null);
             * db.ExecuteNonQuery("delete from collector_imports_temp where exists (select 1 from collector_imports o where o.date >= dateadd(day,-1,getdate()) and o.file_name = file_name and o.resource_plugin_id = resource_plugin_id and o.import_id = import_id and o.package_id = package_id)", System.Data.CommandType.Text, null, null);
             *
             * db.ExecuteNonQuery("insert into collector_imports select * from collector_imports_temp", System.Data.CommandType.Text, null, null);
             * db.ExecuteNonQuery("delete from collector_imports_temp", System.Data.CommandType.Text, null, null);
             * */

            //Atualiza os registros importados deste arquivo para liberar o processamento
            //Isso avisa o sistema que estes registros estão livres para processamento
            //*** Desabilitado essa funç~~ao em 2018-03-08, e colocado o registro para ser importado diretamente com o Status 'F'
            //db.ExecuteNonQuery("update collector_imports set status = 'F' where [file_name] = '" + f.Name + "'", CommandType.Text, null);

            //Realiza o rebuild do indice desta tabela para agilizar no engine
            //Este processo será executado somente uma vez pelo objeto pai
            //db.ExecuteNonQuery("sp_reindex_imports", CommandType.StoredProcedure, null);

#if DEBUG
            TextLog.Log("Inbound", "\t[ImportRegistersV2] Imported " + dtBulk.Rows.Count + " registers for enterprise " + req.enterpriseid + " and proxy " + req.host);
#endif

            dtBulk.Dispose();
            dtBulk = null;

            jData = null;
        }
Beispiel #15
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            List <String> prop = new List <String>();

            String table  = config["table"].ToString();
            String filter = config["select_filter"].ToString();

            OdbcDB db = null;

            try
            {
                db = new OdbcDB(config["system_dsn"].ToString(), (config.ContainsKey("username") ? config["username"].ToString() : ""), (config.ContainsKey("password") ? config["password"].ToString() : ""));
                db.openDB();

                String sql = "select * from " + table;

                if (!String.IsNullOrWhiteSpace(filter))
                {
                    filter = filter.Trim();
                    if (filter.IndexOf("where") != 0)
                    {
                        filter = "where " + filter;
                    }

                    sql = sql + " " + filter;
                }

                DataTable dtSource = db.Select(sql);

                if (dtSource == null)
                {
                    throw new Exception("Erro on select: " + db.LastError);
                }

                foreach (DataRow dr in dtSource.Rows)
                {
                    PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                    try
                    {
                        foreach (DataColumn dc in dtSource.Columns)
                        {
                            package.AddProperty(dc.ColumnName, dr[dc.ColumnName].ToString(), dc.DataType.ToString());
                        }

                        ImportPackageUser(package);
                    }
                    catch (Exception ex)
                    {
                        Log(this, PluginLogType.Error, "Erro ao importar o registro: " + ex.Message);
                    }
                    finally
                    {
                        package.Dispose();
                        package = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "");
                Log(this, PluginLogType.Error, ex.Message);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #16
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            List <String> prop = new List <String>();


            String connectionstring = "Data Source=" + config["server"].ToString() + ";Initial Catalog=master;User Id=" + config["username"].ToString() + ";Password='******';";

            MSSQLDB db = null;

            try
            {
                db = new MSSQLDB(connectionstring);
                db.openDB();

                String sql = "SELECT name AS Login_Name FROM sys.server_principals  WHERE TYPE IN ('S') and name not like '%##%' ORDER BY name, type_desc";

                DataTable dtSource = db.Select(sql);

                if (dtSource == null)
                {
                    throw new Exception("Erro on select: " + db.LastError);
                }

                foreach (DataRow dr in dtSource.Rows)
                {
                    PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                    try
                    {
                        foreach (DataColumn dc in dtSource.Columns)
                        {
                            package.AddProperty(dc.ColumnName, dr[dc.ColumnName].ToString(), dc.DataType.ToString());
                        }

                        ImportPackageUser(package);
                    }
                    catch (Exception ex)
                    {
                        Log2(this, PluginLogType.Error, 0, 0, "Erro ao importar o registro: " + ex.Message, "");
                        Log(this, PluginLogType.Error, "Erro ao importar o registro: " + ex.Message);
                    }
                    finally
                    {
                        package.Dispose();
                        package = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "");
                Log(this, PluginLogType.Error, ex.Message);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
Beispiel #17
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            LogEvent iLog = new LogEvent(delegate(Object sender, PluginLogType type, string text)
            {
                if (Log != null)
                {
                    Log(sender, type, text);
                }
            });

            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }



            String server   = config["server"].ToString();
            String username = config["username"].ToString();
            String password = config["password"].ToString();


            try
            {
                PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo(server, username, password);
                connectionInfo.Timeout = new TimeSpan(0, 1, 0);

                using (SshClient client = new SshClient(connectionInfo))
                {
                    try
                    {
                        client.Connect();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Erro on connect SSH", ex);
                    }


                    List <UserData> users = GetList(client, config);

                    foreach (UserData u in users)
                    {
                        PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);


                        String property = "";

                        property = "username";
                        package.AddProperty(property, u.Username, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "user_id";
                        package.AddProperty(property, u.UserId, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "default_group";
                        package.AddProperty(property, u.DefaultGroup, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "information";
                        package.AddProperty(property, u.Information, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "home_path";
                        package.AddProperty(property, u.HomePath, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));

                        property = "bash";
                        package.AddProperty(property, u.Bash, (fieldMapping.Exists(f => (f.dataName == property)) ? fieldMapping.Find(f => (f.dataName == property)).dataType : "string"));


                        ImportPackageUser(package);
                    }

                    client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                iLog(this, PluginLogType.Error, ex.Message);
            }
        }
Beispiel #18
0
        public override void ProcessImport(String cacheId, String importId, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }


            String table = config["sheet"].ToString();

            table = table.Trim("$ []".ToCharArray());

            try
            {
                DirectoryInfo importDir = null;;
                try
                {
                    importDir = new DirectoryInfo(config["import_folder"].ToString());
                    if (!importDir.Exists)
                    {
                        throw new DirectoryNotFoundException();
                    }
                }
                catch (Exception ex)
                {
                    Log2(this, PluginLogType.Error, 0, 0, "Erro ao localizar o diretório de importação (" + config["import_folder"].ToString() + ")", ex.Message);
                    return;
                }

                foreach (FileInfo f in importDir.GetFiles("*.xls"))
                {
                    OdbcDB db = null;
                    try
                    {
                        db = new OdbcDB(f);
                        db.openDB();

                        String sql = "select * from [" + table + "$]";

                        DataTable dtSource = db.Select(sql);

                        if (dtSource == null)
                        {
                            throw new Exception("Erro on select: " + db.LastError);
                        }

                        foreach (DataRow dr in dtSource.Rows)
                        {
                            PluginConnectorBaseImportPackageUser package = new PluginConnectorBaseImportPackageUser(importId);
                            try
                            {
                                foreach (DataColumn dc in dtSource.Columns)
                                {
                                    package.AddProperty(dc.ColumnName, dr[dc.ColumnName].ToString(), dc.DataType.ToString());
                                }

                                ImportPackageUser(package);
                            }
                            catch (Exception ex)
                            {
                                Log(this, PluginLogType.Error, "Erro ao importar o registro: " + ex.Message);
                            }
                            finally
                            {
                                package.Dispose();
                                package = null;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log2(this, PluginLogType.Error, 0, 0, "Falha ao mapear os dados do arquivo '" + f.Name + "'", ex.Message);
                    }
                    finally
                    {
                        if (db != null)
                        {
                            db.Dispose();
                        }
                    }


                    f.MoveTo(f.FullName + ".imported");

                    Log(this, PluginLogType.Information, "Importação do arquivo '" + f.Name + "' concluida");
                }
            }
            catch (Exception ex)
            {
                Log2(this, PluginLogType.Error, 0, 0, "Error on process import: " + ex.Message, "");
                Log(this, PluginLogType.Error, ex.Message);
            }
        }