private static string ExceptionToText(Exception exc, string source = "", bool isInnerException = false)
        {
            StringBuilder sb    = new StringBuilder();
            string        inner = "";

            if (isInnerException)
            {
                inner = "Inner ";
            }
            else
            {
                sb.AppendFormatLine("********** {0} **********", DateTime.Now);
            }

            if (exc.InnerException != null)
            {
                sb.AppendLine(ExceptionToText(exc.InnerException, null, true));
            }

            sb.AppendLine();
            sb.AppendFormatLine("{0}Tipo: {1}", inner, exc.GetType().ToString());
            sb.AppendFormatLine("{0}Mensagem: {1}", inner, exc.Message);
            sb.AppendFormatLine("{0}Origem: {1}", inner, (source != null ? source : exc.Source));
            sb.AppendLine();

            if (exc.StackTrace != null)
            {
                sb.AppendFormatLine("{0}Stack Trace: {1}", inner, exc.StackTrace);
                sb.AppendLine();
            }

            return(sb.ToString());
        }
        /// <summary>
        /// Prints the web exception action.
        /// </summary>
        /// <param name="stringBuilder">The string builder.</param>
        /// <param name="webException">The web exception.</param>
        private static void PrintWebException(StringBuilder stringBuilder, WebException webException)
        {
            stringBuilder.AppendLine(WebExceptionHeaderLine).AppendFormatLine(StatusFormat, webException.Status);

            var webResponse = webException.Response;

            if (webResponse == null)
            {
                return;
            }

            stringBuilder.AppendFormatLine(ResponseUriFormat, webResponse.ResponseUri);

            var headers =
                webResponse.Headers.AllKeys.ToDictionary(key => key, key => webResponse.Headers[key]).ToJsonIndented();

            stringBuilder.AppendFormatLine(ResponseHeadersFormat, headers);

            var responseStream = webResponse.GetResponseStream();

            if (responseStream != null)
            {
                using (var streamReader = new StreamReader(responseStream))
                {
                    stringBuilder.AppendFormatLine(ResponseBodyFormat, streamReader.ReadToEnd());
                }
            }

            webResponse.Close();
        }
Ejemplo n.º 3
0
        public void WriteConfigurationMethod(string path)
        {
            if (_configurationSectionIsWritten)
            {
                return;
            }

            string qualifiedName = ConstructAssemblyQualifiedNameExample();

            _output.AppendLine("\t\tprotected override void ConfigureComparison(string filename)");
            _output.AppendLine("\t\t{");
            _output.AppendLine("\t\t\t//// Use the filename of the test to setup different");
            _output.AppendLine("\t\t\t//// comparison configurations for each test.");
            _output.AppendFormatLine("\t\t\t//if(filename.EndsWith(\"{0}.xml\"))", _recordingReader.GetRecordingName());
            _output.AppendLine("\t\t\t//{");
            _output.AppendLine("\t\t\t//    // Use IgnoreOnType to exclude a property from the comparison for all objects of that type.");
            _output.AppendFormatLine("\t\t\t//    IgnoreOnType({0});", ConstructTypePropertySelectorExample(qualifiedName));
            _output.AppendLine("\t\t\t//");
            _output.AppendLine("\t\t\t//    // Use Ignore to exclude a property from the comparison for a specific instance.");
            _output.AppendFormatLine("\t\t\t//    Ignore({0});", ConstructObjectPropertySelectorExample(qualifiedName));
            _output.AppendLine("\t\t\t//}");
            _output.AppendLine("\t\t}");
            _output.AppendLine();

            _configurationSectionIsWritten = true;
        }
Ejemplo n.º 4
0
        public void WriteTestMethod(string path)
        {
            if (!string.IsNullOrEmpty(Configuration.TestFlavour.TestAttribute))
            {
                _output.AppendFormatLine("\t\t[{0}]", Configuration.TestFlavour.TestAttribute);
            }

            string recordingName = _recordingReader.GetRecordingName();

            if (!_usedMethodNames.ContainsKey(recordingName))
            {
                _usedMethodNames.Add(recordingName, 1);
            }
            else
            {
                int usedTimes = _usedMethodNames[recordingName];
                _usedMethodNames[recordingName] = usedTimes++;
                recordingName += "_" + usedTimes;
            }

            _output.AppendFormatLine("\t\tpublic void {0}()", recordingName);
            _output.AppendLine("\t\t{");
            _output.AppendFormatLine("\t\t\tRun(@\"{0}\");", path);
            _output.AppendLine("\t\t}");
            _output.AppendLine();
        }
Ejemplo n.º 5
0
        public override string DisplayResult()
        {
            StringBuilder retValue = new StringBuilder();
            int           n        = 1;

            retValue.AppendFormatLine("STARTLE RESULT (Stimulating Pressure: {0:0.00}kPa, Startle Pressure {1:0.00})kPa",
                                      StimulatingPressure,
                                      StartlePressure);

            foreach (var p in Probes)
            {
                if (p.ProbeType == StartleResponseTest.ProbeType.STARTLE)
                {
                    retValue.AppendFormatLine("STARTLE PROBE [ {0} ] VAS: {1:0.00}cm, TYPE: {2}",
                                              n, p.VAS, p.ProbeType);
                }
                else
                {
                    retValue.AppendFormatLine("NORMAL PROBE [ {0} ] VAS: {1:0.00}cm, TYPE: {2}",
                                              n, p.VAS, p.ProbeType);
                }
                ++n;
            }

            return(retValue.ToString());
        }
Ejemplo n.º 6
0
        private void CreateTextQuery_Click(object sender, EventArgs e)
        {
            int entry;

            if ((entry = _tbTextID.Text.ToInt32()) > -1)
            {
                MessageBox.Show("ID текста должно быть отрицательным числом!");
                return;
            }

            string[] loc = new string[_cbLocale.Items.Count];
            if (_cbLocale.SelectedIndex > 0)
            {
                loc[_cbLocale.SelectedIndex] = _tbTextContentLocales.Text.RemExc();
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendFormatLine("DELETE FROM `creature_ai_texts` WHERE entry IN ('{0}');", entry);
            sb.AppendFormatLine("INSERT INTO `creature_ai_texts` VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}');",
                                entry,
                                _tbTextContentDefault.Text.RemExc(),
                                loc[1], loc[2], loc[3], loc[4], loc[5], loc[6], loc[7], loc[8],
                                _cbSoundEntry.GetIntValue(),
                                _cbMessageType.GetIntValue(),
                                _cbLenguage.GetIntValue(),
                                _cbTextEmote.GetIntValue(),
                                _tbCommentAITexts.Text.RemExc());

            rtbTextOut.Text = sb.ToString();
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Get the text detailing where they can get help using the system
 /// </summary>
 /// <param name="body"></param>
 private void GetHelpText(StringBuilder body)
 {
     body.AppendLine("<p>If you need any help using the system, please refer to the user guides on the intranet.</p>");
     body.AppendLine("<p>Kind regards,<br/>Digital Services</p>");
     body.AppendFormatLine("<p>Guidance for web authors: <a href=\"{0}\">{0}</a>", ConfigurationManager.AppSettings["WebAuthorsGuidanceUrl"]);
     body.AppendFormatLine("<br/>Yammer: <a href=\"{0}\">{0}</a></p>", ConfigurationManager.AppSettings["WebAuthorsYammerUrl"]);
 }
Ejemplo n.º 8
0
        public override void ToString(StringBuilder builder)
        {
            builder.AppendLine("Type: " + m_type);
            builder.AppendLine("Language: " + m_language);
            builder.AppendFormatLine("Unknown uint32: {0} (0x{0:X8})", m_unknownUInt32);
            builder.AppendFormatLine("Sender: {0} '{1}'", m_senderGUID, m_senderName ?? "<null>");
            builder.AppendFormatLine("Target: {0} '{1}'", m_targetGUID, m_targetName ?? "<null>");

            builder.AppendLine("Chat Tag: " + m_flags);

            if (!String.IsNullOrEmpty(m_channel))
            {
                builder.AppendLine("Channel: " + m_channel);
            }

            if (m_achievementId != 0)
            {
                builder.AppendLine("Achievement Id: " + m_achievementId);
            }

            builder.AppendLine();

            if (!String.IsNullOrEmpty(m_addonPrefix))
            {
                builder.AppendLine("Addon Prefix: " + m_addonPrefix);
            }

            builder.AppendLine("Text: " + m_text);

            if (m_type == ChatMessageType.RaidBossEmote || m_type == ChatMessageType.RaidBossWhisper)
            {
                builder.AppendLine("Display Time: " + m_displayTime);
                builder.AppendLine("Suspend Event: " + m_suspendEvent);
            }
        }
 /// <summary>
 /// Writes a detailed error message to the buffer
 /// </summary>
 /// <param name="buffer">Instance of <see cref="StringBuilder"/></param>
 /// <param name="jsScriptException">JS script exception</param>
 private static void WriteScriptErrorDetails(StringBuilder buffer,
                                             JsScriptException jsScriptException)
 {
     if (!string.IsNullOrWhiteSpace(jsScriptException.Type))
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Type,
                                 jsScriptException.Type);
     }
     if (!string.IsNullOrWhiteSpace(jsScriptException.DocumentName))
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_DocumentName,
                                 jsScriptException.DocumentName);
     }
     if (jsScriptException.LineNumber > 0)
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_LineNumber,
                                 jsScriptException.LineNumber.ToString(CultureInfo.InvariantCulture));
     }
     if (jsScriptException.ColumnNumber > 0)
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ColumnNumber,
                                 jsScriptException.ColumnNumber.ToString(CultureInfo.InvariantCulture));
     }
     if (!string.IsNullOrWhiteSpace(jsScriptException.SourceFragment))
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_SourceFragment,
                                 jsScriptException.SourceFragment);
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Generates a detailed error message
        /// </summary>
        /// <param name="sassСompilationException">Sass compilation exception</param>
        /// <returns>Detailed error message</returns>
        public static string Format(SassСompilationException sassСompilationException)
        {
            string message = sassСompilationException.Text;
            string filePath = sassСompilationException.File;
            int lineNumber = sassСompilationException.LineNumber;
            int columnNumber = sassСompilationException.ColumnNumber;
            string sourceCode = sassСompilationException.Source;
            string sourceFragment = SourceCodeNavigator.GetSourceFragment(sourceCode,
                new SourceCodeNodeCoordinates(lineNumber, columnNumber));

            var errorMessage = new StringBuilder();
            errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Message, message);
            if (!string.IsNullOrWhiteSpace(filePath))
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_File, filePath);
            }
            if (lineNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_LineNumber,
                    lineNumber.ToString(CultureInfo.InvariantCulture));
            }
            if (columnNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ColumnNumber,
                    columnNumber.ToString(CultureInfo.InvariantCulture));
            }
            if (!string.IsNullOrWhiteSpace(sourceFragment))
            {
                errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
                    Strings.ErrorDetails_SourceFragment,
                    sourceFragment);
            }

            return errorMessage.ToString();
        }
 /// <summary>
 /// Writes a detailed error message to the buffer
 /// </summary>
 /// <param name="buffer">Instance of <see cref="StringBuilder"/></param>
 /// <param name="jsException">JS exception</param>
 /// <param name="omitMessage">Flag for whether to omit message</param>
 private static void WriteCommonErrorDetails(StringBuilder buffer, JsException jsException,
                                             bool omitMessage = false)
 {
     if (!omitMessage)
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Message,
                                 jsException.Message);
     }
     if (!string.IsNullOrWhiteSpace(jsException.EngineName))
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineName,
                                 jsException.EngineName);
     }
     if (!string.IsNullOrWhiteSpace(jsException.EngineVersion))
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineVersion,
                                 jsException.EngineVersion);
     }
     if (!string.IsNullOrWhiteSpace(jsException.Category))
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Category,
                                 jsException.Category);
     }
     if (!string.IsNullOrWhiteSpace(jsException.Description))
     {
         buffer.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Description,
                                 jsException.Description);
     }
 }
