using System; using System.IO; using System.Security; using System.Security.Cryptography; using System.Data; using System.Net; using System.Net.Mail; using System.Net.NetworkInformation; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Drawing; using System.Drawing.Imaging; using System.Web; using MySql.Data.MySqlClient; using System.Text; using System.IO.Compression; namespace WmData{ /// /// Some static common usefull functions. /// public class WmDataTools { public static string makeSureStringHasMinimumLength(string input, int minimumLength, bool appendingWhiteSpaceAfterInput) { int inputLength = input.Length; int difference = minimumLength - inputLength; if (difference > 0) { return appendExtraSpacesToString(input, difference, appendingWhiteSpaceAfterInput); } else { return input; // the string exceeds the minimum length, we're not going to change a thing. } } public static string appendExtraSpacesToString(string input, int extraSpaces, bool afterInput) { string output = input; for (int i = 0; i < extraSpaces; i++) { if (afterInput) { output += " "; } else { output = " " + output; } } return output; } public static bool isHostAvailableViaPing(string host) { bool isAvailable = false; for (int i = 0; i < 10; i++) { PingReply pingReply = getPingReply(host); if (pingReply != null) { isAvailable = (pingReply.Status == IPStatus.Success); } if (isAvailable) { break; // stop looking, we've connect } else { System.Threading.Thread.Sleep(500); } } return isAvailable; } /// /// Performs a ping. If local network errors (that is: if there is no working ethernet), null is returned /// public static PingReply getPingReply(string host) { Ping pingSender = new Ping(); PingOptions options = new PingOptions(); // Use the default Ttl value which is 128, // but change the fragmentation behavior. options.DontFragment = true; // Create a buffer of 32 bytes of data to be transmitted. string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 1000; PingReply reply = null; try { reply = pingSender.Send(host, timeout, buffer, options); } catch(Exception error) { System.Diagnostics.Trace.WriteLine("WmDataTools: Ping Exception: " + error.Message); } return reply; } /// /// Returns true if there is reason to believe that there is an internet connection /// /// public static bool isInternetConnectionAvailable() { bool internetConnectionAvailable = false; bool canReachGoogle = false; try { if (WmDataTools.getInternetResponse("http://www.google.com",5000).Length > 0) { canReachGoogle = true; } } catch { } bool canReachMicrosoft = false; try { if (WmDataTools.getInternetResponse("http://www.microsoft.com", 5000).Length > 0) { canReachMicrosoft = true; } } catch { } internetConnectionAvailable = canReachGoogle || canReachMicrosoft; return internetConnectionAvailable; } /// /// Makes a request and returns the response in a string. /// /// URL to fetch. /// public static string getInternetResponse(string url, int timeoutMilliSeconds) { // used to build entire input System.Text.StringBuilder sb = new System.Text.StringBuilder(); // used on each read operation byte[] buf = new byte[8192]; // prepare the web page we will be asking for HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Referer = url; request.Timeout = timeoutMilliSeconds; request.UserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; nl-nl) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8"; // execute the request HttpWebResponse response = (HttpWebResponse) request.GetResponse(); // we will read data via the response stream Stream resStream = response.GetResponseStream(); string tempString = null; int count = 0; do { // fill the buffer with data count = resStream.Read(buf, 0, buf.Length); // make sure we read some data if (count != 0) { // translate from bytes to ASCII text tempString = System.Text.Encoding.ASCII.GetString(buf, 0, count); // continue building the string sb.Append(tempString); } } while (count > 0); // any more data to read? return sb.ToString(); } public static string compress(string text) { byte[] buffer = Encoding.UTF8.GetBytes(text); MemoryStream ms = new MemoryStream(); using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { zip.Write(buffer, 0, buffer.Length); } ms.Position = 0; MemoryStream outStream = new MemoryStream(); byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); return Convert.ToBase64String(gzBuffer); } public static string decompress(string compressedText) { byte[] gzBuffer = Convert.FromBase64String(compressedText); using (MemoryStream ms = new MemoryStream()) { int msgLength = BitConverter.ToInt32(gzBuffer, 0); ms.Write(gzBuffer, 4, gzBuffer.Length - 4); byte[] buffer = new byte[msgLength]; ms.Position = 0; using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress)) { zip.Read(buffer, 0, buffer.Length); } return Encoding.UTF8.GetString(buffer); } } /// /// Generates a WHERE select statement like: "selectPropertyName in (obj1.PropertyName.Value, obj2.PropertyName.Value, obj3.PropertyName.Value) /// /// object array that is used to build the select range /// name of the property where the select statement is aimed at (e.g. a Id) /// name of the property in the select statement "selectPropertyName IN (.. /// ready to use select statement public static string getInRangeSelect(WmIntermediateObject intermediateObject, object[] objects, string propertyName, string selectPropertyName) { return getInRangeSelect(intermediateObject, objects, propertyName, selectPropertyName, false); } public static string getInRangeSelect(WmIntermediateObject intermediateObject, object[] objects, string propertyName, string selectPropertyName, bool useNotInStatement) { WmIntermediateObjectProperty property = intermediateObject.getProperty(propertyName); string inRangeSelect = "false"; if (objects.Length > 0) { if (!useNotInStatement) { inRangeSelect = selectPropertyName.ToLower() + " IN ("; } else { inRangeSelect = selectPropertyName.ToLower() + " NOT IN ("; } foreach (object obj in objects) { object propertyValue = property.Getter(obj); inRangeSelect += propertyValue + ","; } inRangeSelect = inRangeSelect.Substring(0, inRangeSelect.Length - 1) + ")"; } return inRangeSelect; } /// /// Generates a WHERE select statement like: "selectPropertyName in (values[0].ToString(), values[1].Tostring) /// /// /// /// public static string getInRangeSelect(string selectPropertyName, int[] values) { string inRangeSelect = "false"; if (values.Length > 0) { inRangeSelect = selectPropertyName.ToLower() + " IN ("; foreach (int propertyValue in values) { inRangeSelect += propertyValue + ","; } inRangeSelect = inRangeSelect.Substring(0, inRangeSelect.Length - 1) + ")"; } return inRangeSelect; } // inRangeSelect += "'" + WmDataTools.getSafeString(propertyValue.ToString()) + "',"; /// /// Generates a WHERE select statement like: "selectPropertyName in (values[0].ToString(), values[1].Tostring) /// /// /// /// public static string getInRangeSelect(string selectPropertyName, string[] values) { string inRangeSelect = "false"; if (values.Length > 0) { inRangeSelect = selectPropertyName.ToLower() + " IN ("; foreach (string propertyValue in values) { inRangeSelect += "'" + WmDataTools.getSafeString(propertyValue.ToString()) + "',"; } inRangeSelect = inRangeSelect.Substring(0, inRangeSelect.Length - 1) + ")"; } return inRangeSelect; } /// /// Generates a WHERE select statement like: "selectPropertyName in (values[0].ToString(), values[1].Tostring) /// /// /// /// public static string getInRangeSelect(string selectPropertyName, object[] values) { string inRangeSelect = "false"; if (values.Length > 0) { bool isNumber = (values[0]is int) || (values[0] is long); inRangeSelect = selectPropertyName.ToLower() + " IN ("; foreach (object propertyValue in values) { if(isNumber){ inRangeSelect += "'" + WmDataTools.getSafeString(propertyValue.ToString()) + "',"; }else{ inRangeSelect += "'" + WmDataTools.getSafeString(propertyValue.ToString()) + "',"; } } inRangeSelect = inRangeSelect.Substring(0, inRangeSelect.Length - 1) + ")"; } return inRangeSelect; } /// /// This is an essential function for any unsafe strings /// to prevent SQL injections that _are_ possible with DirectData (in comp. to the original data) /// public static string getSafeString(string unsafeString) { if (unsafeString == null) { return null; } // SQL Encoding for MySQL Recommended here: // http://au.php.net/manual/en/function.mysql-real-escape-string.php // it escapes \r, \n, \x00, \x1a, baskslash, single quotes, and double quotes return Regex.Replace(unsafeString, @"[\r\n\x00\x1a\\'""]", @"\$0"); } /// /// Returns a NameValueCollection containing all properties matching of the objectInstance /// public static NameValueCollection getNameValueCollectionFromObjectInstance(WmIntermediateObject intermediateObject, object objectInstance) { NameValueCollection nameValueCollection = new NameValueCollection(); foreach (WmIntermediateObjectProperty objectProperty in intermediateObject.Properties) { object propertyValue = objectProperty.Getter.Invoke(objectInstance); if(propertyValue is DBNull || propertyValue == null){ propertyValue = "##NULL##"; } nameValueCollection[objectProperty.DataName] = propertyValue.ToString(); } return nameValueCollection; } /// /// Returns a NameValueCollection containing all properties matching the data row /// public static NameValueCollection getNameValueCollectionFromDataRow(DataRow dataRow) { NameValueCollection nameValueCollection = new NameValueCollection(); foreach (DataColumn dataColumn in dataRow.Table.Columns) { object propertyValue = dataRow[dataColumn.ColumnName]; if(propertyValue is DBNull || propertyValue == null){ propertyValue = "##NULL##"; } nameValueCollection[dataColumn.ColumnName] = propertyValue.ToString(); } return nameValueCollection; } /// /// Returns a Name Value collection created from a query string /// public static NameValueCollection getNameValueCollectionFromQueryString(string queryString) { NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(queryString); return nameValueCollection; } /// /// Returns a HtmlEncoded query string from a name value collection /// public static string getQueryStringFromNameValueCollection(NameValueCollection parameters) { List items = new List(); foreach (String name in parameters.AllKeys) { items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name]))); } return String.Join("&", items.ToArray()); } /// /// This function logically combines two select statements. This is a powerfull tool to create complex search statements /// public static string combineSelectStatements(string select1, string select2, LogicalOperand logicalOperand) { if (select1 == null && select2 == null) { return null; } else if (select1 == null && select2 != null) { return select2; } else if (select1 != null && select2 == null) { return select1; } else { return "(" + select1 + ") " + logicalOperand.ToString() + " (" + select2 + ")"; } } public static MySqlCommand getMySqlInsertCommand(WmDataBaseCredentials databaseCredentials, WmIntermediateObject intermediateObject) { MySqlCommand insertCommand = new MySqlCommand(); string insertSql = "INSERT INTO " + databaseCredentials.Catalog + "." + intermediateObject.TableName + " (#COLUMNS#) VALUES (#VALUES#)"; string insertColumnsTmp = ""; string insertValuesTmp = ""; foreach(WmIntermediateObjectProperty property in intermediateObject.Properties){ insertColumnsTmp += intermediateObject.TableName + "." + property.DataName + ","; insertValuesTmp += "?" + property.DataName + ","; insertCommand.Parameters.Add("?" + property.DataName, getMySqlDbTypeFromProperty(property.Type), 0, property.DataName); } insertColumnsTmp = insertColumnsTmp.Substring(0, insertColumnsTmp.Length - 1); // remove last obsolete , insertValuesTmp = insertValuesTmp.Substring(0, insertValuesTmp.Length - 1); // remove last obsolete , insertSql = insertSql.Replace("#COLUMNS#", insertColumnsTmp); // set columnTmp on its position insertSql = insertSql.Replace("#VALUES#", insertValuesTmp); // set valueTmp on its position insertCommand.CommandText = insertSql; return insertCommand; } public static MySqlCommand getMySqlUpdateCommand(WmDataBaseCredentials databaseCredentials, WmIntermediateObject intermediateObject) { MySqlCommand updateCommand = new MySqlCommand(); string updatePropTmp = ""; string updateSql = "UPDATE " + databaseCredentials.Catalog + "." + intermediateObject.TableName + " SET #PROPERTIES# WHERE id=?id"; foreach (WmIntermediateObjectProperty property in intermediateObject.Properties) { updatePropTmp += intermediateObject.TableName + "." + property.DataName + "=?" + property.DataName + ","; updateCommand.Parameters.Add("?" + property.DataName, getMySqlDbTypeFromProperty(property.Type), 0, property.DataName); } updatePropTmp = updatePropTmp.Substring(0, updatePropTmp.Length - 1); updateSql = updateSql.Replace("#PROPERTIES#", updatePropTmp); updateCommand.CommandText = updateSql; return updateCommand; } public static MySqlCommand getMySqlDeleteCommand(WmDataBaseCredentials databaseCredentials, WmIntermediateObject intermediateObject) { MySqlCommand deleteCommand = new MySqlCommand(); string deleteSql = "DELETE FROM "+databaseCredentials.Catalog+"." + intermediateObject.TableName + " WHERE id=?id"; deleteCommand.Parameters.Add("?id",MySqlDbType.Int32,0,"id"); deleteCommand.CommandText = deleteSql; return deleteCommand; } public static MySqlDbType getMySqlDbTypeFromProperty(Type propType) { if (propType.Equals(typeof(int))) { return MySqlDbType.Int32; } else if (propType.Equals(typeof(double))) { return MySqlDbType.Double; } else if (propType.Equals(typeof(long))) { return MySqlDbType.Int64; } else if (propType.Equals(typeof(bool))) { return MySqlDbType.Bit; } else if (propType.Equals(typeof(DateTime))) { return MySqlDbType.DateTime; } else if (propType.Equals(typeof(string))) { return MySqlDbType.VarChar; } else { return MySqlDbType.Int32; } } /// /// Returns the correct table name based upon an instance of an object /// public static string getTableName(object objectInstance) { return getTableName(objectInstance.GetType()); } /// /// Returns the correct table name based upon a system type /// public static string getTableName(Type objectType) { return objectType.Name.ToLower(); } /// /// Returns the correct table name based upon a DataRow /// public static string getTableName(DataRow rowOfTable) { return rowOfTable.Table.TableName; } public static string getSha1Hash(string input) { Byte[] clearBytes = System.Text.Encoding.UTF8.GetBytes(input); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); sha1.ComputeHash(clearBytes); Byte[] hashedBytes = sha1.Hash; sha1.Clear(); string hash = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); return hash; } public static object copyObjectInstance(object originalInstance) { Type objectType = originalInstance.GetType(); return copyObjectInstance(objectType, originalInstance); } public static object copyObjectInstance(Type targetType, object originalInstance) { Type sourceType = originalInstance.GetType(); object newInstance = targetType.GetConstructor(Type.EmptyTypes).Invoke(null); foreach (PropertyInfo targetPropInfo in targetType.GetProperties()) { PropertyInfo sourcePropInfo = sourceType.GetProperty(targetPropInfo.Name); if (sourcePropInfo != null) { object originalValue = sourcePropInfo.GetValue(originalInstance, null); if (checkDataNeed(sourcePropInfo.PropertyType)) { targetPropInfo.SetValue(newInstance, originalValue, null); } } } return newInstance; } /// /// Returns a real object instance with values from the proxy object /// /// The instance of the proxy object /// public static object getRealObjectFromProxyObject( Type targetType, object proxyObject) { Type proxyType = proxyObject.GetType(); object realObject = WmIntermediateObjectTools.GetInstanceCreator(targetType).Invoke(); // Extract the data from the proxy object. foreach (PropertyInfo propInfo in targetType.GetProperties()) { if (checkDataNeed(propInfo.PropertyType)) { PropertyInfo proxyFieldInfo = proxyType.GetProperty(propInfo.Name); if (proxyFieldInfo != null) { object propValue = proxyFieldInfo.GetValue(proxyObject, null); propInfo.SetValue(realObject, propValue, null); } else { System.Diagnostics.Trace.WriteLine("WmDataTools: getRealObjectFromProxyObject: Real object property " + propInfo.Name + " was not found in proxy object"); } } } return realObject; } #region Encoding and Decoding strings /// /// Encodes a string using the standard WM Manager encoding /// /// String to encode /// Encoded string public static string encode(string input){ string output = encode(input, "Cr@zYh@sH-defaultwebsite"); return output; } public static string encode(string input,string key) { string output = EncDec.Encrypt(input, key); return output; } /// /// Decodes an encoded string. Will throw an error on failure. /// /// Encoded string /// decoded string public static string decode(string input){ string output = decode(input,"Cr@zYh@sH-defaultwebsite"); return output; } public static string decode(string input,string key) { string output = EncDec.Decrypt(input,key); return output; } #endregion /// /// Indicates if the specified type is a easy-to-transport type (like int, bool, double, but not WmPageContent or some custom thing) /// /// /// public static bool checkDataNeed(System.Type type){ #region Check need to save property (if it is not a child or arraylist object) if( type.Equals(typeof(System.Int16)) || type.Equals(typeof(System.String)) || type.Equals(typeof(System.Double)) || type.Equals(typeof(System.DateTime)) || type.Equals(typeof(System.Boolean)) || type.Equals(typeof(System.Int32)) || type.Equals(typeof(System.Int64))){ return true; }else{ return false; } #endregion } /// /// Compares two objects, returns true if objects are the same. /// Use this function to compare for instance a couple of value containing objects /// /// /// /// public static bool compareObjects(object a, object b){ if(a is string){ string aStr = (string)a; string bStr = (string)b; if (String.IsNullOrEmpty(aStr) && String.IsNullOrEmpty(bStr)) { return true; } else { return aStr.Equals(bStr); } }else if(a is int){ int aInt = (int) a; int bInt = (int) b; return aInt == bInt; } else if (a == null) { return b == null; // both a and b will be null then } else { return a.Equals(b); } } /// /// Convert string to lowercase /// /// /// public static String Lower(String strParam) { return strParam.ToLower(); } /// /// Converts a string to uppercase /// /// /// public static String Upper(String strParam) { return strParam.ToUpper(); } /// /// Counts amount of words in string /// /// /// public static int wordCount(string input) { //String strProper=strParam.Substring(0,1).ToUpper(); //strParam=strParam.Substring(1).ToLower(); input = WmDataTools.ToSingleSpace(input); string strPrev=""; int count = 0; for(int iIndex=0;iIndex1) { strPrev=input.Substring(iIndex-1,1); } if( strPrev.Equals(" ") || strPrev.Equals("\t") || strPrev.Equals("\n") || strPrev.Equals(".")) { count ++; } } return count; } /// /// Walks the given input and returns the first word. /// /// Input string /// First word public static string getFirstWord(string input){ input = input.Trim(); int indexS = input.IndexOf(" "); int indexT = input.IndexOf("\t"); int indexN = input.IndexOf("\n"); int indexP = input.IndexOf("."); if(indexS != -1 || indexT != -1 || indexN != -1 || indexP!=-1){ // There is something to look for... // It's simple, look for the closesd closing char... // its likely that it might be a space [ ] int closePos = indexS; // Check if the \t is closer than the space if(closePos > indexT && indexT!=-1){ closePos = indexT; } // Check if the \n is closer than previous if(closePos > indexN && indexN!=-1){ closePos = indexN; } // Check if the period (.) is closer than previous if(closePos > indexP && indexP!=-1){ closePos = indexP; } return input.Substring(0,closePos); }else{ return input.Trim(); } } /// /// Function to Reverse the String /// /// /// public static String Reverse(String strParam) { if(strParam.Length==1) { return strParam; } else { return Reverse(strParam.Substring(1)) + strParam.Substring(0,1); } } /// /// Function to count no.of occurences of Substring in Main string /// /// /// /// public static int CharCount(String strSource,String strToCount) { int iCount=0; int iPos=strSource.IndexOf(strToCount); while(iPos!=-1) { iCount++; strSource=strSource.Substring(iPos+1); iPos=strSource.IndexOf(strToCount); } return iCount; } /// /// Function to count no.of occurences of Substring in Main string /// /// /// /// public static int CharCount(String strSource,String strToCount,bool IgnoreCase) { if(IgnoreCase) { return CharCount(strSource.ToLower(),strToCount.ToLower()); } else { return CharCount(strSource,strToCount); } } /// /// Trims the whole string to single spaces /// /// /// public static string ToSingleSpace(String strParam) { int iPosition=strParam.IndexOf(" "); if(iPosition==-1) { return strParam; } else { return ToSingleSpace(strParam.Substring(0,iPosition) + strParam.Substring(iPosition+1)); } } /// /// Replace string function /// /// /// /// /// public string Replace(String strText,String strFind,String strReplace) { int iPos=strText.IndexOf(strFind); String strReturn=""; while(iPos!=-1) { strReturn+=strText.Substring(0,iPos) + strReplace; strText=strText.Substring(iPos+strFind.Length); iPos=strText.IndexOf(strFind); } if(strText.Length>0) strReturn+=strText; return strReturn; } /// /// Tests if a certain string is a palingdrome /// /// /// public static bool IsPalindrome(String strParam) { int iLength,iHalfLen; iLength=strParam.Length-1; iHalfLen=iLength/2; for(int iIndex=0;iIndex<=iHalfLen;iIndex++) { if(strParam.Substring(iIndex,1)!=strParam.Substring(iLength-iIndex,1)) { return false; } } return true; } /// /// Returns a string cut to a maximum amount of chars. /// /// Maximum amout of chars /// input string /// true if you want three nice dots behind the string if cut was applied /// public static string getSubString(int maxChar,string input, bool addDots){ input = WmDataTools.ToSingleSpace(input); int dotOffset = 3; if(!addDots){ dotOffset = 0; } if((maxChar > 0) && ((input.Length+dotOffset) > maxChar) && (input.Length > maxChar)){ if(addDots){ input = input.Substring(0,maxChar)+"..."; }else{ input = input.Substring(0,maxChar); } } return input; } /// /// Cleans a certain piece of HTML (removes word carbage) /// /// /// public static string cleanHtmlString(string input){ input = WmDataTools.cleanWordHtml(input); input = WmDataTools.fixEntities(input); return input; } /// /// Cleans word HTML by removing stupid tags /// /// /// public static string cleanWordHtml(string html){ StringCollection sc = new StringCollection(); // get rid of unnecessary tag spans (comments and title) sc.Add(@""); sc.Add(@"(\w|\W)+?"); // Get rid of classes and styles sc.Add(@"\s?class=\w+"); sc.Add(@"\s+style='[^']+'"); // Get rid of unnecessary tags sc.Add( @"<(meta|link|/?o:|/?style|/?div|/?st\d|/?head|/?html|body|/?body|/?span|!\[)[^>]*?>"); // Get rid of empty paragraph tags sc.Add(@"(<[^>]+>)+ ()+"); // remove bizarre v: element attached to tag sc.Add(@"\s+v:\w+=""[^""]+"""); // remove extra lines sc.Add(@"(\n\r){2,}"); foreach (string s in sc){ html = Regex.Replace(html, s, "", RegexOptions.IgnoreCase); } return html; } /// /// Converts certain characters to their HTML unicode equivalent & for instance /// /// /// public static string fixEntities(string html){ NameValueCollection nvc = new NameValueCollection(); nvc.Add("“", "“"); nvc.Add("”", "”"); nvc.Add("–", "—"); foreach (string key in nvc.Keys){ html = html.Replace(key, nvc[key]); } return html; } /// /// This is a handy function to capitalize the first char after a /// space, period, tab or return. /// /// /// public static String PCase(String strParam) { String strProper=strParam.Substring(0,1).ToUpper(); strParam=strParam.Substring(1).ToLower(); String strPrev=""; for(int iIndex=0;iIndex1) { strPrev=strParam.Substring(iIndex-1,1); } if( strPrev.Equals(" ") || strPrev.Equals("\t") || strPrev.Equals("\n") || strPrev.Equals(".")) { strProper+=strParam.Substring(iIndex,1).ToUpper(); } else { strProper+=strParam.Substring(iIndex,1); } } return strProper; } /// /// Returns the image codec info of the specified mimeType (JPG) /// /// /// public static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } } }