Exemplo n.º 1
1
        /// <summary>
        /// Экспортирует массив данных в XLSX формат с учетом выбранной локали
        /// </summary>
        /// <param name="path">Путь к файлу, в который нужно сохранить данные</param>
        /// <param name="localisation">Локализация</param>
        /// <returns>Успешное завершение операции</returns>
        public override bool Export(String path, Localisation localisation)
        {
            try
            {
                if (!path.EndsWith(".xlsx"))
                    path += ".xlsx";

                log.Info(String.Format("Export to .xlsx file to: {0}", path));
                var timer = new Stopwatch();
                timer.Start();
                var file = new FileInfo(path);
                using (var pck = new ExcelPackage(file))
                {
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
                    ws.Cells["A1"].LoadFromDataTable(dataTable, true);
                    ws.Cells.AutoFitColumns();
                    pck.Save();
                }

                timer.Stop();
                log.Info(String.Format("Export complete! Elapsed time: {0} ms", timer.Elapsed.Milliseconds));
                return true;
            }
            catch (Exception ex)
            {
                log.Error("Can't export to .xlsx file!", ex);
                return false;
            }
        }
Exemplo n.º 2
0
        public static String GetFileStaticRelativePath(String fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return string.Empty;
            }

            if (fileName.EndsWith(".js"))
            {
                //Attention: Only for ResourceBundleControl
                return VirtualPathUtility.ToAbsolute("~/products/projects/js/" + fileName);
            }

            if (fileName.EndsWith(".png"))
            {
                return WebPath.GetPath("/Products/Projects/App_Themes/Default/Images/" + fileName);
            }

            if (fileName.EndsWith(".css"))
            {
                //Attention: Only for ResourceBundleControl
                return VirtualPathUtility.ToAbsolute("~/products/projects/app_themes/default/css/" + fileName);
            }

            return string.Empty;
        }