Ejemplo n.º 12
0
        private void DisplayItems(IEnumerable <IItem> items, bool shortDisplay, bool displayNothing) // equivalent to act_info.C:show_list_to_char
        {
            StringBuilder sb         = new StringBuilder();
            var           enumerable = items as IItem[] ?? items.ToArray();

            if (displayNothing && !enumerable.Any())
            {
                sb.AppendLine("Nothing.");
            }
            else
            {
                // Grouped by description
                foreach (var groupedFormattedItem in enumerable.Select(item => FormatItem(item, shortDisplay)).GroupBy(x => x))
                {
                    int count = groupedFormattedItem.Count();
                    if (count > 1)
                    {
                        sb.AppendFormatLine("%W%({0,2})%x% {1}", count, groupedFormattedItem.Key);
                    }
                    else
                    {
                        sb.AppendFormatLine("     {0}", groupedFormattedItem.Key);
                    }
                }
            }
            Send(sb);
        }
Ejemplo n.º 13
0
        private static string GetContentsTable(string path)
        {
            var sb = new StringBuilder();

            sb.AppendLine(TOC_START);

            var dirs = Directory.GetDirectories(path);

            foreach (var dir in dirs)
            {
                var rawDir = Path.GetFileName(dir);
                sb.AppendFormatLine("* **[{0}]({0}/index.md)**", rawDir);
            }

            var files = Directory.GetFiles(path, "*.md");

            foreach (var file in files)
            {
                var rawFile      = Path.GetFileName(file);
                var rawFileNoext = Path.GetFileNameWithoutExtension(file);
                sb.AppendFormatLine("* [{0}]({1})", rawFileNoext, rawFile);
            }

            sb.AppendLine();
            sb.AppendLine(TOC_END);

            return(sb.ToString());
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Wraps a compiled code
        /// </summary>
        /// <param name="compiledCode">Compiled code</param>
        /// <param name="templateNamespace">Template namespace</param>
        /// <param name="templateName">Template name</param>
        /// <param name="isPartial">Flag indicating whether template is partial</param>
        /// <returns>Wrapped code</returns>
        private static string WrapCompiledTemplateCode(string compiledCode, string templateNamespace,
                                                       string templateName, bool isPartial)
        {
            var           stringBuilderPool = StringBuilderPool.Shared;
            StringBuilder contentBuilder    = stringBuilderPool.Rent();

            if (!isPartial)
            {
                contentBuilder.AppendLine("(function(handlebars, templates) {");
                contentBuilder.AppendFormatLine("	templates['{0}'] = handlebars.template({1});",
                                                templateName, compiledCode);
                contentBuilder.AppendFormatLine("}})(Handlebars, {0} = {0} || {{}});", templateNamespace);
            }
            else
            {
                contentBuilder.AppendLine("(function(handlebars) {");
                contentBuilder.AppendFormatLine("	handlebars.partials['{0}'] = handlebars.template({1});",
                                                templateName, compiledCode);
                contentBuilder.AppendLine("})(Handlebars);");
            }

            string content = contentBuilder.ToString();

            stringBuilderPool.Return(contentBuilder);

            return(content);
        }
Ejemplo n.º 15
0
 public void WriteInputParametersDeclaration()
 {
     foreach (var inputParameter in _reader.GetInputParametersMetadata())
     {
         _output.AppendFormatLine("\t\tprivate {0} {1}Input;", inputParameter.TypeName, inputParameter.Name);
     }
 }
Ejemplo n.º 16
0
        protected virtual bool DoWhere(string rawParameters, params CommandParameter[] parameters)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormatLine($"[{Room.Area.DisplayName}].");
            if (parameters.Length == 0)
            {
                sb.AppendLine("Peoples near you:");
                bool found = false;
                foreach (IPlayer player in Room.Area.Players.Where(x => CanSee(x.Impersonating)))
                {
                    sb.AppendFormatLine("{0,-28} {1}", player.Impersonating.DisplayName, player.Impersonating.Room.DisplayName);
                    found = true;
                }
                if (!found)
                {
                    sb.AppendLine("None");
                }
            }
            else
            {
                bool found = false;
                foreach (IPlayer player in Room.Area.Players.Where(x => CanSee(x.Impersonating) && FindHelpers.StringListStartsWith(x.Impersonating.Keywords, parameters[0].Tokens)))
                {
                    sb.AppendFormatLine("{0,-28} {1}", player.Impersonating.DisplayName, player.Impersonating.Room.DisplayName);
                    found = true;
                }
                if (!found)
                {
                    sb.AppendLine($"You didn't find any {parameters[0]}.");
                }
            }
            Send(sb);
            return(true);
        }
Ejemplo n.º 17
0
        public override void ToString(StringBuilder builder)
        {
            builder.AppendFormatLine("{0} ({0:D}) loot contains {1} and {2} items",
                                     this.Type, this.Gold, this.Items.Count);
            builder.AppendLine("Object: " + this.Guid);

            builder.AppendLine();
            builder.AppendLine("Items: " + this.Items.Count);

            foreach (Item item in this.Items)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, " [{0}] (Permission: {1}) {2} x {3} (DisplayId: {4})",
                                     item.Index, item.Perm, item.Count, item.Entry, item.DisplayId);

                if (item.RandomPropertyId != 0 || item.RandomSuffix != 0)
                {
                    builder.AppendFormatLine(" (Random: Suffix {0}, PropertyId {1})",
                                             item.RandomSuffix, item.RandomPropertyId);
                }
                else
                {
                    builder.AppendLine();
                }
            }

            builder.AppendLine();
            builder.AppendLine("Currencies: " + this.Currencies.Count);

            foreach (Currency currency in this.Currencies)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, " [{0}] {1} x {2}",
                                     currency.Index, currency.Count, currency.Entry);
            }
        }
Ejemplo n.º 18
0
        private string BuildExceptionString(Exception ex)
        {
            var str = new StringBuilder(Environment.NewLine);

            str.AppendLine("__Exception__");
            str.AppendFormatLine("Message:{0}", ex.Message);
            str.AppendFormatLine("Source:{0}", ex.Source);
            str.AppendFormatLine("Stack Trace:{0}", ex.StackTrace);
            str.AppendFormatLine("Target Site:{0}", ex.TargetSite);
            if (ex.Data.Count > 0)
            {
                str.AppendLine("___Exception Data___:");
                foreach (DictionaryEntry de in ex.Data)
                {
                    str.AppendFormatLine("Key: {0,-20} - Value: {1}", de.Key.ToString(), de.Value);
                }
                str.AppendLine("___Exception Data End___:");
            }
            str.AppendLine("__End Exception__");
            var innerExeption = ex.InnerException;
            var i             = 1;

            while (innerExeption != null)
            {
                str.AppendLine(FormatInnerExeption(innerExeption, i++));
                innerExeption = innerExeption.InnerException;
            }
            return(str.ToString());
        }
Ejemplo n.º 19
0
        public override void ProcessEvent(HP.HPTRIM.SDK.Database db,
                                          HP.HPTRIM.SDK.TrimEvent eventData)
        {
            StringBuilder logEntry = new StringBuilder();

            logEntry.AppendFormatLine("=========  Event: {0}, from machine: {1}, for user: {2}. =============",
                                      eventData.EventType, eventData.FromMachine, eventData.LoginName);

            // a description of the object affected
            if (eventData.ObjectType != BaseObjectTypes.Unknown)
            {
                logEntry.AppendLine(writeObjectDetails(eventData.ObjectType, eventData.ObjectUri, db));
            }

            // a description of the related object
            if (eventData.RelatedObjectType != BaseObjectTypes.Unknown)
            {
                logEntry.Append("Related Object Details: ");
                logEntry.AppendFormatLine(writeObjectDetails(eventData.RelatedObjectType, eventData.RelatedObjectUri, db));
            }

            if (eventData.ExtraDetails.Length > 0)
            {
                logEntry.AppendFormatLine("Extra event details: {0}", eventData.ExtraDetails);
            }

            OpenLogFile(db.GetTRIMFolder(TrimPathType.AuditLog, true));

            m_logFile.Write(logEntry.ToString());
        }
