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