Пример #1
0
		internal static System.String GetFileName ( System.String name ) {
			if ( name==null || name.Length==0 )
				return name;
			name = name.Replace("\t", "");
			try {
				name = System.IO.Path.GetFileName(name);
			} catch ( System.ArgumentException ) {
				// Remove invalid chars
				foreach ( char ichar in System.IO.Path.GetInvalidPathChars() ) {
					name = name.Replace ( ichar.ToString(), System.String.Empty );
				}
				name = System.IO.Path.GetFileName(name);
			}
			try {
				System.IO.FileInfo fi = new System.IO.FileInfo(name);
				if ( fi!=null )
					fi = null;
			} catch ( System.ArgumentException ) {
				name = null;
#if LOG
				if ( log.IsErrorEnabled ) {
					log.Error(System.String.Concat("Filename [", name, "] is not allowed by the filesystem"));
				}
#endif
			}
			return name;
		}
Пример #2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static System.Single Parse(System.String s)
 {
     if (s.EndsWith("f") || s.EndsWith("F"))
         return System.Single.Parse(s.Substring(0, s.Length - 1).Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator));
     else
         return System.Single.Parse(s.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator));
 }
        public void Should_replace_an_item_with_a_sequence_of_items()
        {
            var items = new[] {1, 2, 3, 1, 5};
            var replaced = items.Replace(1, 6, 7).ToArray();

            Assert.That(replaced, Is.EquivalentTo(new[] {6, 7, 2, 3, 6, 7, 5}));
        }
Пример #4
0
		/// <summary>Initialize member variable setting the base file path</summary>
		/// <param name="basePath">representing base path location
		/// </param>
		public FileGenerator(System.String basePath)
		{
			// make sure there is a \ appended to ouput director path
			System.Console.Out.WriteLine(basePath);
			this.basePath = basePath.Replace('\\', '/');
			if ((basePath[basePath.Length - 1]) != '/')
				basePath = basePath + "/";
		}
        public void GeneralityOfReplace()
        {
            var input = new[] { "Hello", "World", "Bye", "Again" };
            var replaced = input.Replace(x => x.StartsWith("A"), x => new[] { x.ToLower()});
            var result = string.Join(", ", replaced);

            Assert.AreEqual("Hello, World, Bye, again", result);
        }
Пример #6
0
 public void ReplaceStringInSequence()
 {
     var seq = new[] { "foo", "bar", "baz", "qux", "corge", "grault" };
     var actual = seq.Replace("quux", "qux");
     Assert.Equal(
         new[] { "foo", "bar", "baz", "quux", "corge", "grault" },
         actual);
 }
Пример #7
0
 public static System.Double Parse(System.String s)
 {
     try
     {
         return System.Double.Parse(s.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator));
     }
     catch (OverflowException)
     {
         return System.Double.MaxValue;
     }
 }
Пример #8
0
        /// <summary>
        /// Parse a rfc 2822 date and time specification. rfc 2822 section 3.3
        /// </summary>
        /// <param name="date">rfc 2822 date-time</param>
        /// <returns>A <see cref="System.DateTime" /> from the parsed header body</returns>
        public static System.DateTime parseDate( System.String date )
        {
            if ( date==null || date.Equals(System.String.Empty) )
                return System.DateTime.MinValue;
            System.DateTime msgDateTime;
            date = anmar.SharpMimeTools.SharpMimeTools.uncommentString (date);
            msgDateTime = new System.DateTime (0);
            try {
                // TODO: Complete the list
                date = date.Replace("UT", "+0000");
                date = date.Replace("GMT", "+0000");
                date = date.Replace("EDT", "-0400");
                date = date.Replace("EST", "-0500");
                date = date.Replace("CDT", "-0500");
                date = date.Replace("MDT", "-0600");
                date = date.Replace("MST", "-0600");
                date = date.Replace("EST", "-0700");
                date = date.Replace("PDT", "-0700");
                date = date.Replace("PST", "-0800");

                date = date.Replace("AM", System.String.Empty);
                date = date.Replace("PM", System.String.Empty);
                int rpos = date.LastIndexOfAny(new Char[]{' ', '\t'});
                if (rpos>0 && rpos != date.Length - 6)
                    date = date.Substring(0, rpos + 1) + "-0000";
                date = date.Insert(date.Length-2, ":");
                msgDateTime = DateTime.ParseExact(date,
                    _date_formats,
                    System.Globalization.CultureInfo.CreateSpecificCulture("en-us"),
                    System.Globalization.DateTimeStyles.AllowInnerWhite);
            #if LOG
            } catch ( System.Exception e ) {
                if ( log.IsErrorEnabled )
                    log.Error(System.String.Concat("Error parsing date: [", date, "]"), e);
            #else
            } catch ( System.Exception ) {
            #endif
                msgDateTime = new System.DateTime (0);
            }
            return msgDateTime;
        }
