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; } }
/// <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; } }
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); } }
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(); } } }
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; } }
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(); } } }
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); } }
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 }
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; } }
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; } }
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); } }
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); } }