Ejemplo n.º 20
0
        private string FormatInnerExeption(Exception innerExeption, int i)
        {
            var innExeption = new StringBuilder();

            innExeption.Append('\t', i);
            innExeption.AppendLine("__Inner Exception__");
            innExeption.Append('\t', i);
            innExeption.AppendFormatLine("Message:{0}", innerExeption.Message);
            innExeption.Append('\t', i);
            innExeption.AppendFormatLine("Source:{0}", innerExeption.Source);
            innExeption.Append('\t', i);
            innExeption.AppendFormatLine("Stack Trace:{0}", innerExeption.StackTrace);
            innExeption.Append('\t', i);
            innExeption.AppendFormatLine("Target Site:{0}", innerExeption.TargetSite);
            if (innerExeption.Data.Count > 0)
            {
                innExeption.Append('\t', i);
                innExeption.AppendLine("___Exception Data___:");
                foreach (DictionaryEntry de in innerExeption.Data)
                {
                    innExeption.Append('\t', i);
                    innExeption.AppendFormatLine("Key: {0,-20} - Value: {1}", de.Key.ToString(), de.Value);
                }
                innExeption.Append('\t', i);
                innExeption.AppendLine("___Exception Data End___:");
            }
            innExeption.Append('\t', i);
            innExeption.Append("__End Inner Exception__");
            return(innExeption.ToString());
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Generates a detailed error message
        /// </summary>
        /// <param name="errorDetails">Error details</param>
        /// <param name="sourceCode">Source code</param>
        /// <param name="currentFilePath">Path to current EcmaScript2015-file</param>
        /// <returns>Detailed error message</returns>
        private static string FormatErrorDetails(JToken errorDetails, string sourceCode,
                                                 string currentFilePath)
        {
            var    message        = errorDetails.Value <string>("message");
            string file           = currentFilePath;
            var    lineNumber     = errorDetails.Value <int>("lineNumber");
            var    columnNumber   = errorDetails.Value <int>("columnNumber");
            string sourceFragment = SourceCodeNavigator.GetSourceFragment(sourceCode,
                                                                          new SourceCodeNodeCoordinates(lineNumber, columnNumber));

            var errorMessage = new StringBuilder();

            errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message, message);
            if (!string.IsNullOrWhiteSpace(file))
            {
                errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, file);
            }
            if (lineNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineNumber,
                                              lineNumber.ToString(CultureInfo.InvariantCulture));
            }
            if (columnNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ColumnNumber,
                                              columnNumber.ToString(CultureInfo.InvariantCulture));
            }
            if (!string.IsNullOrWhiteSpace(sourceFragment))
            {
                errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
                                              CoreStrings.ErrorDetails_SourceError, sourceFragment);
            }

            return(errorMessage.ToString());
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Wraps a compiled code
        /// </summary>
        /// <param name="compiledCode">Compiled code</param>
        /// <param name="variableName">Variable name for wrapper</param>
        /// <param name="templateName">Template name</param>
        /// <param name="enableNativeMinification">Flag that indicating to use of native minification</param>
        /// <returns>Wrapped code</returns>
        private static string WrapCompiledTemplateCode(string compiledCode, string variableName,
                                                       string templateName, bool enableNativeMinification)
        {
            var           stringBuilderPool = StringBuilderPool.Shared;
            StringBuilder contentBuilder    = stringBuilderPool.Rent();

            if (!enableNativeMinification)
            {
                contentBuilder.AppendFormatLine("if (!!!{0}) var {0} = {{}};", variableName);
                contentBuilder.AppendFormatLine("{0}['{1}'] = new Hogan.Template({2});",
                                                variableName, templateName, compiledCode);
            }
            else
            {
                contentBuilder.AppendFormat("if(!!!{0})var {0}={{}};", variableName);
                contentBuilder.AppendFormat("{0}['{1}']=new Hogan.Template({2});",
                                            variableName, templateName, compiledCode);
            }

            string content = contentBuilder.ToString();

            stringBuilderPool.Return(contentBuilder);

            return(content);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Send expiry warning emails to users (Web Authors) of pages about to expire
        /// </summary>
        /// <param name="emailTo">
        /// who to send the email to
        /// </param>
        /// <param name="userPages">
        /// User details and list of expiring pages for this user
        /// </param>
        public void UserPageExpiryEmail(string emailTo, UserPagesModel userPages)
        {
            var siteUri = ConfigurationManager.AppSettings["SiteUri"];

            var subject = string.Format("ACTION: Your {0} pages expire in under 14 days", _umbracoSystem);
            var body    = new StringBuilder();

            body.AppendFormatLine("<p>Your {0} pages will expire within the next two weeks. After this they will no longer be available to the public. The dates for each page are given below.</p>", _umbracoSystem);
            body.AppendLine("<p>Note, you should always use Google Chrome to update your pages. If your default web browser is Internet Explorer, you will need to right-click and copy and paste the links below into Chrome instead.</p>");
            body.AppendLine("<p>After you’ve logged in, click on each page below and:</p>");
            body.AppendLine("<ul>");
            body.AppendLine("<li>check they are up to date</li>");
            body.AppendLine("<li>check the information is still needed</li>");
            body.AppendLine("<li>go to Properties tab and use the calendar to set a new date in the 'Unpublish at' box</li>");
            body.AppendLine("<li>then click 'Save and publish'.</li>");
            body.AppendLine("</ul>");
            body.AppendLine("<p>For details on updating your pages, see <a href=\"" + ConfigurationManager.AppSettings["WebAuthorsGuidanceUrl"] + "\">Guidance for web authors</a>.</p>");

            var otherTitle       = "Expiring Pages:";
            var warningDate      = DateTime.Now.AddDays(2);
            var lastWarningPages = userPages.Pages.Where(d => d.ExpiryDate <= warningDate).ToList();

            if (lastWarningPages.Any())
            {
                body.AppendLine("<strong>Pages Expiring Tomorrow:</strong>");
                body.AppendLine("<ol>");
                foreach (var page in lastWarningPages)
                {
                    var linkUrl = string.Format("{0}#/content/content/edit/{1}", siteUri, page.PageId);
                    body.Append("<li>");
                    body.AppendFormat("<a href=\"{0}\">{1}</a> (expires {2}, {3})", linkUrl, page.PageName, page.ExpiryDate.ToLongDateString(), page.ExpiryDate.ToShortTimeString());
                    body.AppendFormat("<br/>{0}", page.PageUrl);
                    body.Append("</li>");
                }
                body.AppendLine("</ol>");

                otherTitle = "Other Pages:";
            }

            // Process remaining pages
            var nonWarningPages = userPages.Pages.Where(d => d.ExpiryDate > warningDate).ToList();

            if (nonWarningPages.Any())
            {
                body.AppendFormatLine("<strong>{0}</strong>", otherTitle);
                body.AppendLine("<ol>");
                foreach (var page in nonWarningPages)
                {
                    var linkUrl = string.Format("{0}#/content/content/edit/{1}", siteUri, page.PageId);
                    body.Append("<li>");
                    body.AppendFormat("<a href=\"{0}\">{1}</a> (expires {2}, {3})", linkUrl, page.PageName, page.ExpiryDate.ToLongDateString(), page.ExpiryDate.ToShortTimeString());
                    body.AppendFormat("<br/>{0}", page.PageUrl);
                    body.Append("</li>");
                }
                body.AppendLine("</ol>");
            }

            SmtpSendEmail(emailTo, subject, body.ToString());
        }
Ejemplo n.º 24
0
        public void WriteBody()
        {
            if (_bodyIsWritten)
            {
                return;
            }

            CreateNameOfTestFixture();

            _output.AppendFormatLine("using System.Linq;");
            _output.AppendFormatLine("using BlackBox.Testing;");
            _output.AppendFormatLine("using {0};", Configuration.TestFlavour.Namespace);
            _output.AppendLine();

            _output.AppendFormatLine("namespace CharacterizationTests");
            _output.AppendLine("{");

            if (Configuration.TestFlavour.UseFixtureAttribute())
            {
                _output.AppendFormatLine("\t[{0}]", Configuration.TestFlavour.FixtureAttribute);
            }

            if (Configuration.TestFlavour.UseCategoryAttribute())
            {
                _output.AppendFormatLine("\t[{0}(\"Characterization\")]", Configuration.TestFlavour.CategoryAttribute);
            }

            _output.AppendFormatLine("\tpublic partial class {0} : CharacterizationTest", TestFixtureName);
            _output.AppendLine("\t{");

            _parameterWriter.WriteInputParametersDeclaration();
            _parameterWriter.WriteOutputParametersDeclaration();

            if (!_reader.IsVoidMethod())
            {
                _output.AppendFormatLine("\t\tprivate {0} expected;", _reader.GetTypeOfReturnValue());
                _output.AppendFormatLine("\t\tprivate {0} actual;", _reader.GetTypeOfReturnValue());
            }

            if (!_reader.IsStaticMethod())
            {
                _output.AppendFormatLine("\t\tprivate {0} target;", _reader.GetTypeRecordingWasMadeOn());
            }

            _output.AppendLine();

            _runMethodWriter.WriteRunMethod();

            if (Configuration.TestFlavour.ConstructorAsSetup())
            {
                _setupWriter.WriteConstructor(TestFixtureName);
            }
            else
            {
                _setupWriter.WriteSetupMethod();
            }

            _bodyIsWritten = true;
        }
Ejemplo n.º 25
0
 public override string ToString()
 {
     var builder = new StringBuilder();
     builder.AppendFormatLine("First name: {0}", FirstName);
     builder.AppendFormatLine("Last name: {0}", LastName);
     builder.AppendFormatLine("Address: {0}", Address);
     return builder.ToString();
 }
Ejemplo n.º 26
0
 public static void AppendDALMethod_SelectOne(this StringBuilder sb, DDLEntity entity)
 {
     #region 方法原型
     //public ACCOUNTS SelectOne(int urid)
     //{
     //    OracleCommand command = (OracleCommand)Session.Connection.CreateCommand();
     //    command.CommandText = string.Format("select * from {0} where {1}",
     //        TableName,
     //        "URID = :URID");
     //    command.Parameters.Add(Session.GetParameter(code, BANKS.URIDProperty));
     //    var reader = Session.ExecuteDataReader(command);
     //    ACCOUNTS result = null;
     //    if (reader.Read())
     //    {
     //        result = new ACCOUNTS(reader);
     //    }
     //    return result;
     //}
     #endregion
     string methodParameterString = string.Join(",",
                                                entity.PrimaryKeyItems.Select <DDLEntityFieldItem, string>(c =>
     {
         return(string.Format("{0} {1}", c.TypeString, c.LowerTitle));
     }));
     string commandParameterString = string.Join(",",
                                                 entity.PrimaryKeyItems.Select <DDLEntityFieldItem, string>(c =>
     {
         return(string.Format(@"{0} = :{0}", c.UpperTitle));
     }));
     sb.AppendFormatLine(
         @"        public {0} SelectOne({1})
 {{
     OracleCommand command = (OracleCommand)Session.Connection.CreateCommand();
     command.CommandText = string.Format(""select * from {{0}} where {{1}}"",TableName,
         ""{2}"");",
         entity.ClassName,
         methodParameterString,
         commandParameterString);
     foreach (DDLEntityFieldItem item in entity.PrimaryKeyItems)
     {
         //目标
         //            command.Parameters.Add(Session.DBParameterGenerator.GetParameter(code, BANKS.URIDProperty));
         sb.AppendLine(string.Format(@"            command.Parameters.Add(Session.DBParameterGenerator.GetParameter({0},{1}.{2}Property));",
                                     item.LowerTitle,
                                     entity.ClassName,
                                     item.UpperTitle));
     }
     sb.AppendFormatLine(
         @"            var reader = Session.ExecuteDataReader(command);
     {0} result = null;
     if (reader.Read())
     {{
         result = new {0}(reader);
     }}
     return result;
 }}",
         entity.ClassName);
 }
Ejemplo n.º 27
0
 public void WriteSetupMethod()
 {
     _output.AppendFormatLine("\t\t[{0}]", Configuration.TestFlavour.SetupAttribute);
     _output.AppendLine("\t\tpublic void Setup()");
     _output.AppendLine("\t\t{");
     _output.AppendLine("\t\t\tInitialize();");
     _output.AppendLine("\t\t}");
     _output.AppendLine();
 }
Ejemplo n.º 28
0
        public override string ToString()
        {
            var builder = new StringBuilder();

            builder.AppendFormatLine("First name: {0}", FirstName);
            builder.AppendFormatLine("Last name: {0}", LastName);
            builder.AppendFormatLine("Address: {0}", Address);
            return(builder.ToString());
        }
Ejemplo n.º 29
0
        protected virtual bool DoAffects(string rawParameters, params CommandParameter[] parameters)
        {
            StringBuilder sb = new StringBuilder();

            if (_auras.Any() || _periodicAuras.Any())
            {
                sb.AppendLine("%c%You are affected by the following auras:%x%");
                // Auras
                foreach (IAura aura in _auras.Where(x => x.Ability == null || (x.Ability.Flags & AbilityFlags.AuraIsHidden) != AbilityFlags.AuraIsHidden))
                {
                    if (aura.Modifier == AuraModifiers.None)
                    {
                        sb.AppendFormatLine("%B%{0}%x% for %c%{1}%x%",
                                            aura.Ability == null ? "Unknown" : aura.Ability.Name,
                                            StringHelpers.FormatDelay(aura.SecondsLeft));
                    }
                    else
                    {
                        sb.AppendFormatLine("%B%{0}%x% modifies %W%{1}%x% by %m%{2}{3}%x% for %c%{4}%x%",
                                            aura.Ability == null ? "Unknown" : aura.Ability.Name,
                                            aura.Modifier,
                                            aura.Amount,
                                            aura.AmountOperator == AmountOperators.Fixed ? string.Empty : "%",
                                            StringHelpers.FormatDelay(aura.SecondsLeft));
                    }
                }
                // Periodic auras
                foreach (IPeriodicAura pa in _periodicAuras.Where(x => x.Ability == null || (x.Ability.Flags & AbilityFlags.AuraIsHidden) != AbilityFlags.AuraIsHidden))
                {
                    if (pa.AuraType == PeriodicAuraTypes.Damage)
                    {
                        sb.AppendFormatLine("%B%{0}%x% %W%deals {1}{2}%x% {3} damage every %g%{4}%x% for %c%{5}%x%",
                                            pa.Ability == null ? "Unknown" : pa.Ability.Name,
                                            pa.Amount,
                                            pa.AmountOperator == AmountOperators.Fixed ? string.Empty : "%",
                                            StringHelpers.SchoolTypeColor(pa.School),
                                            StringHelpers.FormatDelay(pa.TickDelay),
                                            StringHelpers.FormatDelay(pa.SecondsLeft));
                    }
                    else
                    {
                        sb.AppendFormatLine("%B%{0}%x% %W%heals {1}{2}%x% hp every %g%{3}%x% for %c%{4}%x%",
                                            pa.Ability == null ? "Unknown" : pa.Ability.Name,
                                            pa.Amount,
                                            pa.AmountOperator == AmountOperators.Fixed ? string.Empty : "%",
                                            StringHelpers.FormatDelay(pa.TickDelay),
                                            StringHelpers.FormatDelay(pa.SecondsLeft));
                    }
                }
            }
            else
            {
                sb.AppendLine("%c%You are not affected by any spells.%x%");
            }
            Send(sb);
            return(true);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Generates a detailed error message based on object ContextError
        /// </summary>
        /// <param name="error">Object ContextError</param>
        /// <returns>Detailed error message</returns>
        internal static string FormatContextError(ContextError error)
        {
            var           stringBuilderPool   = AdvancedStringBuilderPool.Shared;
            StringBuilder errorMessageBuilder = stringBuilderPool.Rent();

            errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message, error.Message);
            errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ErrorCode, error.ErrorCode);
            errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Severity, error.Severity);
            errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Subcategory, error.Subcategory);
            if (!string.IsNullOrWhiteSpace(error.HelpKeyword))
            {
                errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_HelpKeyword, error.HelpKeyword);
            }
            if (!string.IsNullOrWhiteSpace(error.File))
            {
                errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, error.File);
            }
            errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_StartLine, error.StartLine);
            errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_StartColumn, error.StartColumn);
            errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_EndLine, error.EndLine);
            errorMessageBuilder.AppendFormat("{0}: {1}", CoreStrings.ErrorDetails_EndColumn, error.EndColumn);

            string errorMessage = errorMessageBuilder.ToString();

            stringBuilderPool.Return(errorMessageBuilder);

            return(errorMessage);
        }