Пример #9
0
	/// <summary>
	/// Gets the loader specified in the configuration file.
	/// </summary>
	/// <returns>TemplateLoader</returns>
	public static ResourceLoader getLoader(RuntimeServices rs, System.String loaderClassName) {
	    ResourceLoader loader = null;

	    try {
		// since properties are parsed into arrays with commas, something else needed to be used
		loaderClassName = loaderClassName.Replace(';', ',');
		Type loaderType = System.Type.GetType(loaderClassName);
		Object o = System.Activator.CreateInstance(loaderType);
		loader = (ResourceLoader) o;

		rs.info("Resource Loader Instantiated: " + loader.GetType().FullName);

		return loader;
	    } catch (System.Exception e) {
		rs.error("Problem instantiating the template loader.\n" + "Look at your properties file and make sure the\n" + "name of the template loader is correct. Here is the\n" + "error: " + StringUtils.stackTrace(e));
		throw new System.Exception("Problem initializing template loader: " + loaderClassName + "\nError is: " + StringUtils.stackTrace(e));
	    }
	}
Пример #10
0
        public static System.String escape(System.String text, EncodingCharacters encChars)
        {
            //First, take all special characters and replace them with something that is garbled
            for(int i=0;i<SPECIAL_ENCODING_VALUES.Length;i++)
            {
                string specialValues = SPECIAL_ENCODING_VALUES[i];
                text = text.Replace(specialValues, EncodeSpecialCharacters(i.ToString()));
            }
            //Encode each escape character
                        System.Collections.Hashtable esc = getEscapeSequences(encChars);
            System.Text.StringBuilder result = new System.Text.StringBuilder();
            SupportClass.SetSupport keys = new SupportClass.HashSetSupport(esc.Keys);
            System.String escChar = System.Convert.ToString(encChars.EscapeCharacter);
            int position = 0;
            while (position < text.Length)
            {
                System.Collections.IEnumerator it = keys.GetEnumerator();
                bool isReplaced = false;
                while (it.MoveNext() && !isReplaced)
                {
                    System.String seq = (System.String) it.Current;
                    System.String val = (System.String) esc[seq];
                    if (text.Substring(position, 1).Equals(val))
                    {
                        result.Append(seq);
                        isReplaced = true;
                    }
                }
                if (!isReplaced)
                {
                    result.Append(text.Substring(position, 1));
                }
                position++;
            }

            //Replace each garbled entry with the correct special value
            for(int i=0;i<SPECIAL_ENCODING_VALUES.Length;i++)
            {
                string specialValues = SPECIAL_ENCODING_VALUES[i];
                result.Replace(EncodeSpecialCharacters(i.ToString()), specialValues);
            }
            return result.ToString();
        }
Пример #11
0
		/// <summary>this method writes the GeneratedClass object to disk</summary>
		/// <param name="gc">the object to be written to disk
		/// </param>
		/// <param name="packageName">representing the packageName
		/// </param>
		/// <param name="fileName">representing the file name
		/// </param>
		/// <exception cref="IOException">if unable to create file
		/// </exception>
		public virtual void  storeFile(GeneratedClass gc, System.String packageName, System.String fileName)
		{
			
			//format package name
			packageName = packageName.Replace('.', '/');
			
			// set the file path			
            fileName = Regex.Replace(fileName, " ", "") + ".java";
			System.String filePath = basePath + "/" + packageName + "/" + fileName;
			System.IO.FileInfo f = new System.IO.FileInfo(filePath);
			System.Text.StringBuilder dir = new System.Text.StringBuilder();
			
			//check if file exist
			// TODO: Reactivate this once everything works!
			//if(f.exists())
			//	throw new IOException("File already exists");
			
			//create subfolders
			int i = 0;
			while (i < filePath.Length)
			{
				if (filePath[i] != '/')
				{
					dir.Append(filePath[i]);
				}
				else
				{
					dir.Append(filePath[i]);
					System.IO.FileInfo d = new System.IO.FileInfo(dir.ToString());
					System.IO.Directory.CreateDirectory(d.FullName);
				}
				++i;
			}
			
			System.IO.FileStream fstream = new System.IO.FileStream(f.FullName, System.IO.FileMode.Create); /* open file stream */
			System.IO.BinaryWriter ostream = new System.IO.BinaryWriter(fstream); /* open object stream */
			ostream.Write(gc.ToString());
			
			/* clean-up */
			ostream.Flush();
			fstream.Close();
		}
 internal void ReplaceFieldKey(ref System.Text.StringBuilder builder, TemplateOptions options)
 {
     object refVal = this.Value ?? options.NullDisplayText;
     string replacementValue = (this.HasFormatString) ? string.Format(CultureInfo.CurrentUICulture, this.FormatString, (refVal ?? "")) : (refVal ?? "").ToString();
     builder.Replace(this.fieldKey.ToString(), replacementValue);
 }