Exemplo n.º 3
0
 /*
  * Starts a new explorer process with passed arguments.
  *
  * Added 2007-05-01 by T.Norad
  * 2009-02-27 Nochbaer: Edited to select the file in the explorer window and call the standard shell on mono
  */
 public static void startExplorerProcess(String path, String filename)
 {
     if (!UtilitiesForMono.IsRunningOnMono)
     {
         string arguments;
         if (filename.Length > 0)
         {
             string secondStringArgument = "";
             if (!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
             {
                 secondStringArgument =  System.IO.Path.DirectorySeparatorChar.ToString();
             }
             arguments = String.Format("/e,/select,\"{0}{1}{2}\"", path,secondStringArgument, filename);
         }
         else
         {
             arguments = String.Format("/e,{0}", path);
         }
         ProcessStarter.startProcess(EXLORER_PROCESS, arguments);
     }
     else
     {
         if (!path.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
         {
             path = path + System.IO.Path.DirectorySeparatorChar.ToString();
             ProcessStarter.startProcess(path);
         }
     }
 }
Exemplo n.º 4
0
		/// <summary> Creates source code for a Group and returns a GroupDef object that 
		/// describes the Group's name, optionality, repeatability.  The source 
		/// code is written under the given directory.
		/// The structures list may contain [] and {} pairs representing 
		/// nested groups and their optionality and repeastability.  In these cases
		/// this method is called recursively.
		/// If the given structures list begins and ends with repetition and/or 
		/// optionality markers the repetition and optionality of the returned 
		/// GroupDef are set accordingly.  
		/// <param name="structures">a list of the structures that comprise this group - must 
		/// be at least 2 long
		/// </param>
		/// <param name="groupName">The group name</param>
		/// <param name="version">The version of message</param>
		/// <param name="baseDirectory">the directory to which files should be written
		/// </param>
		/// <param name="message">the message to which this group belongs
		/// </param>
		/// <throws>  HL7Exception if the repetition and optionality markers are not  </throws>
		/// </summary>
		public static GroupDef writeGroup(IStructureDef[] structures, String groupName, String baseDirectory, String version,
			String message)
		{
			//make base directory
			if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
			{
				baseDirectory = baseDirectory + "/";
			}
			FileInfo targetDir =
				SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Group");

			// some group names are troublesome and have "/" which will cause problems when writing files
			groupName = groupName.Replace("/", "_");
			GroupDef group = getGroupDef(structures, groupName, baseDirectory, version, message);

			using (StreamWriter out_Renamed = new StreamWriter(targetDir.FullName + @"\" + group.Name + ".cs"))
			{
				out_Renamed.Write(makePreamble(group, version));
				out_Renamed.Write(makeConstructor(group, version));

				IStructureDef[] shallow = group.Structures;
				for (int i = 0; i < shallow.Length; i++)
				{
					out_Renamed.Write(makeAccessor(group, i));
				}
				out_Renamed.Write("}\r\n"); //Closing class
				out_Renamed.Write("}\r\n"); //Closing namespace
			}
			return group;
		}
Exemplo n.º 5
0
        /// <summary>
        /// Creates a relative path from one file or folder to another.
        /// </summary>
        /// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
        /// <param name="fromIs">Is the fromPath a File or a Folder</param>
        /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
        /// <param name="toIs">Is the toPath a File or a Folder</param>
        /// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="UriFormatException"></exception>
        /// <exception cref="InvalidOperationException"></exception>
        public static String MakeRelativePath(String fromPath, PathIs fromIs, String toPath, PathIs toIs)
        {
            if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
            if (String.IsNullOrEmpty(toPath)) throw new ArgumentNullException("toPath");

            //Slash am Ende anfügen, damit Uri damit klarkommt und weiß, was ein Folder ist, und was nicht
            if (!fromPath.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
                !fromPath.EndsWith(Path.AltDirectorySeparatorChar.ToString()) &&
                fromIs == PathIs.Folder)
                fromPath += Path.DirectorySeparatorChar;
            if (!toPath.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
                !toPath.EndsWith(Path.AltDirectorySeparatorChar.ToString()) &&
                toIs == PathIs.Folder)
                toPath += Path.DirectorySeparatorChar;

            Uri fromUri = new Uri(fromPath);
            Uri toUri = new Uri(toPath);

            if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.

            Uri relativeUri = fromUri.MakeRelativeUri(toUri);
            String relativePath = Uri.UnescapeDataString(relativeUri.ToString());

            if (toUri.Scheme.ToUpperInvariant() == "FILE")
            {
                relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            }
            if (relativePath == string.Empty)
                relativePath = ".\\";
            //ein \ am Ende entfernen, dies macht Probleme, insbesondere in CommandLine wenn quoted
            //zudem scheint der .Net - Standard zu sein, kein \ am Ende zu haben vgl. Path.GetDirectoryname()
            return relativePath.TrimEnd(Path.DirectorySeparatorChar);
        }
Exemplo n.º 6
0
		public static void makeAll(String baseDirectory, String version)
		{
			//make base directory
			if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
			{
				baseDirectory = baseDirectory + "/";
			}
			FileInfo targetDir =
				SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "EventMapping");

			//get list of data types
			OleDbConnection conn = NormativeDatabase.Instance.Connection;
			String sql =
				"SELECT * from HL7EventMessageTypes inner join HL7Versions on HL7EventMessageTypes.version_id = HL7Versions.version_id where HL7Versions.hl7_version = '" +
				version + "'";
			OleDbCommand temp_OleDbCommand = new OleDbCommand();
			temp_OleDbCommand.Connection = conn;
			temp_OleDbCommand.CommandText = sql;
			OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();


			using (StreamWriter sw = new StreamWriter(targetDir.FullName + @"\EventMap.properties", false))
			{
				sw.WriteLine("#event -> structure map for " + version);
				while (rs.Read())
				{
					string messageType = string.Format("{0}_{1}", rs["message_typ_snd"], rs["event_code"]);
					string structure = (string) rs["message_structure_snd"];

					sw.WriteLine(string.Format("{0} {1}", messageType, structure));
				}
			}
		}
Exemplo n.º 7
0
 /// <summary>
 /// 自动根据系统追加一级目录
 /// </summary>
 /// <returns></returns>
 public static String JoinPath(String path,String dir)
 {
     dir = dir.Replace("\\", "").Replace("/", "");
     try
     {
         if (path.EndsWith("\\") || path.EndsWith("/"))
         {
             if (SystemInfo.IsWindows)
                 return path += dir + "\\";
             else
                 return path += dir + "/";
         }
         else
         {
             if (SystemInfo.IsWindows)
                 return path += "\\" + dir + "\\";
             else
                 return path += "/" + dir + "/";
         }
     }
     catch
     {
         return path += "\\" + dir + "\\";
     }
 }
Exemplo n.º 8
0
        public static String removeLastSlash(String path)
        {
            if (path.EndsWith("/") || path.EndsWith("\\") )
                return path.Substring(1);

            return path;
        }
 bool IsTagOpen(String sb)
 {
     if (sb.StartsWith("</") && sb.EndsWith(">"))
         return false;
     else if (sb.StartsWith("<") && sb.EndsWith(">"))
         return true;
     else return false;
 }
Exemplo n.º 10
0
 //##################################################
 //# testing
 //##################################################//
 public static bool _HasPm(String s)
 {
     s = s.ToLower();
     if ( s.EndsWith("pm") )
         return true;
     if ( s.EndsWith("p") )
         return true;
     return false;
 }
Exemplo n.º 11
0
 private static String StripQuotes(String value)
 {
     if (value.StartsWith("\"") && value.EndsWith("\"")) {
         value = value.Substring(1, value.Length - 2);
     } else if (value.StartsWith("\'") && value.EndsWith("\'")) {
         value = value.Substring(1, value.Length - 2);
     }
     return value;
 }
Exemplo n.º 12
0
		/// <summary> Creates skeletal source code (without correct data structure but no business
		/// logic) for all data types found in the normative database.  For versions > 2.2, Primitive data types
		/// are not generated, because they are coded manually (as of HAPI 0.3).  
		/// </summary>
		public static void makeAll(String baseDirectory, String version)
		{
			//make base directory
			if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
			{
				baseDirectory = baseDirectory + "/";
			}
			FileInfo targetDir =
				SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Datatype");
			SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Datatype");
			//get list of data types
			ArrayList types = new ArrayList();
			OleDbConnection conn = NormativeDatabase.Instance.Connection;
			OleDbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
			//get normal data types ... 
			OleDbCommand temp_OleDbCommand;
			temp_OleDbCommand = stmt;
			temp_OleDbCommand.CommandText =
				"select data_type_code from HL7DataTypes, HL7Versions where HL7Versions.version_id = HL7DataTypes.version_id and HL7Versions.hl7_version = '" +
				version + "'";
			OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();
			while (rs.Read())
			{
				types.Add(Convert.ToString(rs[1 - 1]));
			}
			rs.Close();
			//get CF, CK, CM, CN, CQ sub-types ... 

			OleDbCommand temp_OleDbCommand2;
			temp_OleDbCommand2 = stmt;
			temp_OleDbCommand2.CommandText = "select data_structure from HL7DataStructures, HL7Versions where (" +
			                                 "data_type_code  = 'CF' or " + "data_type_code  = 'CK' or " +
			                                 "data_type_code  = 'CM' or " + "data_type_code  = 'CN' or " +
			                                 "data_type_code  = 'CQ') and " +
			                                 "HL7Versions.version_id = HL7DataStructures.version_id and  HL7Versions.hl7_version = '" +
			                                 version + "'";
			rs = temp_OleDbCommand2.ExecuteReader();
			while (rs.Read())
			{
				types.Add(Convert.ToString(rs[1 - 1]));
			}

			stmt.Dispose();
			NormativeDatabase.Instance.returnConnection(conn);

			Console.Out.WriteLine("Generating " + types.Count + " datatypes for version " + version);
			if (types.Count == 0)
			{
				log.Warn("No version " + version + " data types found in database " + conn.Database);
			}

			for (int i = 0; i < types.Count; i++)
			{
				if (!((String) types[i]).Equals("*"))
					make(targetDir, (String) types[i], version);
			}
		}
Exemplo n.º 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="myString">String </param>
        /// <returns>The value in milliseconds</returns>
        public static Int32 ConvertStringToMilliseconds(String myString)
        {
            // Guard Block
            // String null
            // String ""
            // String "        "
            if (String.IsNullOrWhiteSpace(myString))
            {
                throw new ArgumentException("Value was null, empty, or not a recognized time format.");
            }

            // Try Parse in the hopes that they gave us a number without ANY suffix
            int num;
            bool res = int.TryParse(myString, out num);

            if (res)
            {
                // Log statement saying that we're good
            }
                // Hours suffix scenario - h
            else if (myString.EndsWith("h"))
            {
                myString = myString.TrimEnd(new char[] {'h'});
                bool x = int.TryParse(myString, out num);
                if (x)
                {
                    num = num * 3600000;
                }
                
            }
                // Minute suffix scenario - m
            else if (myString.EndsWith("m"))
            {
                myString = myString.TrimEnd(new char[] { 'm' });
                bool x = int.TryParse(myString, out num);
                if (x)
                {
                    num = num * 60000;
                }
            }
              // Second suffix scenario - s
            else if (myString.EndsWith("s"))
            {
                myString = myString.TrimEnd(new char[] { 's' });
                bool x = int.TryParse(myString, out num);
                if (x)
                {
                    num = num * 1000;
                }
            }
            else
            {
                throw new ArgumentException("Value is not a recognized time format.");
            }
            return num;
        }
 private MediaInfo CreateMediaInfoFromFilePath(String filePath)
 {
     return new MediaInfo
     {
         ContentType = filePath.EndsWith(".png") ? "image/png" : filePath.EndsWith(".jpg") ? "image/jpeg" : "image/png",
         MediaId = Guid.Parse(Path.GetFileNameWithoutExtension(filePath)),
         UserId = Uri.UnescapeDataString(Path.GetFileName(Path.GetDirectoryName(filePath))),
         CreatedAt = File.GetCreationTimeUtc(filePath),
     };
 }
Exemplo n.º 15
0
		/// <summary> <p>Creates skeletal source code (without correct data structure but no business
		/// logic) for all segments found in the normative database.  </p>
		/// </summary>
		public static void makeAll(String baseDirectory, String version)
		{
			//make base directory
			if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
			{
				baseDirectory = baseDirectory + "/";
			}
			FileInfo targetDir =
				SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Segment");

			//get list of data types
			OleDbConnection conn = NormativeDatabase.Instance.Connection;
			String sql =
				"SELECT seg_code, [section] from HL7Segments, HL7Versions where HL7Segments.version_id = HL7Versions.version_id AND hl7_version = '" +
				version + "'";
			OleDbCommand temp_OleDbCommand = new OleDbCommand();
			temp_OleDbCommand.Connection = conn;
			temp_OleDbCommand.CommandText = sql;
			OleDbDataReader rs = temp_OleDbCommand.ExecuteReader();


			ArrayList segments = new ArrayList();
			while (rs.Read())
			{
				String segName = Convert.ToString(rs[1 - 1]);
				if (Char.IsLetter(segName[0]))
					segments.Add(altSegName(segName));
			}
			temp_OleDbCommand.Dispose();
			NormativeDatabase.Instance.returnConnection(conn);

			if (segments.Count == 0)
			{
				log.Warn("No version " + version + " segments found in database " + conn.Database);
			}

			for (int i = 0; i < segments.Count; i++)
			{
				try
				{
					String seg = (String) segments[i];
					String source = makeSegment(seg, version);
					using (StreamWriter w = new StreamWriter(targetDir.ToString() + @"\" + GetSpecialFilename(seg) + ".cs"))
					{
						w.Write(source);
						w.Write("}");
					}
				}
				catch (Exception e)
				{
					Console.Error.WriteLine("Error creating source code for all segments: " + e.Message);
					SupportClass.WriteStackTrace(e, Console.Error);
				}
			}
		}
Exemplo n.º 16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            PicLoc = System.Configuration.ConfigurationManager.AppSettings["RDS_MVS_ESOP"];
            if (!PicLoc.EndsWith("/") && !PicLoc.EndsWith("\\"))
            {
                PicLoc += "/";
            }
        }

    }
Exemplo n.º 17
0
        public ReplayRunner(ScrollsPost.Mod mod, String path)
        {
            this.mod = mod;
            // Convert a .sgr replay to .spr
            if( path.EndsWith(".sgr") ) {
                path = ConvertScrollsGuide(path);
            }

            this.replayPrimaryPath = path;
            this.primaryType = path.EndsWith("-white.spr") ? "white" : "black";

            // Check if we have both perspectives available to us
            String secondary = path.EndsWith("-white.spr") ? path.Replace("-white.spr", "-black.spr") : path.Replace("-black.spr", "-white.spr");
            if( File.Exists(secondary) ) {
                this.replaySecondaryPath = secondary;
            } else if( !secondary.Contains(mod.replayLogger.replayFolder) ) {
                // In case we're playing a replay from the download folder but we have the primary in our replay folder
                secondary = mod.replayLogger.replayFolder + Path.DirectorySeparatorChar + Path.GetFileName(secondary);
                if( File.Exists(secondary) ) {
                    this.replaySecondaryPath = secondary;
                }
            }

            // Always make sure the white is the primary as that person starts off the game
            if( !String.IsNullOrEmpty(this.replaySecondaryPath) && this.primaryType.Equals("black") ) {
                path = this.replayPrimaryPath;
                this.replayPrimaryPath = this.replaySecondaryPath;
                this.replaySecondaryPath = path;
                this.primaryType = "white";
            }

            GUISkin skin = (GUISkin)Resources.Load("_GUISkins/LobbyMenu");
            this.buttonStyle = skin.button;
            this.buttonStyle.normal.background = this.buttonStyle.hover.background;
            this.buttonStyle.normal.textColor = new Color(1f, 1f, 1f, 1f);
            this.buttonStyle.fontSize = (int)((10 + Screen.height / 72) * 0.65f);

            this.buttonStyle.hover.textColor = new Color(0.80f, 0.80f, 0.80f, 1f);

            this.buttonStyle.active.background = this.buttonStyle.hover.background;
            this.buttonStyle.active.textColor = new Color(0.60f, 0.60f, 0.60f, 1f);

            this.speedButtonStyle = new GUIStyle(this.buttonStyle);
            this.speedButtonStyle.fontSize = (int)Math.Round(this.buttonStyle.fontSize * 0.80f);

            this.realTimeButtonStyle = new GUIStyle(this.buttonStyle);
            this.realTimeButtonStyle.fontSize = (int)Math.Round(this.buttonStyle.fontSize * 1.20f);

            sceneLoaded = false;
            playerThread = new Thread(new ThreadStart(Start));
            playerThread.Start();
        }
Exemplo n.º 18
0
        public static String join(String path1, String path2)
        {
            bool bSlash1 = path1.EndsWith("/") || path1.EndsWith("\\");
            bool bSlash2 = path2.StartsWith("/") || path2.StartsWith("\\");

            String res;
            if (bSlash1 && bSlash2)
                res = path1 + path2.Substring(1);
            else if (bSlash1 || bSlash2)
                res = path1 + path2;
            else
                res = path1 + '/' + path2;

            return res;
        }
Exemplo n.º 19
0
 //- ~AdjustMatchType -//
 internal static EndpointData AdjustMatchType(String matchText)
 {
     EndpointData element = null;
     if (matchText.StartsWith("wdp^", StringComparison.OrdinalIgnoreCase) && matchText.EndsWith("$", StringComparison.OrdinalIgnoreCase))
     {
         element = new EndpointData();
         element.Selector = SelectorType.WebDomainPathEquals;
         element.Text = matchText.Substring(3, matchText.Length - 4);
     }
     if (matchText.StartsWith("p^", StringComparison.OrdinalIgnoreCase) && matchText.EndsWith("$", StringComparison.OrdinalIgnoreCase))
     {
         element = new EndpointData();
         element.Selector = SelectorType.PathEquals;
         element.Text = matchText.Substring(2, matchText.Length - 3);
     }
     if (matchText.StartsWith("^", StringComparison.OrdinalIgnoreCase) && matchText.EndsWith("$", StringComparison.OrdinalIgnoreCase))
     {
         element = new EndpointData();
         element.Selector = SelectorType.Equals;
         element.Text = matchText.Substring(1, matchText.Length - 2);
     }
     if (matchText.StartsWith("wdp^", StringComparison.OrdinalIgnoreCase))
     {
         element = new EndpointData();
         element.Selector = SelectorType.WebDomainPathStartsWith;
         element.Text = matchText.Substring(4, matchText.Length - 4);
     }
     if (matchText.StartsWith("p^", StringComparison.OrdinalIgnoreCase))
     {
         element = new EndpointData();
         element.Selector = SelectorType.PathStartsWith;
         element.Text = matchText.Substring(2, matchText.Length - 2);
     }
     if (matchText.EndsWith("$", StringComparison.OrdinalIgnoreCase))
     {
         element = new EndpointData();
         element.Selector = SelectorType.EndsWith;
         element.Text = matchText.Substring(0, matchText.Length - 1);
     }
     if (matchText.StartsWith("^", StringComparison.OrdinalIgnoreCase))
     {
         element = new EndpointData();
         element.Selector = SelectorType.StartsWith;
         element.Text = matchText.Substring(1, matchText.Length - 1);
     }
     //+
     return element;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Retrieve the Bazaarvoice container div and all indexable Smart SEO content to be rendered on the page.
        /// </summary>
        /// <param name="displayCode">
        /// A <see cref="String"/> - The display code for which Smart SEO content is generated.  This should be the same display 
        /// code that is the root directory of the Smart SEO archive retrieved from the Bazaarvoice server.
        /// </param>
        /// <param name="productId">
        /// A <see cref="String"/> - The ID of the product for which this product details page is being rendered.
        /// </param>
        /// <param name="productUrl">
        /// A <see cref="String"/> - The URL of the product details page for which reviews are injected.
        /// </param>
        /// <param name="rrSmartSEOParamValue">
        /// A <see cref="String"/> - The *value* of the configurable query parameter that must be kept in synch with your 
        /// Bazaarvoice Implementation Engineer.  Default query parameter *name* for Ratings and Reviews is "bvrrp"
        /// </param>
        /// <param name="smartSEOPathPrefix">
        /// A <see cref="String"/> - The absolute path to the location where your Smart SEO archive has been extracted.
        /// This absolute path should not contain your display code. 
        /// WARNING: The Smart SEO files should be the only files within this location.
        /// Files that should not be publicly exposed should not be in this directory.
        /// </param>
        /// <returns>
        /// A <see cref="String"/> - The Bazaarvoice container div and all indexable Smart SEO content to be rendered on the page.
        /// </returns>
        private String getBazaarvoiceInjectionContainer(String displayCode, String productId, String productUrl, String rrSmartSEOParamValue, String smartSEOPathPrefix)
        {
            StringBuilder cntnrBuf = new StringBuilder();
            cntnrBuf.Append("<div id=\"BVRRContainer\">" + Environment.NewLine);

            try {

                //Make sure the productUrl ends with either a ? or &
                if (!productUrl.EndsWith("?") && !productUrl.EndsWith("&")) {
                    if (productUrl.Contains("?")) {
                        productUrl += "&";
                    } else {
                        productUrl += "?";
                    }
                }

                //Make sure the smartSEOPathPrefix ends with a trailing slash
                if (!smartSEOPathPrefix.EndsWith("/")) {
                    smartSEOPathPrefix += "/";
                }

                //Get the name of the file from disk that we should use to include in the page.
                String rrSmartSEOFilename = smartSEOPathPrefix + displayCode + "/reviews/product/1/" + Server.UrlEncode(productId).Replace("+", "%20") + ".htm";
                if (rrSmartSEOParamValue != null && rrSmartSEOParamValue.IndexOf("..") < 0) {
                    String tmpFilename = smartSEOPathPrefix + rrSmartSEOParamValue;
                    if (File.Exists(tmpFilename)) {
                        rrSmartSEOFilename = tmpFilename;
                    }
                }
                //Verify the file exists
                //Verify no strange ..\ hacking attempts
                if (File.Exists(rrSmartSEOFilename)
                    && Path.GetDirectoryName(Path.GetFullPath(rrSmartSEOFilename)).StartsWith(smartSEOPathPrefix + displayCode)) {
                    //Read in the file contents, replacing all occurrences of {INSERT_PAGE_URI} with productUrl as we go along
                    String fileContents = "";
                    fileContents = File.ReadAllText(rrSmartSEOFilename, System.Text.UTF8Encoding.UTF8);
                    cntnrBuf.Append(fileContents.Replace("{INSERT_PAGE_URI}", productUrl));
                }

            } catch (Exception ex) {
                //TODO: Log exception
                Console.WriteLine(ex.ToString());
            } finally {
                cntnrBuf.Append("</div>" + Environment.NewLine);
            }

            return cntnrBuf.ToString();
        }
Exemplo n.º 21
0
 /// <summary>
 /// 将 endString 附加到 srcString末尾,如果 srcString 末尾已包含 endString,则不再附加。
 /// </summary>
 /// <param name="srcString"></param>
 /// <param name="endString"></param>
 /// <returns></returns>
 public static String Append( String srcString, String endString )
 {
     if (strUtil.IsNullOrEmpty( srcString )) return endString;
     if (strUtil.IsNullOrEmpty( endString )) return srcString;
     if (srcString.EndsWith( endString )) return srcString;
     return srcString + endString;
 }
Exemplo n.º 22
0
 public Boolean CanParseMessage(String message)
 {
     return message != null &&
            message.StartsWith("<log4j:event ") &&
            message.EndsWith("</log4j:event>") &&
            message.Contains("<log4j:data name=\"log4jmachinename\" ");
 }
Exemplo n.º 23
0
        // accept either a POINT(X Y) or a "X Y"
        public point(String ps)
        {
            if (ps.StartsWith(geomType, StringComparison.InvariantCultureIgnoreCase))
            {
                // remove point, and matching brackets
                ps = ps.Substring(geomType.Length);
                if (ps.StartsWith("("))
                {
                    ps = ps.Substring(1);
                }
                if (ps.EndsWith(")"))
                {
                    ps = ps.Remove(ps.Length - 1);
                }

            }
            ps = ps.Trim(); // trim leading and trailing spaces
            String[] coord = ps.Split(CoordSeparator.ToCharArray());
            if (coord.Length == 2)
            {
                X = Double.Parse(coord[0]);
                Y = Double.Parse(coord[1]);
            }
            else
            {
                throw new WaterOneFlowException("Could not create a point. Coordinates are separated by a space 'X Y'");
            }
        }
Exemplo n.º 24
0
        public String convert()
        {
            if (!Sauce.StartsWith("Hai 1.2"))
            {
                return new SyntaxErrorException("No 'Hai 1.2' starting command!").ToString();
            }
            Sauce = Sauce.Remove(0, 7);
            if (!Sauce.EndsWith("KTHXBYE"))
            {
                return new SyntaxErrorException("No KTHXBYE ending command!").ToString();
            }
            else
            {
                Sauce = Sauce.Remove(Sauce.Length - 8);
            }

            #region Pattern
            pattern.Add(@"I HAS A ([a-zA-Z]+)( ITZ )([a-zA-Z0-9\.]+)"); //Variable declaration and init
            pattern.Add(@"I HAS A ([a-zA-Z]+)"); //Only declaration
            pattern.Add(@"([a-zA-Z]+) R (""?[a - zA - Z0 - 9\.] + ""?)"); //only init
            pattern.Add(@",? *	*BTW"); //One line comment
            pattern.Add(@",? *	*OBTW"); //Multi line comment 1.
            pattern.Add(@",? *	*TLDR"); //Multi line comment 2.
            pattern.Add(@"WIN"); //truec
            pattern.Add(@"FAIL"); //false
            pattern.Add(@","); //Line breaks
            pattern.Add(@"YARN"); //String
            pattern.Add(@"NUMBR"); //int
            pattern.Add(@"NUMBAR"); //float
            pattern.Add(@"TROOF"); //bool
            pattern.Add(@"NOOB"); //untyped
            pattern.Add(@"(""[a-zA-Z0-9.]*)(:\))([a-zA-Z0-9.]*"")"); //newline in String
            pattern.Add(@"(""[a-zA-Z0-9.]*)(:\>)([a-zA-Z0-9.]*"")"); //tab in String
            pattern.Add(@"(""[a-zA-Z0-9.]*)(:o)([a-zA-Z0-9.]*"")"); //beep in String
            pattern.Add(@"(""[a-zA-Z0-9.]*)(:"")([a-zA-Z0-9.]*"")"); //literal quote in String
            pattern.Add(@"(""[a-zA-Z0-9.]*)(::)([a-zA-Z0-9.]*"")"); //: in String
            pattern.Add(Util.Util.getNewLineInString(Sauce) + @"? *   *(\.\.\.) ?" + Util.Util.getNewLineInString(Sauce) + @" *   *([a-zA-Z0-9 .]+)"); //Line continuation
            pattern.Add(@"[^{};](" + Util.Util.getNewLineInString(Sauce) + @")"); //obvsl new line
            #endregion
            #region replacements
            replacements.Add(@"var $1 = $2;" + Util.Util.getNewLine());
            replacements.Add(@"var $1;" + Util.Util.getNewLine());
            replacements.Add(@"$1 = $2;" + Util.Util.getNewLine());
            replacements.Add(@"//");
            replacements.Add(@"/\*");
            replacements.Add(@"\*/");
            replacements.Add(@"true");
            replacements.Add(@"false");
            replacements.Add(Util.Util.getNewLine());
            replacements.Add(@"$2");
            replacements.Add(@";" + Util.Util.getNewLine());
            #endregion

            for (int i = 0; i < pattern.Count; i++)
            {
                Sauce = Regex.Replace(Sauce, pattern[i], replacements[i]);
            }

            return Sauce;
        }
		static String GetExpectedMethodName( String path )
		{
			//WARN: questo è un bug: impedisce di chiamare effettivamente il metodo nel VM qualcosa del tipo FooCommand perchè noi cercheremmo solo Foo
			var methodName = path.EndsWith( "Command" ) ? path.Remove( path.LastIndexOf( "Command" ) ) : path;

			return methodName;
		}
Exemplo n.º 26
0
 /// <summary>
 /// Строка подключения к Excel
 /// </summary>
 /// <param name="fileName">Имя файла</param>
 /// <returns>Строка с подключением</returns>
 private static string GetConnectionString(String fileName, bool hasHeader = false)
 {
     Dictionary<string, string> props = new Dictionary<string, string>();
     // XLSX - Excel 2007, 2010, 2012, 2013
     if (fileName.EndsWith("xlsx"))
     {
         props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
         props["Extended Properties"] = "\"Excel 12.0 XML" + (!hasHeader ? ";HDR=NO" : ";HDR=NO;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0") + "\"";
         props["Data Source"] = fileName;
     }
     // XLS - Excel 2003 and Older
     else
     {
         //props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
         props["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
         props["Extended Properties"] = "\"Excel 8.0" + (!hasHeader ? ";HDR=NO" : ";HDR=NO;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0") + "\"";
         props["Data Source"] = fileName;
     }
     StringBuilder sb = new StringBuilder();
     foreach (KeyValuePair<string, string> prop in props)
     {
         sb.Append(prop.Key);
         sb.Append('=');
         sb.Append(prop.Value);
         sb.Append(';');
     }
     return sb.ToString();
 }
Exemplo n.º 27
0
        private void Push(String line)
        {
            if (_nextIsPath)
            {
                CurrentPath = line;
                _nextIsPath = false;
            }
            else if (line == _preCDID)
                _nextIsPath = true;
            else if (line == _postCDID)
            {
                Output(String.Empty, _commandCorrelationId, _errorBuffer.Count == 0);
                _lastCommand = null;
                if (_errorBuffer.Count != 0)
                {
                    for (int i = 0; i < _errorBuffer.Count; i++)
                        Output(_errorBuffer[i], _commandCorrelationId, i == _errorBuffer.Count-1);
                    _errorBuffer.Clear();
                }
            }
            else if (_lastCommand != null && line.EndsWith(_lastCommand))
            {

            }
            else if (Output != null && !String.IsNullOrWhiteSpace(line))
                Output(line, _commandCorrelationId, _lastCommand == null);
        }
Exemplo n.º 28
0
        public ResourcePaths(String pathPrefix)
        {
            if (!pathPrefix.EndsWith("/"))
                pathPrefix += "/";

            _pathPrefix = pathPrefix;
        }
Exemplo n.º 29
0
        public static void LoadScript(UserObject userobj, String args)
        {
            if (userobj.Level < Settings.ScriptLevel)
                return;

            string scriptDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
            scriptDir = System.IO.Path.Combine(scriptDir, "Arca4", "Scripts");
            if (!Directory.Exists(scriptDir))
                Directory.CreateDirectory(scriptDir);

            // Not a javascript script
            if (!args.EndsWith(".js"))
            {
                // TODO: Localizaton support
                userobj.SendPacket(AresTCPPackets.NoSuch("File is not a javascript script"));
                return;
            }

            // file doesnt exist return false
            string filePath = Path.Combine(scriptDir, args);
            if (!File.Exists(filePath))
            {
                // TODO: Localizaton support
                userobj.SendPacket(AresTCPPackets.NoSuch("File does not exist"));
                return;
            }

            ScriptManager.Items.Remove(args);
            ScriptManager.Items.Add(args, File.ReadAllText(filePath, Encoding.UTF8));
        }
Exemplo n.º 30
0
        public String Stem(String term)
        {
            term = term.ToLower();

            for (int i = 0; i < transFrom.Count; ++i)
            {
                if (term.EndsWith(transFrom[i]))
                {
                    term = term.Substring(0, term.Length - transFrom[i].Length) + transTo[i];
                    break;
                }
            }

            foreach (Regex r in rules)
            {
                Match m = r.Match(term);
                if (m.Success)
                {
                    String g1 = m.Groups[1].ToString();
                    if (HasVowel(g1) && g1.Length > 1)
                    {
                        return g1;
                    }
                }
            }

            return term;
        }
Exemplo n.º 31
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static System.Single Parse(System.String s)
 {
     try
     {
         if (s.EndsWith("f") || s.EndsWith("F"))
         {
             return(System.Single.Parse(s.Substring(0, s.Length - 1).Replace(".", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)));
         }
         else
         {
             return(System.Single.Parse(s.Replace(".", System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)));
         }
     }
     catch (System.FormatException fex)
     {
         throw fex;
     }
 }
Exemplo n.º 32
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="s"></param>
 /// <param name="style"></param>
 /// <returns></returns>
 public static System.Single Parse(System.String s, System.Globalization.NumberStyles style)
 {
     try
     {
         if (s.EndsWith("f") || s.EndsWith("F"))
         {
             return(System.Single.Parse(s.Substring(0, s.Length - 1), style));
         }
         else
         {
             return(System.Single.Parse(s, style));
         }
     }
     catch (System.FormatException fex)
     {
         throw fex;
     }
 }
Exemplo n.º 33
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="s"></param>
 /// <param name="provider"></param>
 /// <returns></returns>
 public static System.Single Parse(System.String s, System.IFormatProvider provider)
 {
     try
     {
         if (s.EndsWith("f") || s.EndsWith("F"))
         {
             return(System.Single.Parse(s.Substring(0, s.Length - 1), provider));
         }
         else
         {
             return(System.Single.Parse(s, provider));
         }
     }
     catch (System.FormatException fex)
     {
         throw fex;
     }
 }
Exemplo n.º 34
0
 private System.String[] readDtypeDatumTuple(System.String triggerLine)
 {
     System.String dTypeLine = triggerLine;
     //UPGRADE_WARNING: Method 'java.io.LineNumberReader.readLine' was converted to 'System.IO.StreamReader.ReadLine' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
     System.String datumLine = input.ReadLine();
     System.String type      = dTypeLine.Substring(7);
     System.String datum     = datumLine.Substring(7);
     //logger.debug("Tuple TYPE: ", type);
     System.String line = datum;
     if (datum.EndsWith("$MFMT"))
     {
         // deal with MDL mol content
         System.Text.StringBuilder fullDatum = new System.Text.StringBuilder();
         do
         {
             //UPGRADE_WARNING: Method 'java.io.LineNumberReader.readLine' was converted to 'System.IO.StreamReader.ReadLine' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
             line = input.ReadLine();
             fullDatum.Append(line);
         }while (!(line.Equals("M  END")));
         datum = fullDatum.ToString();
     }
     else if (datum.EndsWith("+") && (datum.Length >= 74))
     {
         // deal with multiline fields
         System.Text.StringBuilder fullDatum = new System.Text.StringBuilder();
         fullDatum.Append(datum.Substring(0, (datum.Length - 1) - (0)));
         do
         {
             //UPGRADE_WARNING: Method 'java.io.LineNumberReader.readLine' was converted to 'System.IO.StreamReader.ReadLine' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
             line = input.ReadLine();
             if (line.Length > 0)
             {
                 fullDatum.Append(line.Substring(0, (line.Length - 1) - (0)));
             }
         }while (line.EndsWith("+"));
         datum = fullDatum.ToString();
     }
     //logger.debug("     DATUM: ", datum);
     System.String[] tuple = new System.String[2];
     tuple[0] = type;
     tuple[1] = datum;
     return(tuple);
 }
Exemplo n.º 35
0
 /// <summary> Sets the string contents of the node.
 /// If the text has the remark delimiters (&lt;!-- --&gt;), these are stripped off.
 /// </summary>
 /// <param name="text">The new text for the node.
 /// </param>
 public override void SetText(System.String text)
 {
     mText = text;
     if (text.StartsWith("<!--") && text.EndsWith("-->"))
     {
         mText = text.Substring(4, (text.Length - 3) - (4));
     }
     nodeBegin = 0;
     nodeEnd   = mText.Length;
 }
Exemplo n.º 36
0
        //
        // static methods
        //

        /// <summary> Get a CharacterSet name corresponding to a charset parameter.</summary>
        /// <param name="content">A text line of the form:
        /// <pre>
        /// text/html; charset=Shift_JIS
        /// </pre>
        /// which is applicable both to the HTTP header field Content-Type and
        /// the meta tag http-equiv="Content-Type".
        /// Note this method also handles non-compliant quoted charset directives
        /// such as:
        /// <pre>
        /// text/html; charset="UTF-8"
        /// </pre>
        /// and
        /// <pre>
        /// text/html; charset='UTF-8'
        /// </pre>
        /// </param>
        /// <returns> The character set name to use when reading the input stream.
        /// If the charset parameter is not found in the given string, the default
        /// character set is returned.
        /// </returns>
        /// <seealso cref="findCharset">
        /// </seealso>
        /// <seealso cref="DEFAULT_CHARSET">
        /// </seealso>
        public static System.String GetCharset(System.String content)
        {
            System.String CHARSET_STRING = "charset";
            int           index;

            System.String ret;

            ret = DEFAULT_CHARSET;
            if (null != content)
            {
                index = content.IndexOf(CHARSET_STRING);

                if (index != -1)
                {
                    content = content.Substring(index + CHARSET_STRING.Length).Trim();
                    if (content.StartsWith("="))
                    {
                        content = content.Substring(1).Trim();
                        index   = content.IndexOf(";");
                        if (index != -1)
                        {
                            content = content.Substring(0, (index) - (0));
                        }

                        //remove any double quotes from around charset string
                        if (content.StartsWith("\"") && content.EndsWith("\"") && (1 < content.Length))
                        {
                            content = content.Substring(1, (content.Length - 1) - (1));
                        }

                        //remove any single quote from around charset string
                        if (content.StartsWith("'") && content.EndsWith("'") && (1 < content.Length))
                        {
                            content = content.Substring(1, (content.Length - 1) - (1));
                        }

                        ret = FindCharset(content, ret);
                    }
                }
            }

            return(ret);
        }
Exemplo n.º 37
0
 /// <summary> Simply tells whether the specified classname probably is provided
 /// by Velocity or is implemented by someone else.  Not surefire, but
 /// it'll probably always be right.  In any case, this method shouldn't
 /// be relied upon for anything important.
 /// </summary>
 private static bool IsProbablyProvidedLogChute(System.String claz)
 {
     if (claz == null)
     {
         return(false);
     }
     else
     {
         return(claz.StartsWith("org.apache.velocity.runtime.log") && claz.EndsWith("ILogChute"));
     }
 }
Exemplo n.º 38
0
        /// <summary> Finds a message or segment class by name and version.</summary>
        /// <param name="name">the segment or message structure name
        /// </param>
        /// <param name="version">the HL7 version
        /// </param>
        /// <param name="type">'message', 'group', 'segment', or 'datatype'
        /// </param>
        private static System.Type findClass(System.String name, System.String version, System.String type)
        {
            if (Parser.validVersion(version) == false)
            {
                throw new HL7Exception("The HL7 version " + version + " is not recognized", HL7Exception.UNSUPPORTED_VERSION_ID);
            }

            //get list of packages to search for the corresponding message class
            System.String[] packages = packageList(version);

            //get subpackage for component type
            System.String types = "message|group|segment|datatype";
            if (types.IndexOf(type) < 0)
            {
                throw new HL7Exception("Can't find " + name + " for version " + version + " -- type must be " + types + " but is " + type);
            }
            System.String subpackage = type;

            //try to load class from each package
            System.Type compClass = null;
            int         c         = 0;

            while (compClass == null && c < packages.Length)
            {
                try
                {
                    System.String p = packages[c];
                    if (!p.EndsWith("."))
                    {
                        p = p + ".";
                    }
                    System.String classNameToTry = p + subpackage + "." + name;
                    string        assembly       = GetAssemblyName(version);

                    if (log.DebugEnabled)
                    {
                        log.debug("Trying to load: " + classNameToTry);
                    }
                    //UPGRADE_TODO: The differences in the format  of parameters for method 'java.lang.Class.forName'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                    compClass = System.Type.GetType(classNameToTry + "," + assembly);
                    if (log.DebugEnabled)
                    {
                        log.debug("Loaded: " + classNameToTry + " class: " + compClass);
                    }
                }
                //UPGRADE_NOTE: Exception 'java.lang.ClassNotFoundException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
                catch (System.Exception)
                {
                    /* just try next one */
                }
                c++;
            }
            return(compClass);
        }
            public override IndexInput OpenInput(System.String name)
            {
                IndexInput ii = base.OpenInput(name);

                if (name.EndsWith(".prx"))
                {
                    // we decorate the proxStream with a wrapper class that allows to count the number of calls of seek()
                    ii = new SeeksCountingStream(enclosingInstance, ii);
                }
                return(ii);
            }
    public virtual bool runTest
        ()
    {
        System.Console.Error.WriteLine("String.EndsWith: Co1150EW runTest starting...");
        int nErrorBits = 0;

        System.String swrString2 = null;
        swrString2 = "nOpqRs";
        if (swrString2.EndsWith("qRs") != true)
        {
            nErrorBits = nErrorBits | 0x1;
        }
        if (swrString2.EndsWith("qrs") != false)
        {
            nErrorBits = nErrorBits | 0x2;
        }
        if (swrString2.EndsWith("nOp") != false)
        {
            nErrorBits = nErrorBits | 0x4;
        }
        Char[]      swrString3 = new Char[8];
        IntlStrings intl       = new IntlStrings();

        swrString2 = intl.GetString(10, true, true);
        swrString2.CopyTo(2, swrString3, 0, swrString2.Length - 2);
        String swrString4 = new String(swrString3);

        if (swrString2.EndsWith(swrString4) != true)
        {
            nErrorBits = nErrorBits | 0x1;
        }
        System.Console.Error.WriteLine(nErrorBits);
        if (nErrorBits == 0)
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Exemplo n.º 41
0
        /// <summary> Creates source code for a specific message structure and
        /// writes it under the specified directory.
        /// throws IllegalArgumentException if there is no message structure
        /// for this message in the normative database
        /// </summary>
        public static void make(System.String message, System.String baseDirectory, System.String chapter, System.String version)
        {
            try
            {
                SegmentDef[] segments = getSegments(message, version);
                //System.out.println("Making: " + message + " with " + segments.length + " segments (not writing message code - just groups)");

                GroupDef        group    = GroupGenerator.getGroupDef(segments, null, baseDirectory, version, message);
                IStructureDef[] contents = group.Structures;

                //make base directory
                if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
                {
                    baseDirectory = baseDirectory + "/";
                }

                System.IO.FileInfo targetDir = SourceGenerator.makeDirectory(baseDirectory + PackageManager.GetVersionPackagePath(version) + "Message");
                System.Console.Out.WriteLine("Writing " + message + " to " + targetDir.FullName);
                using (System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(targetDir.FullName + "/" + message + ".cs"))
                {
                    out_Renamed.Write(makePreamble(contents, message, chapter, version));
                    out_Renamed.Write(makeConstructor(contents, message, version));
                    for (int i = 0; i < contents.Length; i++)
                    {
                        out_Renamed.Write(GroupGenerator.makeAccessor(group, i));
                    }

                    //add implementation of model.control interface, if any
                    out_Renamed.Write("}\r\n"); //End class
                    out_Renamed.Write("}\r\n"); //End namespace
                }
            }
            catch (System.Exception e)
            {
                log.Error("Error while creating source code", e);

                log.Warn("Warning: could not write source code for message structure " + message + " - " + e.GetType().FullName + ": " + e.Message);
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// 去除最后多余字符串
        /// </summary>
        public static System.String RemoveEndChar(this System.String SourceString, System.String ExcessChar)
        {
            SourceString = SourceString.TBBRTrim();
            ExcessChar   = ExcessChar.TBBRTrim();
            System.String reVal = SourceString;

            if (SourceString.Length > 0 && SourceString.EndsWith(ExcessChar))
            {
                reVal = SourceString.Remove(SourceString.Length - ExcessChar.Length, ExcessChar.Length);
            }

            return(reVal);
        }
Exemplo n.º 43
0
        private void  OpenNorms(Directory cfsDir, int readBufferSize)
        {
            long nextNormSeek = SegmentMerger.NORMS_HEADER.Length;             //skip header (header unused for now)
            int  maxDoc       = MaxDoc();

            for (int i = 0; i < fieldInfos.Size(); i++)
            {
                FieldInfo fi = fieldInfos.FieldInfo(i);
                if (norms.Contains(fi.name))
                {
                    // in case this SegmentReader is being re-opened, we might be able to
                    // reuse some norm instances and skip loading them here
                    continue;
                }
                if (fi.isIndexed && !fi.omitNorms)
                {
                    Directory     d        = Directory();
                    System.String fileName = si.GetNormFileName(fi.number);
                    if (!si.HasSeparateNorms(fi.number))
                    {
                        d = cfsDir;
                    }

                    // singleNormFile means multiple norms share this file
                    bool       singleNormFile = fileName.EndsWith("." + IndexFileNames.NORMS_EXTENSION);
                    IndexInput normInput      = null;
                    long       normSeek;

                    if (singleNormFile)
                    {
                        normSeek = nextNormSeek;
                        if (singleNormStream == null)
                        {
                            singleNormStream = d.OpenInput(fileName, readBufferSize);
                        }
                        // All norms in the .nrm file can share a single IndexInput since
                        // they are only used in a synchronized context.
                        // If this were to change in the future, a clone could be done here.
                        normInput = singleNormStream;
                    }
                    else
                    {
                        normSeek  = 0;
                        normInput = d.OpenInput(fileName);
                    }

                    norms[fi.name] = new Norm(this, normInput, singleNormFile, fi.number, normSeek);
                    nextNormSeek  += maxDoc;                    // increment also if some norms are separate
                }
            }
        }
Exemplo n.º 44
0
        /// <summary>   Finds a message or segment class by name and version. </summary>
        ///
        /// <exception cref="HL7Exception"> Thrown when a HL 7 error condition occurs. </exception>
        ///
        /// <param name="name">     the segment or message structure name. </param>
        /// <param name="version">  the HL7 version. </param>
        /// <param name="type">     'message', 'group', 'segment', or 'datatype'.  </param>
        ///
        /// <returns>   The found class. </returns>

        private static System.Type findClass(System.String name, System.String version, ClassType type)
        {
            if (ParserBase.ValidVersion(version) == false)
            {
                throw new HL7Exception(
                          "The HL7 version " + version + " is not recognized",
                          HL7Exception.UNSUPPORTED_VERSION_ID);
            }

            //get list of packages to search for the corresponding message class
            List <string> packages = PackageList(version);

            //get subpackage for component type
            string typeString = type.ToString();

            System.String subpackage = typeString.Substring(0, 1).ToUpper() + typeString.Substring(1);

            //try to load class from each package
            System.Type compClass = null;
            int         c         = 0;

            while (compClass == null && c < packages.Count)
            {
                try
                {
                    System.String p = packages[c];
                    if (!p.EndsWith("."))
                    {
                        p = p + ".";
                    }
                    System.String classNameToTry = p + subpackage + "." + name;

                    classNameToTry = AddAssemblyName(p, classNameToTry);
                    if (log.DebugEnabled)
                    {
                        log.Debug("Trying to load: " + classNameToTry);
                    }
                    compClass = System.Type.GetType(classNameToTry);
                    if (log.DebugEnabled)
                    {
                        log.Debug("Loaded: " + classNameToTry + " class: " + compClass);
                    }
                }
                catch (System.Exception)
                {
                    /* just try next one */
                }
                c++;
            }
            return(compClass);
        }
Exemplo n.º 45
0
        internal virtual System.Collections.ArrayList Files()
        {
            System.Collections.ArrayList files = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(16));

            if (si.GetUseCompoundFile())
            {
                System.String name = segment + ".cfs";
                if (Directory().FileExists(name))
                {
                    files.Add(name);
                }
            }
            else
            {
                for (int i = 0; i < IndexFileNames.INDEX_EXTENSIONS.Length; i++)
                {
                    System.String name = segment + "." + IndexFileNames.INDEX_EXTENSIONS[i];
                    if (Directory().FileExists(name))
                    {
                        files.Add(name);
                    }
                }
            }

            if (si.HasDeletions())
            {
                files.Add(si.GetDelFileName());
            }

            bool addedNrm = false;

            for (int i = 0; i < fieldInfos.Size(); i++)
            {
                System.String name = si.GetNormFileName(i);
                if (name != null && Directory().FileExists(name))
                {
                    if (name.EndsWith("." + IndexFileNames.NORMS_EXTENSION))
                    {
                        if (addedNrm)
                        {
                            continue;                             // add .nrm just once
                        }
                        addedNrm = true;
                    }
                    files.Add(name);
                }
            }
            return(files);
        }
Exemplo n.º 46
0
        public static string BytesToNBNSQuery(byte[] field)
        {
            string nbnsUTF8 = BitConverter.ToString(field);

            nbnsUTF8 = nbnsUTF8.Replace("-00", String.Empty);
            string[] nbnsArray = nbnsUTF8.Split('-');
            string   nbnsQuery = "";

            foreach (string character in nbnsArray)
            {
                nbnsQuery += new System.String(Convert.ToChar(Convert.ToInt16(character, 16)), 1);
            }

            if (nbnsQuery.Contains("CA"))
            {
                nbnsQuery = nbnsQuery.Substring(0, nbnsQuery.IndexOf("CA"));
            }

            int    i = 0;
            string nbnsQuerySubtracted = "";

            do
            {
                byte nbnsQuerySub = (byte)Convert.ToChar(nbnsQuery.Substring(i, 1));
                nbnsQuerySub        -= 65;
                nbnsQuerySubtracted += Convert.ToString(nbnsQuerySub, 16);
                i++;
            }while (i < nbnsQuery.Length);

            i = 0;
            string nbnsQueryHost = "";

            do
            {
                nbnsQueryHost += (Convert.ToChar(Convert.ToInt16(nbnsQuerySubtracted.Substring(i, 2), 16)));
                i             += 2;
            }while (i < nbnsQuerySubtracted.Length - 1);

            if (nbnsQuery.StartsWith("ABAC") && nbnsQuery.EndsWith("AC"))
            {
                nbnsQueryHost = nbnsQueryHost.Substring(2);
                nbnsQueryHost = nbnsQueryHost.Substring(0, nbnsQueryHost.Length - 1);
                nbnsQueryHost = String.Concat("<01><02>", nbnsQueryHost, "<02>");
            }

            return(nbnsQueryHost);
        }
Exemplo n.º 47
0
 /// <summary> Reads the command on this line. If the line is continued on the next, that
 /// part is added.
 ///
 /// </summary>
 /// <returns> Returns the command on this line.
 /// </returns>
 private System.String readCommand()
 {
     System.String line = readLine();
     if (line.StartsWith("M  V30 "))
     {
         System.String command = line.Substring(7);
         if (command.EndsWith("-"))
         {
             command  = command.Substring(0, (command.Length - 1) - (0));
             command += readCommand();
         }
         return(command);
     }
     else
     {
         throw new CDKException("Could not read MDL file: unexpected line: " + line);
     }
 }
Exemplo n.º 48
0
        public void GetLogsByProgramFilter(INTEGER appNumber, STRING programNameFilter)
        {
            programNameFilter = programNameFilter.Trim();
            if (programNameFilter.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
            {
                programNameFilter = programNameFilter.Remove(programNameFilter.LastIndexOf('.'), 4);
            }

            if (_cachedLogEntries == null)
            {
                return;
            }

            var data = new LogEntryArray(_cachedLogEntries.Array.Where(
                                             entry => entry.Program.StartsWith(programNameFilter, StringComparison.OrdinalIgnoreCase)).ToArray());

            OnLogsUpdated(data);
        }
Exemplo n.º 49
0
        /// <summary>
        /// 脱帽(去除开头和结尾多余字符串)
        /// </summary>
        public static System.String TakeHat(this System.String SourceString, System.String ExcessChar)
        {
            SourceString = SourceString.TBBRTrim();
            ExcessChar   = ExcessChar.TBBRTrim();
            System.String reVal = SourceString;

            if (SourceString.Length > 0)
            {
                if (SourceString.StartsWith(ExcessChar))
                {
                    reVal = SourceString.Remove(ExcessChar.Length, SourceString.Length - ExcessChar.Length);
                }
                if (SourceString.EndsWith(ExcessChar))
                {
                    reVal = SourceString.Remove(SourceString.Length - ExcessChar.Length, ExcessChar.Length);
                }
            }
            return(reVal);
        }
Exemplo n.º 50
0
 public static void Log(System.String msg)
 {
     if (msg.EndsWith(Environment.NewLine))
     {
         msg = msg.Substring(0, msg.Length - Environment.NewLine.Length);                                    // Trim any final newline.
     }
     if (msg.StartsWith("[error]", StringComparison.Ordinal))
     {
         Debug.LogError(msg);
     }
     else if (msg.StartsWith("[warning]", StringComparison.Ordinal))
     {
         Debug.LogWarning(msg);
     }
     else
     {
         Debug.Log(msg);  // includes [info] and [debug].
     }
 }
        /// <summary> Finds a message or segment class by name and version.</summary>
        /// <param name="name">the segment or message structure name
        /// </param>
        /// <param name="version">the HL7 version
        /// </param>
        /// <param name="type">'message', 'group', 'segment', or 'datatype'
        /// </param>
        private static System.Type findClass(System.String name, System.String version, System.String type)
        {
            if (NuGenParser.validVersion(version) == false)
            {
                throw new NuGenHL7Exception("The HL7 version " + version + " is not recognized", NuGenHL7Exception.UNSUPPORTED_VERSION_ID);
            }

            //get list of packages to search for the corresponding message class
            System.String[] packages = packageList(version);

            //get subpackage for component type
            System.String types = "message|group|segment|datatype";
            if (types.IndexOf(type) < 0)
            {
                throw new NuGenHL7Exception("Can't find " + name + " for version " + version + " -- type must be " + types + " but is " + type);
            }
            System.String subpackage = type;

            //try to load class from each package
            System.Type compClass = null;
            int         c         = 0;

            while (compClass == null && c < packages.Length)
            {
                try
                {
                    System.String p = packages[c];
                    if (!p.EndsWith("."))
                    {
                        p = p + ".";
                    }
                    System.String classNameToTry = p + subpackage + "." + name;

                    compClass = System.Type.GetType(classNameToTry);
                }
                catch (System.Exception)
                {
                    /* just try next one */
                }
                c++;
            }
            return(compClass);
        }
Exemplo n.º 52
0
        private Boolean _SelectDirectory(ref System.String result)
        {
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();

            folderDialog.SelectedPath = System.IO.Directory.GetCurrentDirectory();

            DialogResult dialogResult = folderDialog.ShowDialog();

            if (dialogResult.ToString() == "OK")
            {
                result = folderDialog.SelectedPath;
                if (!result.EndsWith("\\"))
                {
                    result += "\\";
                }
                return(true);
            }

            return(false);
        }
Exemplo n.º 53
0
        static StackObject *EndsWith_22(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 2);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.String @value = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.String instance_of_this_method = (System.String) typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.EndsWith(@value);

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method ? 1 : 0;
            return(__ret + 1);
        }
Exemplo n.º 54
0
        private void  OpenNorms(Directory cfsDir)
        {
            long nextNormSeek = SegmentMerger.NORMS_HEADER.Length;             //skip header (header unused for now)
            int  maxDoc       = MaxDoc();

            for (int i = 0; i < fieldInfos.Size(); i++)
            {
                FieldInfo fi = fieldInfos.FieldInfo(i);
                if (fi.isIndexed && !fi.omitNorms)
                {
                    Directory     d        = Directory();
                    System.String fileName = si.GetNormFileName(fi.number);
                    if (!si.HasSeparateNorms(fi.number))
                    {
                        d = cfsDir;
                    }
                    long normSeek = (fileName.EndsWith("." + IndexFileNames.NORMS_EXTENSION)?nextNormSeek:0);
                    norms[fi.name] = new Norm(this, d.OpenInput(fileName), fi.number, normSeek);
                    nextNormSeek  += maxDoc;                    // increment also if some norms are separate
                }
            }
        }
Exemplo n.º 55
0
        // ArcGIS Snippet Title:
        // Create JPEG (hi-resolution) from ActiveView
        //
        // Long Description:
        // Creates a .jpg (JPEG) file from IActiveView using a high resolution exporting option. Default values of 96 DPI are overwritten to 300 used for the image creation.
        //
        // Add the following references to the project:
        // ESRI.ArcGIS.Carto
        // ESRI.ArcGIS.Display
        // ESRI.ArcGIS.Geometry
        // ESRI.ArcGIS.Output
        //
        // Intended ArcGIS Products for this snippet:
        // ArcGIS Desktop (ArcEditor, ArcInfo, ArcView)
        // ArcGIS Engine
        // ArcGIS Server
        //
        // Applicable ArcGIS Product Versions:
        // 9.2
        // 9.3
        // 9.3.1
        // 10.0
        //
        // Required ArcGIS Extensions:
        // (NONE)
        //
        // Notes:
        // This snippet is intended to be inserted at the base level of a Class.
        // It is not intended to be nested within an existing Method.
        //

        ///<summary>Creates a .jpg (JPEG) file from the ActiveView using a high resolution exporting option. Default values of 96 DPI are overwritten to 300 used for the image creation.</summary>
        ///
        ///<param name="activeView">An IActiveView interface</param>
        ///<param name="pathFileName">A System.String that the path and filename of the JPEG you want to create. Example: "C:\temp\hiResolutionTest.jpg"</param>
        ///
        ///<returns>A System.Boolean indicating the success</returns>
        ///
        ///<remarks></remarks>
        public System.Boolean CreateJPEGHiResolutionFromActiveView(ESRI.ArcGIS.Carto.IActiveView activeView, System.String pathFileName)
        {
            //parameter check
            if (activeView == null || !(pathFileName.EndsWith(".jpg")))
            {
                return(false);
            }
            ESRI.ArcGIS.Output.IExport export = (IExport) new ESRI.ArcGIS.Output.ExportJPEG();
            export.ExportFileName = pathFileName;

            // Because we are exporting to a resolution that differs from screen
            // resolution, we should assign the two values to variables for use
            // in our sizing calculations
            System.Int32 screenResolution = 96;
            System.Int32 outputResolution = 300;

            export.Resolution = outputResolution;

            tagRECT exportRECT; // This is a structure

            exportRECT.left   = 0;
            exportRECT.top    = 0;
            exportRECT.right  = activeView.ExportFrame.right * (outputResolution / screenResolution);
            exportRECT.bottom = activeView.ExportFrame.bottom * (outputResolution / screenResolution);

            // Set up the PixelBounds envelope to match the exportRECT
            ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass();
            envelope.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
            export.PixelBounds = envelope;

            System.Int32 hDC = export.StartExporting();

            activeView.Output(hDC, (System.Int16)export.Resolution, ref exportRECT, null, null); // Explicit Cast and 'ref' keyword needed
            export.FinishExporting();
            export.Cleanup();

            return(true);
        }
Exemplo n.º 56
0
    public static string[] getExcelSheets(string mFile)
    {
        try
        {
            string strXlsConnString;
            strXlsConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mFile + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
            OleDbConnection xlsConn = new OleDbConnection(strXlsConnString);
            xlsConn.Open();
            DataTable xlTable = new DataTable();
            xlTable = xlsConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            System.String strExcelSheetNames = "";
            string        sheetName;
            //Loop through the excel database table names and take only the tables that ends with a $ characters. Other tables are not worksheets...
            for (int lngStart = 0; lngStart < xlTable.Rows.Count; lngStart++)
            {
                sheetName = xlTable.Rows[lngStart][2].ToString().Replace("'", "");            //Remove the single-quote surrounding the table name...
                if (sheetName.EndsWith("$"))                                                  //Yes, this is a worksheet
                {
                    strExcelSheetNames += sheetName.Substring(0, sheetName.Length - 1) + "~"; //concatenate with a single-quote delimeter... to be returned as a string array later using the split function
                }
            }

            if (strExcelSheetNames.EndsWith("~")) //the last single quote needs to be removed so that the array index ends with the last sheetname
            {
                strExcelSheetNames = strExcelSheetNames.Substring(0, strExcelSheetNames.Length - 1);
            }

            xlsConn.Close();
            xlsConn.Dispose();
            char[] chrDelimter = { '~' };
            return(strExcelSheetNames.Split(chrDelimter));
        }
        catch (Exception exp)
        {
            throw new Exception("Error while listing the excel sheets from upload file <br>" + exp.Message, exp);
        }
    }
Exemplo n.º 57
0
 /* (non-Javadoc)
  * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
  */
 public virtual bool Accept(System.IO.FileInfo dir, System.String name)
 {
     for (int i = 0; i < IndexFileNames.INDEX_EXTENSIONS.Length; i++)
     {
         if (name.EndsWith("." + IndexFileNames.INDEX_EXTENSIONS[i]))
         {
             return(true);
         }
     }
     if (name.Equals(IndexFileNames.DELETABLE))
     {
         return(true);
     }
     else if (name.Equals(IndexFileNames.SEGMENTS))
     {
         return(true);
     }
     else if (true)             // else if (name.Matches(".+\\.f\\d+")) // {{Aroush-1.9}}
     {
         return(true);
     }
     return(false);
 }
Exemplo n.º 58
0
        internal static System.String determineAtomSetCollectionReader(System.IO.StreamReader bufferedReader)
        {
            System.String[]   lines = new System.String[4];
            LimitedLineReader llr   = new LimitedLineReader(bufferedReader, 16384);

            for (int i = 0; i < lines.Length; ++i)
            {
                lines[i] = llr.readLineWithNewline();
            }
            if (lines[3].Length >= 6)
            {
                System.String line4trimmed = lines[3].Trim();
                if (line4trimmed.EndsWith("V2000") || line4trimmed.EndsWith("v2000") || line4trimmed.EndsWith("V3000"))
                {
                    return("Mol");
                }
                try
                {
                    System.Int32.Parse(lines[3].Substring(0, (3) - (0)).Trim());
                    System.Int32.Parse(lines[3].Substring(3, (6) - (3)).Trim());
                    return("Mol");
                }
                catch (System.FormatException nfe)
                {
                }
            }
            try
            {
                /*int atomCount = */
                System.Int32.Parse(lines[0].Trim());
                return("Xyz");
            }
            catch (System.FormatException e)
            {
            }
            try
            {
                SupportClass.Tokenizer tokens = new SupportClass.Tokenizer(lines[0].Trim(), " \t");
                if ((tokens != null) && (tokens.Count >= 2))
                {
                    System.Int32.Parse(tokens.NextToken().Trim());
                    return("FoldingXyz");
                }
            }
            catch (System.FormatException e)
            {
                //
            }
            // run these loops forward ... easier for people to understand
            for (int i = 0; i < startsWithRecords.Length; ++i)
            {
                System.String[] recordTags = startsWithRecords[i];
                for (int j = 0; j < recordTags.Length; ++j)
                {
                    System.String recordTag = recordTags[j];
                    for (int k = 0; k < lines.Length; ++k)
                    {
                        if (lines[k].StartsWith(recordTag))
                        {
                            return(startsWithFormats[i]);
                        }
                    }
                }
            }
            for (int i = 0; i < containsRecords.Length; ++i)
            {
                System.String[] recordTags = containsRecords[i];
                for (int j = 0; j < recordTags.Length; ++j)
                {
                    System.String recordTag = recordTags[j];
                    for (int k = 0; k < lines.Length; ++k)
                    {
                        if (lines[k].IndexOf(recordTag) != -1)
                        {
                            return(containsFormats[i]);
                        }
                    }
                }
            }

            if (lines[1] == null || lines[1].Trim().Length == 0)
            {
                return("Jme"); // this is really quite broken :-)
            }
            return(null);
        }
Exemplo n.º 59
0
        /// <summary>
        /// Prints a code block that will deserialize the specified variable from the
        /// given stream.
        /// </summary>
        /// <param name="sw">the print stream to write the code block to
        /// </param>
        /// <param name="indentLevel">the level of indentation to use
        /// </param>
        /// <param name="iteratorVariable">the name of the iterator variable to use ('i', 'j', 'k'...)
        /// </param>
        /// <param name="dataTypeName">the name of the variable's data type
        /// </param>
        /// <param name="variableName">the name of the variable
        /// </param>
        /// <param name="streamName">the name of the stream
        /// </param>
        private void PrintDeserializationBlock(System.IO.StreamWriter ps, int indentLevel, char iteratorVariable, System.String dataTypeName, System.String variableName, System.String streamName)
        {
            if (dataTypeName == null || dataTypeName.Equals("HLAopaqueData") || opaqueTypes.Contains(dataTypeName))
            {
                ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + streamName + ".ReadHLAopaqueData();");
            }
            else if (dataTypeName.Equals("NA"))
            {
                return;
            }
            //TODO all these types are simpleDatatype. Must we consider it as default or try to look for in descriptorManager.SimpleDataTypeMap ???
            else if (dataTypeName.Equals("HLAASCIIchar") || dataTypeName.Equals("HLAunicodeChar") ||
                     dataTypeName.Equals("HLAboolean") || dataTypeName.Equals("HLAunicodestring") ||
                     dataTypeName.Equals("HLAASCIIstring"))
            {
                ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + streamName + ".Read" + dataTypeName + "();");
            }
            else if (descriptorManager.BasicDataTypeMap.ContainsKey(dataTypeName))
            {
                //TODO Check if a Basic Data has a specific deserializer
                ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + streamName + ".Read" + dataTypeName + "();");
            }
            else if (descriptorManager.SimpleDataTypeMap.ContainsKey(dataTypeName))
            {
                System.String representation = descriptorManager.SimpleDataTypeMap[dataTypeName].Representation;

                if (descriptorManager.BasicDataTypeMap.ContainsKey(representation))
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + streamName + ".Read" + representation + "();");
                }
                else
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + streamName + ".ReadHLAopaqueData();");
                }
            }
            else if (descriptorManager.ArrayDataTypeMap.ContainsKey(dataTypeName))
            {
                HLAarrayDataType arrData = descriptorManager.ArrayDataTypeMap[dataTypeName];

                if (arrData.HasNativeSerializer)
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + streamName + ".Read" + dataTypeName + "();");
                }
                else
                {
                    System.String nativeType  = NativeTypeForDataType(dataTypeName);
                    System.String preBracket  = nativeType.Substring(0, (nativeType.IndexOf((System.Char) ']')) - (0));
                    System.String postBracket = nativeType.Substring(nativeType.IndexOf((System.Char) ']'));

                    if (arrData.Cardinality.ToUpper().Equals("DYNAMIC"))
                    {
                        ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = new " + preBracket + " " + streamName + ".ReadHLAinteger32BE() " + postBracket + ";");
                        ps.WriteLine();
                        ps.WriteLine(GenerateIndentString(indentLevel) + "for(int " + iteratorVariable + "=0;" + iteratorVariable + "<" + variableName + ".Length;" + iteratorVariable + "++)");
                    }
                    else
                    {
                        ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = new " + preBracket + arrData.Cardinality + postBracket + ";");
                        ps.WriteLine();
                        ps.WriteLine(GenerateIndentString(indentLevel) + "for(int " + iteratorVariable + "=0;" + iteratorVariable + "<" + arrData.Cardinality + ";" + iteratorVariable + "++)");
                    }

                    ps.WriteLine(GenerateIndentString(indentLevel) + "{");
                    PrintDeserializationBlock(ps, indentLevel + 1, (char)(iteratorVariable + 1), arrData.DataType, variableName + "[" + iteratorVariable + "]", streamName);
                    ps.WriteLine(GenerateIndentString(indentLevel) + "}");
                }
            }
            else
            {
                if (dataTypeName.StartsWith("HLA") && !dataTypeName.EndsWith("[]") && !dataTypeName.EndsWith("]"))
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + dataTypeName + "XrtiSerializer.Deserialize(" + streamName + ");");
                }
                else
                {
                    if (dataTypeName.StartsWith("HLA") && !dataTypeName.EndsWith("[]") && !variableName.EndsWith("]"))
                    {
                        ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + dataTypeName + "XrtiSerializer.Deserialize(" + streamName + ");");
                    }
                    else
                    {
                        ps.WriteLine(GenerateIndentString(indentLevel) + variableName + " = " + dataTypeName + "XrtiSerializer.Deserialize(" + streamName + ");");
                    }
                }
            }
        }