Ejemplo n.º 31
0
 /// <summary>
 /// 模板:添加构造函数字符串
 /// </summary>
 /// <param name="sb"></param>
 /// <param name="className">类名</param>
 /// <param name="parameterString">标准格式:(DataType1 DataName1, DataType2 DataName2,...)</param>
 /// <param name="assignmentString">标准格式:(            this.{0} = {1};)</param>
 /// <param name="chainingString">标准格式:(DataName1, DataName2,...)</param>
 internal static void AppendConstructor(this StringBuilder sb, string className, string parameterString, string assignmentString, string chainingString = "")
 {
     sb.AppendFormatLine("        public {0}({1})", className, parameterString);
     if (!string.IsNullOrEmpty(chainingString))
     {
         sb.AppendFormatLine("            : {0}", chainingString);
     }
     sb.AppendLine("        {");
     sb.AppendLine(assignmentString);
     sb.AppendLine("        }");
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Writes PDF image element into file stream
        /// </summary>
        /// <param name="image">PDF image element</param>
        internal void Write(ImageElement image)
        {
            var imageContent = new StringBuilder();

            imageContent.AppendLine("q");
            imageContent.AppendFormatLine("{0} 0 0 {1} {2} {3} cm", image.Width, image.Height, image.X, image.Y);
            imageContent.AppendFormatLine("{0} Do", image.GetXReference());
            imageContent.Append("Q");

            writeStreamedObject(image.ObjectId, imageContent.ToString());
        }
Ejemplo n.º 33
0
        public string WriteToString(ServerSettings serverSettings)
        {
            var sb = new StringBuilder();

            sb.AppendFormatLine(@"server:{0}", serverSettings.ServerIp);
            sb.AppendFormatLine(@"port:{0}", serverSettings.Port);
            sb.AppendLine(";Timeout in seconds");
            sb.AppendFormatLine(@"timeout:{0}", serverSettings.TimeoutInSeconds);

            return sb.ToString();
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Generates a detailed error message
        /// </summary>
        /// <param name="jsEngineLoadException">JavaScript engine load exception</param>
        /// <returns>Detailed error message</returns>
        public static string Format(JsEngineLoadException jsEngineLoadException)
        {
            var errorMessage = new StringBuilder();
            errorMessage.AppendFormatLine("{0}: {1}", CommonStrings.ErrorDetails_Message,
                jsEngineLoadException.Message);
            if (!string.IsNullOrWhiteSpace(jsEngineLoadException.EngineMode))
            {
                errorMessage.AppendFormatLine("{0}: {1}", CommonStrings.ErrorDetails_EngineMode,
                    jsEngineLoadException.EngineMode);
            }

            return errorMessage.ToString();
        }
Ejemplo n.º 35
0
		protected override string CombineAssetContent(IList<IAsset> assets)
		{
			var contentBuilder = new StringBuilder();
			int assetCount = assets.Count;
			int lastAssetIndex = assetCount - 1;

			for (int assetIndex = 0; assetIndex < assetCount; assetIndex++)
			{
				IAsset asset = assets[assetIndex];
				string assetContent = asset.Content.TrimEnd();

				if (EnableTracing)
				{
					contentBuilder.AppendFormatLine("//#region URL: {0}", asset.Url);
				}
				contentBuilder.Append(assetContent);
				if (!assetContent.EndsWith(";"))
				{
					contentBuilder.Append(";");
				}
				if (EnableTracing)
				{
					contentBuilder.AppendLine();
					contentBuilder.AppendLine("//#endregion");
				}

				if (assetIndex != lastAssetIndex)
				{
					contentBuilder.AppendLine();
				}
			}

			return contentBuilder.ToString();
		}
Ejemplo n.º 36
0
 public override void ToString(StringBuilder builder)
 {
     builder.AppendFormatLine("Seed: 0x{0:X8}  Count: {1}", Seed, Count);
     builder.Append("Client Seed: ");
     ClientSeed.ToHexString(builder);
     builder.AppendLine();
     builder.Append("Server Seed: ");
     ServerSeed.ToHexString(builder);
     builder.AppendLine();
 }
        /// <summary>
        /// Logs a information about the error
        /// </summary>
        /// <param name="category">Error category</param>
        /// <param name="message">Error message</param>
        /// <param name="filePath">File path</param>
        /// <param name="lineNumber">Line number on which the error occurred</param>
        /// <param name="columnNumber">Column number on which the error occurred</param>
        /// <param name="sourceFragment">Fragment of source code</param>
        public override void Error(string category, string message, string filePath = "",
			int lineNumber = 0, int columnNumber = 0, string sourceFragment = "")
        {
            var errorMessage = new StringBuilder();
            errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Category, category);
            errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Message, message);

            if (!string.IsNullOrWhiteSpace(filePath))
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_File, filePath);
            }

            if (lineNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_LineNumber, lineNumber);
            }

            if (columnNumber > 0)
            {
                errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ColumnNumber, columnNumber);
            }

            if (!string.IsNullOrWhiteSpace(sourceFragment))
            {
                errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
                    Strings.ErrorDetails_SourceFragment, sourceFragment);
            }

            throw new MarkupMinificationException(errorMessage.ToString());
        }