Пример #13
0
 private System.String ReplaceUrlTokens(System.String url, SharpAttachment attachment)
 {
     if (string.IsNullOrEmpty(url) || url.IndexOf('[') == -1 || url.IndexOf(']') == -1)
         return url;
     if (url.IndexOf("[MessageID]", System.StringComparison.Ordinal) != -1)
     {
         url = url.Replace("[MessageID]", System.Web.HttpUtility.UrlEncode(MimeTools.Rfc2392Url(this.MessageID)));
     }
     if (attachment != null && attachment.ContentID != null)
     {
         if (url.IndexOf("[ContentID]", System.StringComparison.Ordinal) != -1)
         {
             url = url.Replace("[ContentID]", System.Web.HttpUtility.UrlEncode(MimeTools.Rfc2392Url(attachment.ContentID)));
         }
         if (url.IndexOf("[Name]", System.StringComparison.Ordinal) != -1)
         {
             url = url.Replace("[Name]", attachment.SavedFile != null ? System.Web.HttpUtility.UrlEncode(attachment.SavedFile.Name) : System.Web.HttpUtility.UrlEncode(attachment.Name));
         }
     }
     return url;
 }
        public void Replace_SourceIsNull_NullIsReplaced()
        {
            string[] chars = new[] {"a", null, "c"};

            var actual = chars.Replace(null, "b");

            AssertEx.AreEquivalent(actual, "a", "b", "c");
        }
        public void Replace_ReplacementIsNull_ReplacedWithNull()
        {
            string[] chars = new[] {"a", "b", "c"};

            var actual = chars.Replace("b", null);

            AssertEx.AreEquivalent(actual, "a", null, "c");
        }
Пример #16
0
 private System.String ReplaceUrlTokens( System.String url, anmar.SharpMimeTools.SharpAttachment attachment )
 {
     if ( url==null || url.Length==0 || url.IndexOf('[')==-1  || url.IndexOf(']')==-1 )
         return url;
     if ( url.IndexOf("[MessageID]")!=-1 ) {
         url = url.Replace("[MessageID]", System.Web.HttpUtility.UrlEncode(anmar.SharpMimeTools.SharpMimeTools.Rfc2392Url(this.MessageID)));
     }
     if ( attachment!=null && attachment.ContentID!=null ) {
         if ( url.IndexOf("[ContentID]")!=-1 ) {
             url = url.Replace("[ContentID]", System.Web.HttpUtility.UrlEncode(anmar.SharpMimeTools.SharpMimeTools.Rfc2392Url(attachment.ContentID)));
         }
         if ( url.IndexOf("[Name]")!=-1 ) {
             if ( attachment.SavedFile!=null ) {
                 url = url.Replace("[Name]", System.Web.HttpUtility.UrlEncode(attachment.SavedFile.Name));
             } else {
                 url = url.Replace("[Name]", System.Web.HttpUtility.UrlEncode(attachment.Name));
             }
         }
     }
     return url;
 }
Пример #17
0
 /// <summary>
 /// Parse and decode rfc 2047 header body
 /// </summary>
 /// <param name="header">header body to parse</param>
 /// <returns>parsed <see cref="System.String" /></returns>
 public static System.String parserfc2047Header( System.String header )
 {
     header = header.Replace ("\"", System.String.Empty);
     header = anmar.SharpMimeTools.SharpMimeTools.rfc2047decode(header);
     return header;
 }
Пример #18
0
 public void ReplaceNumberInSequence()
 {
     var seq = new[] { 4, 2, 42, 1337, 7 };
     var actual = seq.Replace(9, i => i == 2);
     Assert.Equal(new[] { 4, 9, 42, 1337, 7 }, actual);
 }
Пример #19
0
		public static System.String Uid2url(System.String uid)
		{
			System.String url = uid.Replace('\u0000', '/'); // replace nulls with slashes
			return url.Substring(0, (url.LastIndexOf('/')) - (0)); // remove date from end
		}
Пример #20
0
 /// <summary>
 /// Normalizes lines to account for platform differences.  Macs use
 /// a single \r, DOS derived operating systems use \r\n, and Unix
 /// uses \n.  Replace each with a single \n.
 /// </summary>
 /// <author> <a href="mailto:[email protected]">Sam Ruby</a>
 /// </author>
 /// <returns>
 /// source with all line terminations changed to Unix style
 /// </returns>
 protected internal virtual System.String normalizeNewlines(System.String source)
 {
     //TODO:
     //return perl.substitute("s/\r[\n]/\n/g", source);
     return source.Replace(Environment.NewLine, "|").Replace("\n", "|");
 }
 public virtual double ParseDouble(System.String value_Renamed)
 {
     return System.Double.Parse(value_Renamed.Replace(".", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator));
 }
