private static void ManageIndexLock(bool indexExists) { try { if (indexExists && IndexWriter.IsLocked(Settings.Instance.StoreFolder)) { GXLogging.Warn(log, "There is more than one process trying to write to the index folder"); int indexChecks = 0; while (IndexWriter.IsLocked(Settings.Instance.StoreFolder) && indexChecks < 20) { indexChecks++; Thread.Sleep(3000); GXLogging.Warn(log, "Waiting for the lock to release."); } if (IndexWriter.IsLocked(Settings.Instance.StoreFolder)) { GXLogging.Warn(log, "Forcefully releasing lock"); IndexWriter.Unlock(Settings.Instance.StoreFolder); } } } catch (IOException e1) { GXLogging.Error(log, "There was a problem waiting for the lock to release.", e1); } }
public short Open(String xlName) { this.fileName = xlName; if (document != null && closed) { document = null; } if (!string.IsNullOrEmpty(xlName) && checkExcelDocument()) { closed = false; try { if (GXServices.Instance == null || GXServices.Instance.Get(GXServices.STORAGE_SERVICE) == null) { if (!Path.IsPathRooted(this.fileName)) { this.fileName = Path.Combine(GxContext.StaticPhysicalPath(), this.fileName); } } else { this.fileName = this.fileName.Replace("\\", "/"); } } catch (Exception e) { GXLogging.Warn(log, "Setting Rooted Path on " + this.fileName, e); } return(document.Open(this.fileName)); } else { return(document.ErrCode); } }
internal static bool GetEncryptedDataStoreProperty(string id, string name, out string ret) { string key = "Connection-" + id + name; string ds = DATASTORE_SECTION + id; ret = ""; string cfgBuf = string.Empty; bool found = false; string envPath; if (!connectionProperties.ContainsKey(key)) { try { if (Config.GetValueOf(ds, key, out cfgBuf)) { found = true; } else if ((envPath = Environment.GetEnvironmentVariable("GXCFG")) != null) { if (IniGetValueOf(envPath + "\\gxcfg.ini", "Connection-" + id + name, out cfgBuf)) { found = true; } } #if !NETCORE else if (IniGetValueOf(Environment.SystemDirectory + "\\gxcfg.ini", "Connection-" + id + name, out cfgBuf)) { found = true; } #endif } catch (SecurityException ex) { GXLogging.Warn(log, "Error in GetEncryptedDataStoreProperty", ex); } if (found) { if (!CryptoImpl.Decrypt(ref ret, cfgBuf)) { ret = cfgBuf; } if (!string.IsNullOrEmpty(ret)) { connectionProperties[key] = ret; } } } else { ret = connectionProperties[key]; found = true; } return(found); }
private void Insert(IndexRecord indexRecord) { IndexWriter writer = Writer; if (writer == null) { return; } try { Document doc = new Document(); doc.Add(new Field(IndexRecord.URIFIELD, indexRecord.Uri, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field(IndexRecord.ENTITYFIELD, indexRecord.Entity, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field(IndexRecord.CONTENTFIELD, new StringReader(IndexRecord.ProcessContent(indexRecord.Content)))); #pragma warning disable CS0618 // Type or member is obsolete doc.Add(new Field(IndexRecord.TIMESTAMPFIELD, DateField.DateToString(DateTime.Now), Field.Store.YES, Field.Index.NO)); #pragma warning restore CS0618 // Type or member is obsolete doc.Add(new Field(IndexRecord.VIEWERFIELD, indexRecord.Viewer, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field(IndexRecord.TITLEFIELD, indexRecord.Title, Field.Store.YES, Field.Index.NOT_ANALYZED)); int i = 1; foreach (string key in indexRecord.Keys) { doc.Add(new Field(string.Format("{0}{1}", IndexRecord.KEYFIELDPREFIX, (i++).ToString()), key, Field.Store.YES, Field.Index.NO)); } GXLogging.Debug(log, "AddDocument:" + indexRecord.Uri + " content:" + indexRecord.Content); writer.AddDocument(doc, m_analyzer); if (m_counter++ > Settings.Instance.OptimizeThreshold) { m_counter = 0; GXLogging.Warn(log, "Optimizing index"); writer.Optimize(); } } catch (Exception e) { GXLogging.Error(log, "Insert error", e); } finally { try { writer.Dispose(); Searcher.Instance.Close(); } catch (Exception ex) { GXLogging.Error(log, "Close writer error", ex); } } }
public override string GetString(int i) { string res; try { res = Convert.ToString(reader.GetString(i)); } catch (InvalidCastException ex) { GXLogging.Warn(log, "GetString error", ex); res = Convert.ToString(reader.GetValue(i).ToString()); } readBytes += 10 + (2 * res.Length); return(res); }
public string XsltApply(string xslFileName) { #if !NETCORE XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CheckCharacters = false; try { return(GxXsltImpl.Apply(FileUtil.NormalizeSource(xslFileName, _baseDirectory), _file.FullName)); } catch (Exception ex) //ArgumentException invalid characters in xml, XslLoadException An item of type 'Attribute' cannot be constructed within a node of type 'Root'. { GXLogging.Warn(log, "XsltApply Error", ex); return(GxXsltImpl.ApplyOld(FileUtil.NormalizeSource(xslFileName, _baseDirectory), _file.FullName)); } #else return(string.Empty); #endif }
public override IDbTransaction BeginTransaction(IsolationLevel isoLevel) { try { IDbTransaction trn = InternalConnection.BeginTransaction(isoLevel); return(trn); } catch (Exception e) { GXLogging.Warn(log, "BeginTransaction Error ", e); IDbTransaction trn = InternalConnection.BeginTransaction(IsolationLevel.Unspecified); if (trn.IsolationLevel != isoLevel) { GXLogging.Error(log, "BeginTransaction Error, could not open new transaction isoLevel=" + isoLevel, e); throw new GxADODataException("Begin transaction error in informix", e); } return(trn); } }
protected override string SelectOperation(ref Message message, out bool uriMatched) { bool messageModified = false; string result = base.SelectOperation(ref message, out uriMatched); if (!uriMatched || string.IsNullOrEmpty(result) || result == "LoadDefault") //In the BC POST, uriMatched is true but result = string.Empty. { string address = message.Headers.To.AbsoluteUri; if (address.EndsWith(",")) { address = address + "gxempty"; } if (address.Contains("/,")) { address = address.Replace("/,", "/gxempty,"); } while (address.Contains(",,")) { address = address.Replace(",,", ",gxempty,"); } if (uriMatched && !string.IsNullOrEmpty(result)) { message.Properties.Remove("UriTemplateMatchResults"); messageModified = true; } if (message.Headers.To.AbsoluteUri != address) { message.Headers.To = new Uri(address); messageModified = true; } if (messageModified) { try { result = base.SelectOperation(ref message, out uriMatched); }catch (Exception ex) { GXLogging.Warn(log, ex, "Could not rewrite wcf message to ", address); } } } return(result); }
private static ThemeData GetThemeData(string themeName) { if (!m_themes.ContainsKey(themeName)) { string path = Path.Combine(GxContext.StaticPhysicalPath(), "themes", $"{themeName}.json"); ThemeData themeData; try { #pragma warning disable SCS0018 // Path traversal: injection possible in {1} argument passed to '{0}' string json = File.ReadAllText(path); #pragma warning restore SCS0018 // Path traversal: injection possible in {1} argument passed to '{0}' themeData = JSONHelper.Deserialize <ThemeData>(json); } catch (Exception ex) { GXLogging.Warn(log, $"Unable to load theme metadata ({themeName}). Using an empty default one.", ex); themeData = CreateDefaultThemeData(themeName); } m_themes[themeName] = themeData; } return(m_themes[themeName]); }
static public string GetMessage(string langId, string strId1, Object[] obj) { bool trimSpaces = strId1 != null && strId1.Length > 0 && (strId1[0] == ' ' || strId1[strId1.Length - 1] == ' '); string strId = trimSpaces ? strId1.Trim() : strId1; ResourceSet rs = GetRManager(langId); string strFormat = null; if (rs != null) { strFormat = rs.GetString(strId); } if (strFormat == null) { strFormat = strId1; } else { try { if (obj != null) { strFormat = string.Format(strFormat, obj); } } catch { GXLogging.Warn(log, "Cannot format message '" + strFormat + "'"); } if (trimSpaces) { strFormat = CopySpaces(strId1, strFormat); } } return(strFormat); }
public string GetValue(string Name) { if (string.IsNullOrEmpty(Name)) { GXLogging.Warn(log, "GetValue of empty SDT property at " + this.GetType()); return(string.Empty); } else { Type me = GetType(); string FieldName = "gxTpr_" + Name.Substring(0, 1).ToUpper() + Name.Substring(1).ToLower(); object objValue = me.GetProperty(FieldName).GetValue(this, Array.Empty <object>()); if (objValue is DateTime) { DateTime dt = (DateTime)objValue; if (dt.Year > 200) { objValue = new DateTime(dt.Year - 1900, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond); } } else if (objValue is Guid) { objValue = objValue.ToString(); } else { IGxCollection objColValue = objValue as IGxCollection; if (objColValue != null) { return(objColValue.ToJSonString()); } } return(Convert.ChangeType(objValue, typeof(string), System.Globalization.CultureInfo.InvariantCulture) as string); } }
public void Execute(string method, string name) { HttpWebRequest req; HttpWebResponse resp = null; int BytesRead; Byte[] Buffer = new Byte[1024]; _errCode = 0; _errDescription = ""; GXLogging.Debug(log, "Start Execute: method '" + method + "', name '" + name + "'"); try { string requestUrl = GetRequestURL(name); bool contextCookies = _context != null && !String.IsNullOrEmpty(requestUrl); CookieContainer cookies = contextCookies ? _context.GetCookieContainer(requestUrl, IncludeCookies) : new CookieContainer(); req = buildRequest(method, requestUrl, cookies); #if NETCORE resp = req.GetResponse() as HttpWebResponse; if (contextCookies) { _context.UpdateSessionCookieContainer(); } #else resp = (HttpWebResponse)req.GetResponse(); #endif } catch (WebException e) { GXLogging.Warn(log, "Error Execute", e); _errCode = 1; _errDescription = e.Message; resp = (HttpWebResponse)(e.Response); if (resp == null) { return; } } #if NETCORE catch (AggregateException aex) { GXLogging.Warn(log, "Error Execute", aex); _errCode = 1; _errDescription = aex.Message; var baseEx = aex.GetBaseException() as WebException; if (baseEx != null) { resp = baseEx.Response as HttpWebResponse; _errDescription = baseEx.Message; } if (resp == null) { return; } } #endif GXLogging.Debug(log, "Reading response..."); loadResponseHeaders(resp); _receiveStream = new MemoryStream(); using (Stream rStream = resp.GetResponseStream()) { try { Buffer = new Byte[1024]; BytesRead = rStream.Read(Buffer, 0, 1024); GXLogging.Debug(log, "BytesRead " + BytesRead); bool encodingFound = false; String charset = resp.ContentType; if (!string.IsNullOrEmpty(charset)) { int idx = charset.IndexOf("charset="); if (idx > 0) { idx += 8; charset = charset.Substring(idx, charset.Length - idx); _encoding = GetEncoding(charset); if (_encoding != null) { encodingFound = true; } } else { charset = String.Empty; } } while (BytesRead > 0) { if (!encodingFound) { _encoding = DetectEncoding(charset, out encodingFound, Buffer, BytesRead); } _receiveStream.Write(Buffer, 0, BytesRead); BytesRead = rStream.Read(Buffer, 0, 1024); GXLogging.Debug(log, "BytesRead " + BytesRead); } } catch (IOException ioEx) { if (_errCode == 1) { GXLogging.Warn(log, "Could not read response", ioEx); } else { throw ioEx; } } } _receiveStream.Seek(0, SeekOrigin.Begin); _statusCode = (short)resp.StatusCode; _statusDescription = resp.StatusDescription; resp.Close(); ClearSendStream(); GXLogging.Debug(log, "_responseString " + ToString()); }
private void mSave(object state1) { object[] state = state1 as object[]; GXDebugItem[] Data = state[0] as GXDebugItem[]; int saveTop = (int)state[1]; int saveCount = (int)state[2]; lock (mSaveLock) { int idx = 0; try { string FQFileName = Path.IsPathRooted(FileName) ? FileName : Path.Combine(GxContext.Current.GetPhysicalPath(), FileName); #pragma warning disable SCS0018 // Path traversal: injection possible in {1} argument passed to '{0}' using (GXDebugStream stream = new GXDebugStream(FQFileName, FileMode.Append)) #pragma warning restore SCS0018 // Path traversal: injection possible in {1} argument passed to '{0}' { stream.WriteHeader(SessionGuid, (short)(GXDEBUG_VERSION << 4 | GENERATOR_ID.ToByte()), saveCount); #if _DEBUG_DEBUGGER Console.WriteLine("mSave-" + saveTop); #endif for (; idx < saveTop; idx++) { GXDebugItem dbgItem = Data[idx]; #if _DEBUG_DEBUGGER Console.WriteLine($"item({idx}): { dbgItem }"); #endif switch (dbgItem.MsgType) { case GXDebugMsgType.SYSTEM: { stream.WriteByte((byte)(dbgItem.MsgType.ToByte() | ((GXDebugMsgCode)dbgItem.Arg1).ToByte())); switch ((GXDebugMsgCode)dbgItem.Arg1) { case GXDebugMsgCode.INITIALIZE: stream.WriteLong(((DateTime)dbgItem.ArgObj).ToUniversalTime().Ticks); break; case GXDebugMsgCode.OBJ_CLEANUP: stream.WriteVLUInt((int)dbgItem.ArgObj); break; case GXDebugMsgCode.EXIT: break; case GXDebugMsgCode.PGM_INFO: KeyValuePair <object, object> info = (KeyValuePair <object, object>)dbgItem.ArgObj; stream.WriteVLUInt(((KeyValuePair <int, int>)info.Key).Key); stream.WriteVLUInt(((KeyValuePair <int, int>)info.Key).Value); stream.WriteVLUInt(((KeyValuePair <int, long>)info.Value).Key); stream.WriteInt(((KeyValuePair <int, long>)info.Value).Value); break; default: throw new ArgumentException($"Invalid DbgItem: { dbgItem }"); } } break; case GXDebugMsgType.PGM_TRACE: { stream.WritePgmTrace(dbgItem.DbgInfo.SId, dbgItem.Arg1, dbgItem.Arg2, dbgItem.Ticks); } break; case GXDebugMsgType.PGM_TRACE_RANGE: case GXDebugMsgType.PGM_TRACE_RANGE_WITH_COLS: { stream.WriteByte(dbgItem.MsgType.ToByte()); stream.WriteVLUInt(dbgItem.DbgInfo.SId); stream.WriteVLUInt(dbgItem.Arg1); stream.WriteVLUInt(dbgItem.Arg2); if (dbgItem.MsgType == GXDebugMsgType.PGM_TRACE_RANGE_WITH_COLS) { stream.WriteVLUInt(((KeyValuePair <int, int>)dbgItem.ArgObj).Key); stream.WriteVLUInt(((KeyValuePair <int, int>)dbgItem.ArgObj).Value); } } break; case GXDebugMsgType.REGISTER_PGM: { stream.WriteByte(dbgItem.MsgType.ToByte()); stream.WriteVLUInt(dbgItem.DbgInfo.SId); stream.WriteVLUInt(dbgItem.Arg1); stream.WriteVLUInt(((KeyValuePair <int, int>)dbgItem.ArgObj).Key); stream.WriteVLUInt(((KeyValuePair <int, int>)dbgItem.ArgObj).Value); } break; case GXDebugMsgType.SKIP: continue; } ClearDebugItem(dbgItem); } } } catch (Exception ex) { GXLogging.Warn(log, $"GXDebugManager: Cannot write debug file", ex); } saving = false; waitSaveEvent.Set(); } }
public override bool ProcessError(int dbmsErrorCode, string emsg, GxErrorMask errMask, IGxConnection con, ref int status, ref bool retry, int retryCount) { switch (dbmsErrorCode) { case -243: // Locked case -244: // Locked case -245: // Locked retry = Retry(errMask, retryCount); if (retry) { status = 110; // Locked - Retry } else { status = 103; //Locked } return(retry); case -239: // Duplicated record case -268: // Duplicated record case -346: // Duplicated record status = 1; break; case -203: // File not found case -206: // File not found case -319: // File not found case -623: // File not found status = 105; break; case 50: // table or view does not exist if (!GxContext.isReorganization) { status = 999; return(false); } else { status = 105; } break; case -691: // Parent key not found if ((errMask & GxErrorMask.GX_MASKFOREIGNKEY) == 0) { status = 500; // ForeignKeyError return(false); } else { status = 0; // NoError } break; default: GXLogging.Warn(log, "ProcessError dbmsErrorCode:'" + dbmsErrorCode + "'" + emsg); status = 999; return(false); } return(true); }
public int Shell(string commandString, int modal) { try { GXLogging.Debug(log, "Shell commandString:'", commandString, "',modal:'", modal.ToString(), "'"); int startArgs; string file, args; commandString = commandString.TrimStart(); file = ""; args = ""; bool in_string = false; startArgs = -1; for (int i = 0; i < commandString.Length; i++) { if (commandString[i] == '"' || commandString[i] == '\'') { if (in_string) { in_string = false; } else { in_string = true; } } if (in_string) { continue; } if (commandString[i] == ' ') { startArgs = i; break; } } if (startArgs == -1) { file = commandString; args = ""; } else { file = commandString.Substring(0, startArgs); args = commandString.Substring(startArgs + 1); } file = file.Replace("\'", "").Replace("\"", ""); //If the file name was delimited with 'it is changed to ". Process p = new Process(); p.StartInfo.Arguments = args; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = true; //When UseShellExecute is true, the WorkingDirectory property specifies the location of the executable. //If WorkingDirectory is an empty string, the current directory is understood to contain the executable. try { p.StartInfo.FileName = "\"" + file + "\""; } catch (Exception e) { GXLogging.Warn(log, "Setting Path Rooted", e); } try { if (Path.IsPathRooted(file)) { p.StartInfo.WorkingDirectory = "\"" + Path.GetDirectoryName(file) + "\""; } else { p.StartInfo.WorkingDirectory = GxContext.StaticPhysicalPath(); } } catch (Exception e) { GXLogging.Warn(log, "Setting Working Directory", e); } GXLogging.Debug(log, "Shell FileName:'" + p.StartInfo.FileName + "',Arguments:'" + p.StartInfo.Arguments + "'"); GXLogging.Debug(log, "Shell Working directory:'" + p.StartInfo.WorkingDirectory + "'"); bool res = p.Start(); GXLogging.Debug(log, "Shell new process resource is started:" + res); if (modal > 0) { p.WaitForExit(); GXLogging.Debug(log, "Shell ExitCode:" + p.ExitCode); return(p.ExitCode); } return(0); } catch (Exception e) { GXLogging.Error(log, "Shell Error", e); throw e; } }
private string getBLOBFile(int id, string extension, string name, string fileName, bool temporary, GxFileType fileType = GxFileType.PrivateAttribute) { GxFile file = null; Stream fs = null; BinaryWriter bw = null; int bufferSize = 4096; byte[] outbyte = new byte[bufferSize]; long retval; long startIndex = 0; bool streamClosed = false; try { startIndex = 0; retval = _gxDbCommand.Db.GetBytes(_gxDbCommand, _DR, id - 1, startIndex, outbyte, 0, bufferSize); if (retval == 0) { return(""); } using (fs = new MemoryStream()) { using (bw = new BinaryWriter(fs)) { while (retval == bufferSize) { bw.Write(outbyte); bw.Flush(); startIndex += bufferSize; retval = _gxDbCommand.Db.GetBytes(_gxDbCommand, _DR, id - 1, startIndex, outbyte, 0, bufferSize); } bw.Write(outbyte, 0, (int)retval); bw.Flush(); fs.Seek(0, SeekOrigin.Begin); file = new GxFile(_gxDbCommand.Conn.BlobPath, fileName, fileType); file.Create(fs); } } streamClosed = true; GXLogging.Debug(log, "GetBlobFile fileName:" + fileName + ", retval bytes:" + retval); if (temporary) { GXFileWatcher.Instance.AddTemporaryFile(file); } fileName = file.GetURI(); } catch (IOException e) { if (!file.Exists()) { GXLogging.Error(log, "Return getBLOBFile Error Can't read BLOB field into " + fileName, e); throw (new GxADODataException(e)); } else { GXLogging.Warn(log, "Return getBLOBFile Error Can't write BLOB field into " + fileName, e); } } finally { if (!streamClosed) { try { if (bw != null) { bw.Close(); } if (fs != null) { fs.Close(); } } catch (Exception ex) { GXLogging.Error(log, "getBLOBFile Close Stream Error", ex); } } } return(fileName); }
//ns = kb Namespace //clssWithoutNamespace = fullname genexus object (includes module), p.e. genexus.sd.synchronization.offlineeventreplicator static public Type FindType(string defaultAssemblyName, string ns, string clssWithoutNamespace, Assembly defaultAssembly, bool ignoreCase = false) { string clss = string.IsNullOrEmpty(ns) ? clssWithoutNamespace : string.Format("{0}.{1}", ns, clssWithoutNamespace); Type objType = null; string appNS; loadedAssemblies.TryGetValue(clss, out objType); if (objType == null) { #if NETCORE var asl = new AssemblyLoader(FileUtil.GetStartupDirectory()); #endif if (defaultAssembly != null) { try { objType = ignoreCase? defaultAssembly.GetType(clss, false, ignoreCase): defaultAssembly.GetType(clss); } catch { GXLogging.Error(log, "Failed to load type: " + clss + ", assembly: " + defaultAssembly.FullName); } } try { AssemblyName defaultAssemblyNameObj = new AssemblyName(defaultAssemblyName); if (objType == null) { #if NETCORE Assembly assem = asl.LoadFromAssemblyName(defaultAssemblyNameObj); objType = ignoreCase ? assem.GetType(clss): assem.GetType(clss, false, ignoreCase); #else objType = Assembly.Load(defaultAssemblyNameObj).GetType(clss); #endif } } catch (Exception ex) { GXLogging.Error(log, "Failed to load type: " + clss + ", assembly: " + defaultAssemblyName, ex); } try { if (objType == null) { if (Assembly.GetEntryAssembly() != null) { objType = ignoreCase ? Assembly.GetEntryAssembly().GetType(clss, false, ignoreCase) : Assembly.GetEntryAssembly().GetType(clss); } } } catch { GXLogging.Error(log, "Failed to load type: " + clss + " from entryAssembly"); } try { if (objType == null) { objType = ignoreCase ? Assembly.GetCallingAssembly().GetType(clss, false, ignoreCase) : Assembly.GetCallingAssembly().GetType(clss); } } catch { GXLogging.Error(log, "Failed to load type: " + clss + " from callingAssembly"); } if (objType == null && !string.IsNullOrEmpty(ns) && Config.GetValueOf("AppMainNamespace", out appNS)) { if (ns != appNS) { return(FindType(defaultAssemblyName, appNS, clssWithoutNamespace, defaultAssembly)); } } if (objType == null) { GXLogging.Warn(log, "Find Instance in CurrentDomain"); foreach (Assembly asby in AppDomain.CurrentDomain.GetAssemblies()) { objType = ignoreCase ? asby.GetType(clss, false, ignoreCase) : asby.GetType(clss); if (objType != null) { break; } } } if (objType == null && !string.IsNullOrEmpty(ns)) { if (defaultAssemblyName.Contains(",")) { string[] parts = defaultAssemblyName.Split(','); if (parts.Length == 2) { defaultAssemblyName = parts[1]; clss = parts[0]; } return(FindType(defaultAssemblyName, string.Empty, clss, defaultAssembly)); } } if (objType == null) { GXLogging.Debug(log, "Find class in assemblies in directory " + FileUtil.GetStartupDirectory()); ArrayList files = new ArrayList(); files.AddRange(Directory.GetFiles(FileUtil.GetStartupDirectory(), "*.dll")); #if !NETCORE files.AddRange(Directory.GetFiles(FileUtil.GetStartupDirectory(), "*.exe")); #endif foreach (string file in files) { GXLogging.Debug(log, "Find class " + clss + ", assembly: " + file); try { #if !NETCORE objType = Assembly.LoadFrom(file).GetType(clss); #else Assembly assem = asl.LoadFromAssemblyName(new AssemblyName(Path.GetFileNameWithoutExtension(file))); objType = ignoreCase ? assem.GetType(clss, false, ignoreCase) : assem.GetType(clss); #endif if (objType != null) { break; } } catch (BadImageFormatException) { // It is not an .Net assembly } } if (objType == null) { GXLogging.Error(log, "Failed to load type: " + clss + " from currentdomain"); throw new GxClassLoaderException("Failed to load type: " + clss); } } loadedAssemblies[clss] = objType; } return(objType); }
//Insert image from local file in web transacion, storage enabled, image_gxi = myimage.jpg, image = http://amazon...s3./PrivateTempStorage/myimage.jpg (after a getMultimediaValue(imgTransaction003Image_Internalname, ref A175TransactionImage, ref A40000TransactionImage_GXI); //Update image from dataprovider (KB image object), storage enabled, image_gxi = "file:///C:/Models/Cahttea/Data017/web/Resources/Carmine/myimage.png", image: ".\\Resources/Carmine/myimage.png" //Insert KB image from Dataprovider in dynamic transaction image_gxi vacio, image= .\Resources\myimage.png, //Second execution of Dataprovider that updates images, CategoryImage = calendar.Link(), image_gxi=https://chatteatest.s3.amazonaws.com/TestPGXReleased/Category/CategoryImage/calendar_dc0ca2d9335a484cbdc2d21fc7568af7.png, copy falla, multimediaUri = image_gxi; #pragma warning disable SCS0018 // Path traversal: injection possible in {1} argument passed to '{0}' public void SetParameterMultimedia(int id, string image_gxi, string image, string tableName, string fieldName) { bool storageServiceEnabled = !string.IsNullOrEmpty(tableName) && !string.IsNullOrEmpty(fieldName) && (GXServices.Instance != null && GXServices.Instance.Get(GXServices.STORAGE_SERVICE) != null); if (GxRestUtil.IsUpload(image)) { image = GxRestUtil.UploadPath(image); } if (GxRestUtil.IsUpload(image_gxi)) { image_gxi = GxRestUtil.UploadPath(image_gxi); } if (String.IsNullOrEmpty(image)) { _gxDbCommand.SetParameter(id - 1, image_gxi); } else { string multimediaUri = string.Empty; if (storageServiceEnabled) { //image_gxi not empty => process image_gxi if (!String.IsNullOrEmpty(image_gxi)) { if (PathUtil.IsAbsoluteUrl(image_gxi)) //http://, https://, ftp:// { string objectName; //file is already on the cloud p.e. https://s3.amazonaws.com/Test/PublicTempStorage/multimedia/Image_ad013b5b050c4bf199f544b5561d9b92.png //Must be copied to https://s3.amazonaws.com/Test/TableName/FieldName/Image_ad013b5b050c4bf199f544b5561d9b92.png if (ServiceFactory.GetExternalProvider().GetObjectNameFromURL(image_gxi, out objectName)) { try { multimediaUri = ServiceFactory.GetExternalProvider().Copy(image_gxi, GXDbFile.GenerateUri(image_gxi, !GXDbFile.HasToken(image_gxi), false), tableName, fieldName, GxFileType.PublicAttribute); GXLogging.Debug(log, "Copy file already in ExternalProvider:", multimediaUri); } catch (Exception ex) { multimediaUri = image_gxi; //it is trying to copy an object to itself without changing the object's metadata GXLogging.Warn(log, ex, "Copy file to itself filed in ExternalProvider:", image_gxi); } } else //image_gxi url is in another cloud { try { using (var fileStream = new MemoryStream(new WebClient().DownloadData(image_gxi))) { //Cannot pass Http Stream directly, because some Providers (AWS S3) does not support Http Stream. multimediaUri = ServiceFactory.GetExternalProvider().Save(fileStream, GXDbFile.GenerateUri(image_gxi, !GXDbFile.HasToken(image_gxi), false), tableName, fieldName, GxFileType.Public); GXLogging.Debug(log, "Upload external file to ExternalProvider:", multimediaUri); } } catch (WebException) { multimediaUri = image_gxi; } } } else { Uri uri; string fileFullName = string.Empty; if (Uri.TryCreate(image_gxi, UriKind.Absolute, out uri)) //file:// { fileFullName = uri.AbsolutePath; Stream fileStream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read); String fileName = PathUtil.GetValidFileName(fileFullName, "_"); using (fileStream) { multimediaUri = ServiceFactory.GetExternalProvider().Save(fileStream, GXDbFile.GenerateUri(fileName, !GXDbFile.HasToken(fileName), false), tableName, fieldName, GxFileType.Public); GXLogging.Debug(log, "Upload file (_gxi) to ExternalProvider:", multimediaUri); } } else //relative image name=> Assume it is a local file on the cloud, because storageService is Enabled. { try { multimediaUri = ServiceFactory.GetExternalProvider().Copy(image, GXDbFile.GenerateUri(image_gxi, !GXDbFile.HasToken(image_gxi), false), tableName, fieldName, GxFileType.Public); GXLogging.Debug(log, "Copy external file in ExternalProvider:", multimediaUri); } catch (Exception e) { GXLogging.Warn(log, e, "Could not copy external file in ExternalProvider:", image); //If Image is not in Cloud Storage, then we look if we can find it in the hard drive. This is the case for Relative paths using Image.FromImage() //If file is not available, exception must be thrown multimediaUri = PushToExternalProvider(new FileStream(image, FileMode.Open, FileAccess.Read), GXDbFile.GenerateUri(image_gxi, !GXDbFile.HasToken(image_gxi), false), tableName, fieldName); GXLogging.Debug(log, "Upload file to ExternalProvider:", multimediaUri); } } } } //image_gxi is empty => process image else if (!String.IsNullOrEmpty(image)) { var fileName = PathUtil.GetValidFileName(image, "_"); try { Stream fileStream; if (!PathUtil.IsAbsoluteUrl(image)) //Assume it is a local file { image = Path.Combine(GxContext.StaticPhysicalPath(), image); fileStream = new FileStream(image, FileMode.Open, FileAccess.Read); } else { WebClient c = new WebClient(); fileStream = new MemoryStream(c.DownloadData(image)); //Cannot pass Http Stream directly, because some Providers (AWS S3) does not support Http Stream. } string externalFileName = GXDbFile.GenerateUri(fileName, !GXDbFile.HasToken(fileName), false); multimediaUri = PushToExternalProvider(fileStream, externalFileName, tableName, fieldName); } catch (WebException) //403 forbidden, parm = url in external provider that has been deleted { multimediaUri = image_gxi; } } } //image_gxi not empty => process image_gxi else if (!String.IsNullOrEmpty(image_gxi)) { multimediaUri = GXDbFile.GenerateUri(PathUtil.GetValidFileName(image_gxi, "_"), !GXDbFile.HasToken(image_gxi), true); } //image_gxi is empty => process image else if (!String.IsNullOrEmpty(image)) { multimediaUri = GXDbFile.GenerateUri(PathUtil.GetValidFileName(image, "_"), !GXDbFile.HasToken(image), true); } _gxDbCommand.SetParameter(id - 1, multimediaUri); } }
public void Receive(GXPOP3Session sessionInfo, GXMailMessage gxmessage) { if (client == null) { LogError("Login Error", "Must login", MailConstants.MAIL_CantLogin); return; } if (lastReadMessage == count) { LogDebug("No messages to receive", "No messages to receive", MailConstants.MAIL_NoMessages); return; } try { if (count > lastReadMessage) { Message m = null; try { m = client.GetMessage(++lastReadMessage); } catch (Exception e) { LogError("Receive message error", e.Message, MailConstants.MAIL_ServerRepliedErr, e); } if (m != null) { MailMessage msg; try { msg = m.ToMailMessage(); } catch (ArgumentException ae) { GXLogging.Error(log, "Receive message error " + ae.Message + " subject:" + m.Headers.Subject, ae); PropertyInfo subjectProp = m.Headers.GetType().GetProperty("Subject"); string subject = m.Headers.Subject; if (HasCROrLF(subject)) { subjectProp.SetValue(m.Headers, subject.Replace('\r', ' ').Replace('\n', ' ')); GXLogging.Warn(log, "Replaced CR and LF in subject " + m.Headers.Subject); } msg = m.ToMailMessage(); } using (msg) { gxmessage.From = new GXMailRecipient(msg.From.DisplayName, msg.From.Address); SetRecipient(gxmessage.To, msg.To); SetRecipient(gxmessage.CC, msg.CC); gxmessage.Subject = msg.Subject; if (msg.IsBodyHtml) { gxmessage.HTMLText = msg.Body; MessagePart plainText = m.FindFirstPlainTextVersion(); if (plainText != null) { gxmessage.Text += plainText.GetBodyAsText(); } } else { gxmessage.Text = msg.Body; } if (msg.ReplyToList != null && msg.ReplyToList.Count > 0) { SetRecipient(gxmessage.ReplyTo, msg.ReplyToList); } gxmessage.DateSent = m.Headers.DateSent; if (gxmessage.DateSent.Kind == DateTimeKind.Utc && GeneXus.Application.GxContext.Current != null) { gxmessage.DateSent = DateTimeUtil.FromTimeZone(m.Headers.DateSent, "Etc/UTC", GeneXus.Application.GxContext.Current); } gxmessage.DateReceived = GeneXus.Mail.Internals.Pop3.MailMessage.GetMessageDate(m.Headers.Date); AddHeader(gxmessage, "DispositionNotificationTo", m.Headers.DispositionNotificationTo.ToString()); ProcessMailAttachments(gxmessage, m.FindAllAttachments()); } } } }catch (Exception e) { LogError("Receive message error", e.Message, MailConstants.MAIL_ServerRepliedErr, e); } }