Ejemplo n.º 38
0
		private void Output(String msg, Boolean error = false)
		{
			var sb = new StringBuilder();
			var start = txtOutput.TextLength;

			sb.AppendFormatLine("> {0}", msg);
			txtOutput.AppendText(sb.ToString());

			txtOutput.Select(start, txtOutput.TextLength - 1);
			txtOutput.SelectionColor = error ? Color.DarkRed : Color.Black;

			txtOutput.DeselectAll();

			txtOutput.Refresh();
		}
		/// <summary>
		/// Generates a detailed error message
		/// </summary>
		/// <param name="jsRuntimeException">JavaScript runtime exception</param>
		/// <returns>Detailed error message</returns>
		public static string Format(JsRuntimeException jsRuntimeException)
		{
			var errorMessage = new StringBuilder();
			errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Message,
				jsRuntimeException.Message);
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.EngineName))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineName,
					jsRuntimeException.EngineName);
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.EngineVersion))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_EngineVersion,
					jsRuntimeException.EngineVersion);
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.ErrorCode))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ErrorCode,
					jsRuntimeException.ErrorCode);
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.Category))
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_Category,
					jsRuntimeException.Category);
			}
			if (jsRuntimeException.LineNumber > 0)
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_LineNumber,
					jsRuntimeException.LineNumber.ToString(CultureInfo.InvariantCulture));
			}
			if (jsRuntimeException.ColumnNumber > 0)
			{
				errorMessage.AppendFormatLine("{0}: {1}", Strings.ErrorDetails_ColumnNumber,
					jsRuntimeException.ColumnNumber.ToString(CultureInfo.InvariantCulture));
			}
			if (!string.IsNullOrWhiteSpace(jsRuntimeException.SourceFragment))
			{
				errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
					Strings.ErrorDetails_SourceFragment,
					jsRuntimeException.SourceFragment);
			}

			return errorMessage.ToString();
		}
Ejemplo n.º 40
0
		protected override string CombineAssetContent(IList<IAsset> assets)
		{
			var contentBuilder = new StringBuilder();
			string topCharset = string.Empty;
			var imports = new List<string>();

			int assetCount = assets.Count;
			int lastAssetIndex = assetCount - 1;

			for (int assetIndex = 0; assetIndex < assetCount; assetIndex++)
			{
				IAsset asset = assets[assetIndex];

				if (EnableTracing)
				{
					contentBuilder.AppendFormatLine("/*#region URL: {0} */", asset.Url);
				}
				contentBuilder.Append(EjectCssCharsetAndImports(asset.Content, ref topCharset, imports));
				if (EnableTracing)
				{
					contentBuilder.AppendLine();
					contentBuilder.AppendLine("/*#endregion*/");
				}

				if (assetIndex != lastAssetIndex)
				{
					contentBuilder.AppendLine();
				}
			}

			if (imports.Count > 0)
			{
				string importsTemplate = EnableTracing ?
					"/*#region CSS Imports */{0}{1}{0}/*#endregion*/{0}{0}" : "{1}{0}";

				contentBuilder.Insert(0, string.Format(importsTemplate, Environment.NewLine,
					string.Join(Environment.NewLine, imports)));
			}

			if (!string.IsNullOrWhiteSpace(topCharset))
			{
				contentBuilder.Insert(0, topCharset + Environment.NewLine);
			}

			return contentBuilder.ToString();
		}