Exemplo n.º 60
0
        /// <summary>
        /// Prints a code block that will serialize the specified variable to the
        /// given stream.
        /// </summary>
        /// <param name="ps">the print stream to write the code block to
        /// </param>
        /// <param name="indentLevel">the level of indentation to use
        /// </param>
        /// <param name="iteratorVariable">the name of the iterator variable to use ('i', 'j', 'k'...)
        /// </param>
        /// <param name="dataTypeName">the name of the variable's data type
        /// </param>
        /// <param name="variableName">the name of the variable
        /// </param>
        /// <param name="streamName">the name of the stream
        /// </param>
        private void PrintSerializationBlock(System.IO.StreamWriter ps, int indentLevel, char iteratorVariable, System.String dataTypeName, System.String variableName, System.String streamName)
        {
            if (dataTypeName == null || dataTypeName.Equals("HLAopaqueData") || opaqueTypes.Contains(dataTypeName))
            {
                ps.WriteLine(GenerateIndentString(indentLevel) + streamName + ".WriteHLAopaqueData(" + variableName + ");");
            }
            else if (dataTypeName.Equals("NA"))
            {
                return;
            }
            else if (dataTypeName.Equals("HLAASCIIchar") || dataTypeName.Equals("HLAunicodeChar") ||
                     dataTypeName.Equals("HLAboolean") || dataTypeName.Equals("HLAunicodestring") ||
                     dataTypeName.Equals("HLAASCIIstring"))
            {
                ps.WriteLine(GenerateIndentString(indentLevel) + streamName + ".Write" + dataTypeName + "(" + variableName + ");");
            }
            else if (descriptorManager.BasicDataTypeMap.ContainsKey(dataTypeName))
            {
                //TODO Check if a Basic Data has a specific serializer
                ps.WriteLine(GenerateIndentString(indentLevel) + streamName + ".Write" + dataTypeName + "(" + variableName + ");");
            }
            else if (descriptorManager.SimpleDataTypeMap.ContainsKey(dataTypeName))
            {
                System.String representation = descriptorManager.SimpleDataTypeMap[dataTypeName].Representation;

                if (descriptorManager.BasicDataTypeMap.ContainsKey(representation))
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + streamName + ".Write" + representation + "(" + variableName + ");");
                }
                else
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + streamName + ".WriteHLAopaqueData(" + variableName + ");");
                }
            }
            else if (descriptorManager.ArrayDataTypeMap.ContainsKey(dataTypeName))
            {
                HLAarrayDataType arrData = descriptorManager.ArrayDataTypeMap[dataTypeName];

                if (arrData.HasNativeSerializer)
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + streamName + ".Write" + dataTypeName + "(" + variableName + ");");
                }
                else
                {
                    if (arrData.Cardinality.ToUpper().Equals("DYNAMIC"))
                    {
                        ps.WriteLine(GenerateIndentString(indentLevel) + streamName + ".WriteHLAinteger32BE((" + variableName + ").Length);");
                        ps.WriteLine();
                        ps.WriteLine(GenerateIndentString(indentLevel) + "for(int " + iteratorVariable + "=0;" + iteratorVariable + "< (" + variableName + ").Length;" + iteratorVariable + "++)");
                    }
                    else
                    {
                        ps.WriteLine(GenerateIndentString(indentLevel) + "for(int " + iteratorVariable + "=0;" + iteratorVariable + "<" + arrData.Cardinality + ";" + iteratorVariable + "++)");
                    }

                    ps.WriteLine(GenerateIndentString(indentLevel) + "{");
                    PrintSerializationBlock(ps, indentLevel + 1, (char)(iteratorVariable + 1), arrData.DataType, "(" + variableName + ")[" + iteratorVariable + "]", streamName);
                    ps.WriteLine(GenerateIndentString(indentLevel) + "}");
                }
            }
            else
            {
                if (variableName.EndsWith("]"))
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + dataTypeName + "XrtiSerializer.Serialize(" + streamName + ", " + variableName + ");");
                }
                else
                {
                    ps.WriteLine(GenerateIndentString(indentLevel) + dataTypeName + "XrtiSerializer.Serialize(" + streamName + ", " + variableName + ");");
                }
            }
        }