Пример #22
0
 public static void insert(System.String mac, int offset, byte[] bytes)
 {
     mac = mac.Replace(":", "").Replace("-","");
     long l = System.Convert.ToInt64(mac, 16);
     ArrayHelper.insertLong(bytes, l, offset, 6);
 }
Пример #23
0
 /// <summary>
 /// Replaces characters that are not necessary for comparing (like whitespaces) and diacritics. The result is returned as <see cref="string.ToLowerInvariant"/>.
 /// </summary>
 /// <param name="name">Name to clean up</param>
 /// <returns>Cleaned string</returns>
 protected string RemoveCharacters(string name)
 {
   string result = new[] { "-", ",", "/", ":", " ", " ", ".", "'" }.Aggregate(name, (current, s) => current.Replace(s, ""));
   result = result.Replace("&", "and");
   return StringUtils.RemoveDiacritics(result.ToLowerInvariant());
 }
Пример #24
0
 /// <summary> Return a package name as a relative path name
 /// *
 /// </summary>
 /// <param name="String">package name to convert to a directory.
 /// </param>
 /// <returns>String directory path.
 ///
 /// </returns>
 public static System.String getPackageAsPath(System.String pckge)
 {
     return pckge.Replace('.', System.IO.Path.DirectorySeparatorChar.ToString()[0]) + System.IO.Path.DirectorySeparatorChar.ToString();
 }
Пример #25
0
 /// <summary>
 /// Encodes a Message-ID or Content-ID following RFC 2392 rules. 
 /// </summary>
 /// <param name="input"><see cref="System.String" /> with the Message-ID or Content-ID.</param>
 /// <returns><see cref="System.String" /> with the value encoded as RFC 2392 dictates.</returns> 
 public static System.String Rfc2392Url( System.String input)
 {
     if ( input==null || input.Length<4 )
         return input;
     if ( input.Length>2 && input[0]=='<' && input[input.Length-1]=='>' )
         input = input.Substring(1, input.Length-2);
     if ( input.IndexOf('/')!=-1 ) {
         input = input.Replace("/", "%2f");
     }
     return input;
 }
        public void Replace_MoreOccurrenceForReplacedElement_AllReplacedWithOneElement()
        {
            char[] chars = new[] {'a', 'b', 'b'};

            var actual = chars.Replace('b', 'x').ToArray();

            AssertEx.AreEquivalent(actual, 'a', 'x', 'x');
        }
Пример #27
0
		internal virtual System.Windows.Forms.MenuItem MenuItem(System.String txt, int key, System.Drawing.Image icon, System.Windows.Forms.KeyEventArgs accel)
		{
			System.Windows.Forms.MenuItem mi = new System.Windows.Forms.MenuItem(txt.Replace("" + (char) key, "&" + (char) key));
			mi.Click += new System.EventHandler(this.actionPerformed);
			SupportClass.CommandManager.CheckCommand(mi);
			if (icon != null)
			{
				//UPGRADE_ISSUE: Method 'javax.swing.AbstractButton.setIcon' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaxswingAbstractButtonsetIcon_javaxswingIcon'"
				// mi.setIcon(icon);
			}
            // Handled by the designer code now. 
            //if (accel != null)
            //{
            //    //UPGRADE_WARNING: Method 'javax.swing.JMenuItem.setAccelerator' was converted to 'System.Windows.Forms.MenuItem.Shortcut' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
            //    // mi.Shortcut = (System.Windows.Forms.Shortcut.) accel.Key.KeyData;
            //}
			return mi;
		}
        public void Replace_NoOccurrence_SameElementsReturned()
        {
            char[] chars = new[] {'a', 'b', 'c'};

            var actual = chars.Replace('x', 'y');

            AssertEx.AreEquivalent(actual, 'a', 'b', 'c');
        }
Пример #29
0
        public static bool TryParse(System.String s, out float f)
        {
            bool ok = false;

            if (s.EndsWith("f") || s.EndsWith("F"))
                ok = System.Single.TryParse(s.Substring(0, s.Length - 1).Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator), out f);
            else
                ok = System.Single.TryParse(s.Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator), out f);

            return ok;
        }
        public void Replace_OneOccurrenceForReplacedElement_ElementReplaced()
        {
            char[] chars = new[] {'a', 'b', 'c'};

            var actual = chars.Replace('b', 'x');

            AssertEx.AreEquivalent(actual, 'a', 'x', 'c');
        }