Ejemplo n.º 41
0
        public static void ShowError(FrameworkElement owner, Exception exception, string formatMessage = null, params object[] args)
        {
            Log.Error(exception, formatMessage, args);

            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrEmpty(formatMessage))
                sb.AppendFormatLine(formatMessage, args);
            if (exception != null)
                sb.Append(exception);

            if (owner == null)
            {
                MessageBox.Show(sb.ToString(), "Ошибка!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                Window window = (Window)owner.GetRootElement();
                MessageBox.Show(window, sb.ToString(), "Ошибка!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 42
0
    /// <summary>
    /// Constructs exception composing details from response, method specific error description and actual inner exception
    /// </summary>
    /// <param name="response">Response of failed request</param>
    /// <param name="stripeErrorMessage">Method specific error description</param>
    /// <param name="inner">Actual inner exception</param>
    /// <returns>Composed exception</returns>
    public static TaxException Compose(HttpWebResponse response, string stripeErrorMessage, Exception inner)
    {
      int statusCode = (int)response.StatusCode;

      string responseErrMsg = string.Empty;
      try
      {
        using(var reponseStream  = response.GetResponseStream())
        {
          using (var responseReader = new System.IO.StreamReader(reponseStream))
          {
            string responseStr = responseReader.ReadToEnd();
            dynamic responseObj = responseStr.JSONToDynamic();
            var sb = new StringBuilder();
            foreach (var item in ((JSONDataMap)responseObj.Data))
            {
              sb.AppendFormatLine("{0}: {1}", item.Key, item.Value);
            }
            responseErrMsg = sb.ToString();
          }
        }
      }
      catch (Exception)
      {
        // dlatushkin 2014/04/07:
        // there is no way to test some cases (50X errors for example)
        // so try/catch is used to swallow exception
      }

      string specificError = System.Environment.NewLine;
      if (responseErrMsg.IsNotNullOrWhiteSpace())
        specificError += StringConsts.PAYMENT_STRIPE_ERR_MSG_ERROR.Args( responseErrMsg) + System.Environment.NewLine;

      specificError += stripeErrorMessage;

      TaxException ex = new TaxException(specificError, inner);

      return ex;
    }
Ejemplo n.º 43
0
        private static string GetHeader(IEnumerable<string> assemblyPaths, bool forceDueToSpecialType)
        {
            if (!forceDueToSpecialType && !assemblyPaths.Any())
            {
                return "";
            }

            if (!assemblyPaths.All(File.Exists))
            {
                return "";
            }

            var sb = new StringBuilder();
            sb.AppendFormatLine("//****************************************************************");
            sb.AppendFormatLine("//  Generated by:  ToTypeScriptD");
            sb.AppendFormatLine("//  Website:       http://github.com/ToTypeScriptD/ToTypeScriptD");
            sb.AppendFormatLine("//  Version:       {0}", System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(Render).Assembly.Location).ProductVersion);
            sb.AppendFormatLine("//  Date:          {0}", DateTime.Now);
            if (assemblyPaths.Any())
            {
                sb.AppendFormatLine("//");
                sb.AppendFormatLine("//  Assemblies:");
                assemblyPaths
                    .Select(System.IO.Path.GetFileName)
                    .Distinct()
                    .OrderBy(s => s)
                    .Each(path =>
                    {
                        sb.AppendFormatLine("//    {0}", System.IO.Path.GetFileName(path));
                    });
                sb.AppendFormatLine("//");
            }
            sb.AppendFormatLine("//****************************************************************");
            sb.AppendFormatLine();
            sb.AppendFormatLine();
            sb.AppendFormatLine();
            return sb.ToString();
        }
Ejemplo n.º 44
0
        private void CreateAIScript_Click(object sender, EventArgs e)
        {
            err = false;
            rtbScriptOut.Clear();
            rtbScriptOut.ForeColor = Color.Blue;

            ScriptAI script             = new ScriptAI();
            script.ID                   = _tbScriptID.Text.ToInt32();
            script.NpcEntry             = _tbEntryNpc.Text.ToInt32();
            script.EventType            = _cbEventType.GetIntValue();
            script.Phase                = _clbPhase.GetFlagsValue();
            script.Chance               = _tbShance.Text.ToInt32();
            script.Flags                = _clbEventFlag.GetFlagsValue();

            script.EventParam[0]        = _cbEventParametr1.GetIntValue();
            script.EventParam[1]        = _cbEventParametr2.GetIntValue();
            script.EventParam[2]        = _cbEventParametr3.GetIntValue();
            script.EventParam[3]        = _cbEventParametr4.GetIntValue();

            script.ActionType[0]        = _cbActionType1.GetIntValue();
            script.ActionParam[0, 0]    = _cbActionParam1_1.GetIntValue();
            script.ActionParam[0, 1]    = _cbActionParam1_2.GetIntValue();
            script.ActionParam[0, 2]    = _cbActionParam1_3.GetIntValue();

            script.ActionType[1]        = _cbActionType2.GetIntValue();
            script.ActionParam[1, 0]    = _cbActionParam2_1.GetIntValue();
            script.ActionParam[1, 1]    = _cbActionParam2_2.GetIntValue();
            script.ActionParam[1, 2]    = _cbActionParam2_3.GetIntValue();

            script.ActionType[2]        = _cbActionType3.GetIntValue();
            script.ActionParam[2, 0]    = _cbActionParam3_1.GetIntValue();
            script.ActionParam[2, 1]    = _cbActionParam3_2.GetIntValue();
            script.ActionParam[2, 2]    = _cbActionParam3_3.GetIntValue();

            script.Comment              = _tbComment.Text;

            #region Проверки

            if (script.ID < 1)
                LogOut("Номен скрипта должен быть больше 0!");

            if (script.Chance == 0 || script.Chance > 100)
                LogOut("Шанс срабатывания должен быть 0 и не больше 100%!");

            switch ((EventType)script.EventType)
            {
                case EventType.ПО_ТАЙМЕРУ_В_БОЮ:
                case EventType.ПО_ТАЙМЕРУ_ВНЕ_БОЯ:
                    if (script.EventParam[0] > script.EventParam[1])
                        LogOut("Минимальное время до срабатывания не может быть больше максимального!");
                    if (script.EventParam[2] > script.EventParam[3])
                        LogOut("Минимальное время до повтора не может быть больше максимального!");
                    break;
                case EventType.ПРИ_ЗНАЧЕНИИ_ЖИЗНИ:
                case EventType.ПРИ_ЗНАЧЕНИИ_МАНЫ:
                case EventType.ПРИ_ЗНАЧЕНИИ_ЖИЗНИ_ЦЕЛИ:
                case EventType.ПРИ_ЗНАЧЕНИИ_МАНЫ_У_ЦЕЛИ:
                    if (script.EventParam[0] > 100 || script.EventParam[1] > 100)
                        LogOut("Параметр 1 или 2 не могут быть болше 100%!");
                    if (script.EventParam[1] > script.EventParam[0])
                        LogOut("Минимальное значение жизни(маны) не может быть больше максимального!");
                    if (script.EventParam[2] > script.EventParam[3])
                        LogOut("Минимальное время до повтора не может быть больше максимального!");
                    break;
                case EventType.ПРИ_УБИЙСТВЕ_ЦЕЛИ:
                    if (script.EventParam[0] > script.EventParam[1])
                        LogOut("Минимальное время до повтора не может быть больше максимального!");
                    break;
                case EventType.ПРИ_УРОНЕ_ЗАКЛИНАНИЕМ:
                    if (script.EventParam[2] > script.EventParam[3])
                        LogOut("Минимальное время до повтора не может быть больше максимального!");
                    if (script.EventParam[0] > 0 && script.EventParam[1] > -1)
                        LogOut("Если указано значение \"ID Заклинания\", тогда значение \"Школа\" должно быть (-1), иначе \"ИД заклинания\" должно быть (0)");
                    break;
                case EventType.ПРИ_ДИСТАНЦИИ:
                    if (script.EventParam[0] > script.EventParam[1])
                        LogOut("Минимальная дистанция до цели не может быть больше максимальной!");
                    if (script.EventParam[2] > script.EventParam[3])
                        LogOut("Минимальное время до повтора не может быть больше максимального!");
                    break;
                case EventType.ПРИ_ПОЯВЛЕНИИ_В_ЗОНЕ_ВИДИМОСТИ:
                    if (script.EventParam[2] > script.EventParam[3])
                        LogOut("Минимальное время до повтора не может быть больше максимального!");
                    break;
                case EventType.ЕСЛИ_ЦЕЛЬ_ЧИТАЕТ_ЗАКЛИНАНИЕ:
                    if (script.EventParam[0] > script.EventParam[1])
                        LogOut("Минимальное время до повтора не может быть больше максимального!");
                    break;
            }

            if (err)
            {
                _bWriteFiles.Enabled = false;
                return;
            }

            #endregion

            StringBuilder sb = new StringBuilder();
            sb.AppendFormatLine("UPDATE `creature_template` SET `AIName` = 'EventAI' WHERE `entry` = '{0}';", script.NpcEntry);
            sb.AppendFormatLine("DELETE FROM `creature_ai_scripts` WHERE (`id`='{0}');", script.ID);
            sb.AppendFormatLine("INSERT INTO `creature_ai_scripts` VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}', '{16}', '{17}', '{18}', '{19}', '{20}', '{21}', '{22}');",
                script.ID, script.NpcEntry, script.EventType, script.Phase, script.Chance, script.Flags,
                script.EventParam[0], script.EventParam[1], script.EventParam[2], script.EventParam[3],
                script.ActionType[0], script.ActionParam[0, 0], script.ActionParam[0, 1], script.ActionParam[0, 2],
                script.ActionType[1], script.ActionParam[1, 0], script.ActionParam[1, 1], script.ActionParam[1, 2],
                script.ActionType[2], script.ActionParam[2, 0], script.ActionParam[2, 1], script.ActionParam[2, 2],
                script.Comment.RemExc());

            rtbScriptOut.Text = sb.ToString();
            _bWriteFiles.Enabled = true;
        }
Ejemplo n.º 45
0
 private void WriteAsyncPromiseMethods(StringBuilder sb)
 {
     string genericTypeArgName;
     if (IsTypeAsync(out genericTypeArgName))
     {
         sb.AppendLine();
         Indent(sb); Indent(sb); sb.AppendFormatLine("// Promise Extension");
         Indent(sb); Indent(sb); sb.AppendFormatLine("then<U>(success?: (value: {0}) => ToTypeScriptD.WinRT.IPromise<U>, error?: (error: any) => ToTypeScriptD.WinRT.IPromise<U>, progress?: (progress: any) => void): ToTypeScriptD.WinRT.IPromise<U>;", genericTypeArgName);
         Indent(sb); Indent(sb); sb.AppendFormatLine("then<U>(success?: (value: {0}) => ToTypeScriptD.WinRT.IPromise<U>, error?: (error: any) => U, progress?: (progress: any) => void): ToTypeScriptD.WinRT.IPromise<U>;", genericTypeArgName);
         Indent(sb); Indent(sb); sb.AppendFormatLine("then<U>(success?: (value: {0}) => U, error?: (error: any) => ToTypeScriptD.WinRT.IPromise<U>, progress?: (progress: any) => void): ToTypeScriptD.WinRT.IPromise<U>;", genericTypeArgName);
         Indent(sb); Indent(sb); sb.AppendFormatLine("then<U>(success?: (value: {0}) => U, error?: (error: any) => U, progress?: (progress: any) => void): ToTypeScriptD.WinRT.IPromise<U>;", genericTypeArgName);
         Indent(sb); Indent(sb); sb.AppendFormatLine("done<U>(success?: (value: {0}) => any, error?: (error: any) => any, progress?: (progress: any) => void): void;", genericTypeArgName);
     }
 }
Ejemplo n.º 46
0
        public ProcInfo(TreeView familyTree, SpellFamilyNames spellfamily)
        {
            familyTree.Nodes.Clear();

            var spells = from Spell in DBC.Spell
                         where Spell.Value.SpellFamilyName == (uint)spellfamily
                         join sk in DBC.SkillLineAbility on Spell.Key equals sk.Value.SpellId into temp1
                         from Skill in temp1.DefaultIfEmpty()
                         join skl in DBC.SkillLine on Skill.Value.SkillId equals skl.Key into temp2
                         from SkillLine in temp2.DefaultIfEmpty()
                         select new
                         {
                             Spell,
                             Skill.Value.SkillId,
                             SkillLine.Value
                         };

            for (int i = 0; i < 96; i++)
            {
                uint[] mask = new uint[3];

                if (i < 32)
                    mask[0] = 1U << i;
                else if (i < 64)
                    mask[1] = 1U << (i - 32);
                else
                    mask[2] = 1U << (i - 64);

                TreeNode node   = new TreeNode();
                node.Text       = String.Format("0x{0:X8} {1:X8} {2:X8}", mask[2], mask[1], mask[0]);
                node.ImageKey   = "family.ico";
                familyTree.Nodes.Add(node);
            }

            foreach (var elem in spells)
            {
                SpellEntry spell = elem.Spell.Value;
                bool IsSkill     = elem.SkillId != 0;

                StringBuilder name    = new StringBuilder();
                StringBuilder toolTip = new StringBuilder();

                name.AppendFormat("{0} - {1} ", spell.ID, spell.SpellNameRank);

                toolTip.AppendFormatLine("Spell Name: {0}",  spell.SpellNameRank);
                toolTip.AppendFormatLine("Description: {0}", spell.Description);
                toolTip.AppendFormatLine("ToolTip: {0}",     spell.ToolTip);

                if (IsSkill)
                {
                    name.AppendFormat("(Skill: ({0}) {1}) ", elem.SkillId, elem.Value.Name);

                    toolTip.AppendLine();
                    toolTip.AppendFormatLine("Skill Name: {0}",  elem.Value.Name);
                    toolTip.AppendFormatLine("Description: {0}", elem.Value.Description);
                }

                name.AppendFormat("({0})", spell.School.ToString().NormaliseString("MASK_"));

                foreach (TreeNode node in familyTree.Nodes)
                {
                    uint[] mask = new uint[3];

                    if (node.Index < 32)
                        mask[0] = 1U << node.Index;
                    else if (node.Index < 64)
                        mask[1] = 1U << (node.Index - 32);
                    else
                        mask[2] = 1U << (node.Index - 64);

                    if ((spell.SpellFamilyFlags.ContainsElement(mask)))
                    {
                        TreeNode child  = new TreeNode();
                        child           = node.Nodes.Add(name.ToString());
                        child.Name      = spell.ID.ToString();
                        child.ImageKey  = IsSkill ? "plus.ico" : "munus.ico";
                        child.ForeColor = IsSkill ? Color.Blue : Color.Red;
                        child.ToolTipText = toolTip.ToString();
                    }
                }
            }
        }
Ejemplo n.º 47
0
		/// <summary>
		/// Generates a detailed error message
		/// </summary>
		/// <param name="errorDetails">Error details</param>
		/// <param name="sourceCode">Source code</param>
		/// <param name="currentFilePath">Path to current LESS-file</param>
		/// <param name="dependencies">List of dependencies</param>
		/// <returns>Detailed error message</returns>
		private static string FormatErrorDetails(JToken errorDetails, string sourceCode, string currentFilePath,
			DependencyCollection dependencies)
		{
			var type = errorDetails.Value<string>("type");
			var message = errorDetails.Value<string>("message");
			var filePath = errorDetails.Value<string>("fileName");
			if (string.IsNullOrWhiteSpace(filePath))
			{
				filePath = currentFilePath;
			}
			var lineNumber = errorDetails.Value<int>("lineNumber");
			var columnNumber = errorDetails.Value<int>("columnNumber");

			string newSourceCode = string.Empty;
			if (string.Equals(filePath, currentFilePath, StringComparison.OrdinalIgnoreCase))
			{
				newSourceCode = sourceCode;
			}
			else
			{
				var dependency = dependencies.GetByUrl(filePath);
				if (dependency != null)
				{
					newSourceCode = dependency.Content;
				}
			}

			string sourceFragment = SourceCodeNavigator.GetSourceFragment(newSourceCode,
				new SourceCodeNodeCoordinates(lineNumber, columnNumber));

			var errorMessage = new StringBuilder();
			if (!string.IsNullOrWhiteSpace(type))
			{
				errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ErrorType, type);
			}
			errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message, message);
			if (!string.IsNullOrWhiteSpace(filePath))
			{
				errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, filePath);
			}
			if (lineNumber > 0)
			{
				errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineNumber,
					lineNumber.ToString(CultureInfo.InvariantCulture));
			}
			if (columnNumber > 0)
			{
				errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ColumnNumber,
					columnNumber.ToString(CultureInfo.InvariantCulture));
			}
			if (!string.IsNullOrWhiteSpace(sourceFragment))
			{
				errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
					CoreStrings.ErrorDetails_SourceError, sourceFragment);
			}

			return errorMessage.ToString();
		}
Ejemplo n.º 48
0
        public override void ToString(StringBuilder builder)
        {
            builder.AppendLine("Cast Id: " + CastId);
            builder.AppendLine("Spell Id: " + SpellId);
            builder.AppendLine("Unk Id: " + UnknownId);
            builder.AppendFormatLine("Unk Flags: {0:X2}", UnknownFlags);

            TargetData.ToString(builder);
        }
		/// <summary>
		/// Generates a detailed error message
		/// </summary>
		/// <param name="errorDetails">Error details</param>
		/// <param name="errorType">Error type</param>
		/// <param name="currentFilePath">Current file path</param>
		/// <param name="externsDependencies">List of JS-externs dependencies</param>
		/// <returns>Detailed error message</returns>
		private static string FormatErrorDetails(JToken errorDetails, ErrorType errorType, string currentFilePath,
			DependencyCollection externsDependencies)
		{
			var errorMessageBuilder = new StringBuilder();
			if (errorType == ErrorType.ServerError || errorType == ErrorType.Error)
			{
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message,
					errorDetails.Value<string>("error"));
			}
			else if (errorType == ErrorType.Warning)
			{
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message,
					errorDetails.Value<string>("warning"));
			}
			if (errorDetails["code"] != null)
			{
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ErrorCode,
					errorDetails.Value<string>("code"));
			}
			if (errorDetails["type"] != null)
			{
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Subcategory,
					errorDetails.Value<string>("type"));
			}
			if (errorDetails["file"] != null)
			{
				string filePath = null;
				string file = errorDetails.Value<string>("file");
				Match errorFileMatch = _errorFileRegex.Match(file);

				if (errorFileMatch.Success)
				{
					GroupCollection errorFileGroups = errorFileMatch.Groups;

					string fileType = errorFileGroups["fileType"].Value;
					int fileIndex = int.Parse(errorFileGroups["fileIndex"].Value);

					if (string.Equals(fileType, "Externs", StringComparison.OrdinalIgnoreCase))
					{
						Dependency externsDependency;

						try
						{
							externsDependency = externsDependencies[fileIndex];
						}
						catch (ArgumentOutOfRangeException)
						{
							externsDependency = null;
						}

						if (externsDependency != null)
						{
							filePath = externsDependency.Url;
						}
					}
				}

				if (string.IsNullOrEmpty(filePath))
				{
					filePath = currentFilePath;
				}

				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, filePath);
			}
			if (errorDetails["lineno"] != null)
			{
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineNumber,
					errorDetails.Value<int>("lineno").ToString(CultureInfo.InvariantCulture));
			}
			if (errorDetails["charno"] != null)
			{
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ColumnNumber,
					errorDetails.Value<int>("charno").ToString(CultureInfo.InvariantCulture));
			}
			if (errorDetails["line"] != null)
			{
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineSource,
					errorDetails.Value<string>("line"));
			}

			return errorMessageBuilder.ToString();
		}
Ejemplo n.º 50
0
        public override void ToString(StringBuilder builder)
        {
            builder.AppendLine("Caster: " + Caster);
            builder.AppendLine("Cast Invoker: " + CastInvoker);
            builder.AppendLine("Cast Id: " + CastId);
            builder.AppendLine("Spell Id: " + SpellId);
            builder.AppendLine("Flags: " + Flags);
            builder.AppendLine("Unk 4.3 2: " + Unk43_2);
            builder.AppendLine("Unk 4.3: " + Unk43);
            builder.AppendLine();

            TargetData.ToString(builder);

            if ((Flags & CastFlags.PredictedPower) != 0)
            {
                builder.AppendLine();
                builder.AppendLine("Predicted Power: " + PredictedPower);
            }

            if ((Flags & CastFlags.RuneStates) != 0)
            {
                builder.AppendLine();
                builder.AppendLine("Runes Before: " + RunesBefore);
                builder.AppendLine("Runes After: " + RunesAfter);
                builder.Append("Rune Cooldowns: ");
                for (int i = 0; i < RuneCooldowns.Length; ++i)
                    builder.Append(RuneCooldowns[i] + " ");
                builder.AppendLine();
            }

            if ((Flags & CastFlags.Ammo) != 0)
            {
                builder.AppendLine();
                builder.AppendFormatLine("Projectile: DisplayId {0}, Inventory Type {1}",
                    ProjectileDisplayId, ProjectileInventoryType);
            }

            if ((Flags & CastFlags.Unk0x04000000) != 0)
            {
                builder.AppendLine();
                builder.AppendFormatLine("Flags 0x04000000: uint32={0}, uint32={1}", Unk0x04000000_UInt32_1, Unk0x04000000_UInt32_2);
            }
        }
Ejemplo n.º 51
0
		/// <summary>
		/// Wraps a compiled code
		/// </summary>
		/// <param name="compiledCode">Compiled code</param>
		/// <param name="variableName">Variable name for wrapper</param>
		/// <param name="templateName">Template name</param>
		/// <param name="enableNativeMinification">Flag that indicating to use of native minification</param>
		/// <returns>Wrapped code</returns>
		private static string WrapCompiledTemplateCode(string compiledCode, string variableName,
			string templateName, bool enableNativeMinification)
		{
			var contentBuilder = new StringBuilder();
			if (!enableNativeMinification)
			{
				contentBuilder.AppendFormatLine("if (!!!{0}) var {0} = {{}};", variableName);
				contentBuilder.AppendFormatLine("{0}['{1}'] = new Hogan.Template({2});",
					variableName, templateName, compiledCode);
			}
			else
			{
				contentBuilder.AppendFormat("if(!!!{0})var {0}={{}};", variableName);
				contentBuilder.AppendFormat("{0}['{1}']=new Hogan.Template({2});",
					variableName, templateName, compiledCode);
			}

			return contentBuilder.ToString();
		}
Ejemplo n.º 52
0
        /// <summary>
        /// Writes PDF path into file stream
        /// </summary>
        /// <param name="path">PDF path element</param>
        internal void Write(PathElement path)
        {
            var x = TextAdapter.FormatFloat(path.X);
              var y = TextAdapter.FormatFloat(path.Y);

              var pathCoordinates = new List<string> { PATH_START_FORMAT.Args(x, y) };
              pathCoordinates.AddRange(path.Primitives.Select(p => p.ToPdfString()));

              var closeTag = path.IsClosed ? "B" : "S";

              var pathContent = new StringBuilder();
              pathContent.AppendLine("q");
              pathContent.Append(path.Style.ToPdfString());
              pathContent.AppendFormatLine(string.Join(Constants.SPACE, pathCoordinates));
              pathContent.AppendLine(closeTag);
              pathContent.Append("Q");

              writeStreamedObject(path.ObjectId, pathContent.ToString());
        }
Ejemplo n.º 53
0
        /// <summary>
        /// Writes PDF image element into file stream
        /// </summary>
        /// <param name="image">PDF image element</param>
        internal void Write(ImageElement image)
        {
            var imageContent = new StringBuilder();
              imageContent.AppendLine("q");
              imageContent.AppendFormatLine("{0} 0 0 {1} {2} {3} cm", image.Width, image.Height, image.X, image.Y);
              imageContent.AppendFormatLine("{0} Do", image.GetXReference());
              imageContent.Append("Q");

              writeStreamedObject(image.ObjectId, imageContent.ToString());
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Writes PDF rectangle element into file stream
        /// </summary>
        /// <param name="rectangle">PDF rectangle element</param>
        internal void Write(RectangleElement rectangle)
        {
            var x = TextAdapter.FormatFloat(rectangle.X);
              var y = TextAdapter.FormatFloat(rectangle.Y);
              var w = TextAdapter.FormatFloat(rectangle.X1 - rectangle.X);
              var h = TextAdapter.FormatFloat(rectangle.Y1 - rectangle.Y);

              var rectangleContent = new StringBuilder();
              rectangleContent.AppendLine("q");
              rectangleContent.Append(rectangle.Style.ToPdfString());
              rectangleContent.AppendFormatLine("{0} {1} {2} {3} re", x, y, w, h);
              rectangleContent.AppendLine("B");
              rectangleContent.Append("Q");

              writeStreamedObject(rectangle.ObjectId, rectangleContent.ToString());
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Writes PDF text element into file stream
        /// </summary>
        /// <param name="text">PDF text element</param>
        internal void Write(TextElement text)
        {
            var escapedText = TextAdapter.FixEscapes(text.Content);

              var pdfStreamBuilder = new StringBuilder();
              pdfStreamBuilder.AppendLine("q");
              pdfStreamBuilder.AppendLine("BT");
              pdfStreamBuilder.AppendFormatLine("{0} {1} Tf", text.Font.GetResourceReference(), TextAdapter.FormatFloat(text.FontSize));
              pdfStreamBuilder.AppendFormatLine("{0} rg", text.Color.ToPdfString());
              pdfStreamBuilder.AppendFormatLine("{0} {1} Td", TextAdapter.FormatFloat(text.X), TextAdapter.FormatFloat(text.Y));
              pdfStreamBuilder.AppendFormatLine("({0}) Tj", escapedText);
              pdfStreamBuilder.AppendLine("ET");
              pdfStreamBuilder.Append("Q");

              writeStreamedObject(text.ObjectId, pdfStreamBuilder.ToString());
        }
Ejemplo n.º 56
0
		/// <summary>
		/// Generates a detailed error message
		/// </summary>
		/// <param name="errorDetails">String representation of error</param>
		/// <param name="sourceCode">Source code</param>
		/// <param name="currentFilePath">Path to current CSS-file</param>
		/// <rereturns>Detailed error message</rereturns>
		private static string FormatErrorDetails(string errorDetails, string sourceCode, string currentFilePath)
		{
			string errorMessage;

			Match errorStringMatch = _errorStringRegex.Match(errorDetails);
			if (errorStringMatch.Success)
			{
				string message = errorDetails;
				string file = currentFilePath;
				int lineNumber = int.Parse(errorStringMatch.Groups["lineNumber"].Value);
				int columnNumber = 0;
				string sourceFragment = SourceCodeNavigator.GetSourceFragment(sourceCode,
					new SourceCodeNodeCoordinates(lineNumber, columnNumber));

				var errorMessageBuilder = new StringBuilder();
				errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message,
					message);
				if (!string.IsNullOrWhiteSpace(file))
				{
					errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, file);
				}
				if (lineNumber > 0)
				{
					errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineNumber,
						lineNumber.ToString(CultureInfo.InvariantCulture));
				}
				if (columnNumber > 0)
				{
					errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ColumnNumber,
						columnNumber.ToString(CultureInfo.InvariantCulture));
				}
				if (!string.IsNullOrWhiteSpace(sourceFragment))
				{
					errorMessageBuilder.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine,
						CoreStrings.ErrorDetails_SourceError, sourceFragment);
				}

				errorMessage = errorMessageBuilder.ToString();
			}
			else
			{
				errorMessage = errorDetails;
			}

			return errorMessage;
		}
Ejemplo n.º 57
0
        private void WriteVectorArrayPrototypeExtensions(StringBuilder sb, bool wroteALengthProperty)
        {
            string genericTypeArgName;
            if (IsTypeArray(out genericTypeArgName))
            {
                sb.AppendLine();
                Indent(sb); Indent(sb); sb.AppendFormatLine("// Array.prototype extensions", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("toString(): string;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("toLocaleString(): string;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("concat(...items: {0}[][]): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("join(seperator: string): string;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("pop(): {0};", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("push(...items: {0}[]): void;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("reverse(): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("shift(): {0};", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("slice(start: number): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("slice(start: number, end: number): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("sort(): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("sort(compareFn: (a: {0}, b: {0}) => number): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("splice(start: number): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("splice(start: number, deleteCount: number, ...items: {0}[]): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("unshift(...items: {0}[]): number;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("lastIndexOf(searchElement: {0}): number;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("lastIndexOf(searchElement: {0}, fromIndex: number): number;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("every(callbackfn: (value: {0}, index: number, array: {0}[]) => boolean): boolean;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("every(callbackfn: (value: {0}, index: number, array: {0}[]) => boolean, thisArg: any): boolean;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("some(callbackfn: (value: {0}, index: number, array: {0}[]) => boolean): boolean;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("some(callbackfn: (value: {0}, index: number, array: {0}[]) => boolean, thisArg: any): boolean;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("forEach(callbackfn: (value: {0}, index: number, array: {0}[]) => void ): void;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("forEach(callbackfn: (value: {0}, index: number, array: {0}[]) => void , thisArg: any): void;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("map(callbackfn: (value: {0}, index: number, array: {0}[]) => any): any[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("map(callbackfn: (value: {0}, index: number, array: {0}[]) => any, thisArg: any): any[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("filter(callbackfn: (value: {0}, index: number, array: {0}[]) => boolean): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("filter(callbackfn: (value: {0}, index: number, array: {0}[]) => boolean, thisArg: any): {0}[];", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: {0}[]) => any): any;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: {0}[]) => any, initialValue: any): any;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: {0}[]) => any): any;", genericTypeArgName);
                Indent(sb); Indent(sb); sb.AppendFormatLine("reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: {0}[]) => any, initialValue: any): any;", genericTypeArgName);
                if (!wroteALengthProperty)
                {
                    Indent(sb); Indent(sb); sb.AppendFormatLine("length: number;", genericTypeArgName);
                }

            }
        }
Ejemplo n.º 58
0
        public override void ToString(StringBuilder builder)
        {
            builder.AppendLine("Caster: " + Caster);
            builder.AppendLine("Cast Invoker: " + CastInvoker);
            builder.AppendLine("Cast Id: " + CastId);
            builder.AppendLine("Spell Id: " + SpellId);
            builder.AppendLine("Flags: " + Flags);
            builder.AppendLine("Cast Time: " + CastTime);
            builder.AppendLine("Unk 4.3: " + Unk43);
            builder.AppendLine();

            builder.AppendLine("Total Hits: " + Hits.Count);
            foreach (WowGuid guid in Hits)
                builder.AppendLine("    " + guid);

            builder.AppendLine("Total Misses: " + Misses.Count);
            foreach (MissData miss in Misses)
                builder.AppendLine("    " + miss);

            builder.AppendLine();
            TargetData.ToString(builder);

            if ((Flags & CastFlags.PredictedPower) != 0)
            {
                builder.AppendLine();
                builder.AppendLine("Predicted Power: " + PredictedPower);
            }

            if ((Flags & CastFlags.RuneStates) != 0)
            {
                builder.AppendLine();
                builder.AppendLine("Runes Before: " + RunesBefore);
                builder.AppendLine("Runes After: " + RunesAfter);
                builder.Append("Rune Cooldowns: ");
                for (int i = 0; i < RuneCooldowns.Length; ++i)
                    builder.Append(RuneCooldowns[i] + " ");
                builder.AppendLine();
            }

            if ((Flags & CastFlags.Unk0x00020000) != 0)
            {
                builder.AppendLine();
                builder.AppendFormatLine("Flags 0x20000: float={0}, uint32={1}", Unk0x20000_Float, Unk0x20000_UInt32);
            }

            if ((Flags & CastFlags.Ammo) != 0)
            {
                builder.AppendLine();
                builder.AppendFormatLine("Projectile: DisplayId {0}, Inventory Type {1}",
                    ProjectileDisplayId, ProjectileInventoryType);
            }

            if ((Flags & CastFlags.Unk0x00080000) != 0)
            {
                builder.AppendLine();
                builder.AppendFormatLine("Flags 0x80000: uint32={0}, uint32={1}", Unk0x80000_UInt32_1, Unk0x80000_UInt32_2);
            }

            if ((TargetData.Flags & SpellCastTargetFlags.DestLocation) != 0)
            {
                builder.AppendLine();
                builder.AppendLine("Dest Location Counter: " + DestLocationCounter);
            }

            if ((TargetData.Flags & SpellCastTargetFlags.Unk4) != 0)
            {
                builder.AppendLine();
                builder.AppendLine("Unk4_Count: " + Unk4_Count);
                foreach (var pair in Unk4_List)
                {
                    builder.AppendFormatLine("  Vector3: {0}   Guid: {1}", pair.Value, pair.Key);
                    if (pair.Key.IsEmpty)
                        break;
                }
            }
        }
		public void AppendFormatLinesAppendsTheFormattedStringAndANewLine()
		{
			var sb = new StringBuilder();
			sb.AppendFormatLine("{0} {1}", "Hello", "World");

			Assert.AreEqual("Hello World" + Environment.NewLine, sb.ToString());
		}
Ejemplo n.º 60
0
		/// <summary>
		/// Generates a detailed error message
		/// </summary>
		/// <param name="message">Error message</param>
		/// <param name="currentFilePath">Path to current Mustache-file</param>
		/// <returns>Detailed error message</returns>
		private static string FormatErrorDetails(string message, string currentFilePath)
		{
			var errorMessage = new StringBuilder();
			errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message, message);
			if (!string.IsNullOrWhiteSpace(currentFilePath))
			{
				errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, currentFilePath);
			}

			return errorMessage.ToString();
		}