AppendLine() private method

private AppendLine ( ) : StringBuilder
return StringBuilder
        public override string ToString()
        {
            if (PageCount == 1)
                return "";

            var sb = new StringBuilder(512);

            sb.Append(@"<div class=""");
            sb.Append(CssClass);
            sb.Append(@""">");

            foreach (int pageSize in PageSizes)
            {
                sb.Append(@"<a href=""");
                sb.Append(HRef.Replace("pagesize=-1", "pagesize=" + pageSize));
                sb.Append(@""" title=""");
                sb.Append("show ");
                sb.Append(pageSize);
                sb.Append(@" items per page""");
                if (pageSize == CurrentPageSize)
                    sb.Append(@" class=""current page-numbers""");
                else
                    sb.Append(@" class=""page-numbers""");
                sb.Append(">");
                sb.Append(pageSize);
                sb.AppendLine("</a>");
            }
            sb.AppendLine(@"<span class=""page-numbers desc"">per page</span>");
            sb.Append("</div>");

            return sb.ToString();
        }
 public static string FormatResults(BrowseResult res)
 {
     var sb = new StringBuilder();
     sb.Append(res.NumHits);
     sb.Append(" hits out of ");
     sb.Append(res.TotalDocs);
     sb.Append(" docs\n");
     BrowseHit[] hits = res.Hits;
     var map = res.FacetMap;
     var keys = map.Keys;
     foreach (string key in keys) 
     {
         var fa = map[key];
         sb.AppendLine(key);
         var lf = fa.GetFacets();
         foreach (var bf in lf) 
         {
             sb.AppendLine("\t" + bf);
         }
     }
     foreach (BrowseHit hit in hits) 
     {
         sb.AppendLine("------------");
         sb.Append(FormatHit(hit));
         sb.AppendLine();
     }
     sb.Append("*****************************\n");
     return sb.ToString();
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        ContentNavigation content = new ContentNavigation();

        DataSet data = new DataSet();

        string[] Vector = new string[6 + 1];
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        data = content.getAllContent(Convert.ToInt32(Session["siteId"]));

        foreach (DataTable table in data.Tables)
        {
            foreach (DataRow row in table.Rows)
            {

                string link = "<a href= CMS_MainSite.aspx?GroupId=" + Convert.ToInt32(row["ContId"]) + ">" + Convert.ToString(row["ContTitle"]) + "</a>";

                Vector[Convert.ToInt32(row["ContOrdPos"])] = link;
            }

        }

        for (int i = 1; i < Vector.Length; i++)
        {
            sb.AppendLine(Convert.ToString(Vector[i]));
        }
        sb.AppendLine("<hr /> <br/>");
        div_Group_Selector.InnerHtml = sb.ToString();
    }
		protected override void DebugIsValid(StringBuilder sb)
		{
			if (this.Items == null) return;
			sb.AppendLine($"# Invalid Bulk items:");
			foreach(var i in Items.Select((item, i) => new { item, i}).Where(i=>!i.item.IsValid))
				sb.AppendLine($"  operation[{i.i}]: {i.item}");
		}
Beispiel #5
0
        public void WriteRSAParamsToFile(string file)
        {
            using (var sw = new StreamWriter(new FileStream(file, FileMode.Append, FileAccess.Write)))
            {
                var sb = new StringBuilder();

                sb.AppendLine("class RsaStore");
                sb.AppendLine("{");

                // Write all private & public rsa parameters.
                WritePublicByteArray(ref sb, "D", RsaParams.D);
                WritePublicByteArray(ref sb, "DP", RsaParams.DP);
                WritePublicByteArray(ref sb, "DQ", RsaParams.DQ);
                WritePublicByteArray(ref sb, "Exponent", RsaParams.Exponent);
                WritePublicByteArray(ref sb, "InverseQ", RsaParams.InverseQ);
                WritePublicByteArray(ref sb, "Modulus", RsaParams.Modulus);
                WritePublicByteArray(ref sb, "P", RsaParams.P);
                WritePublicByteArray(ref sb, "Q", RsaParams.Q);

                sb.AppendLine("}");

                sw.WriteLine(sb.ToString());
            }

            // Reset all values
            RsaParams = new RSAParameters();
        }
Beispiel #6
0
        public static Dictionary<string, string> Parse(string dataSource)
        {
            SortedList<string, SortedSet<string>> allCounters = PdhUtils.Parse(dataSource);
            var generated = new Dictionary<string, string>();

            foreach (string counterSet in allCounters.Keys)
            {
                string setName = NameUtils.CreateIdentifier(counterSet);

                var sb = new StringBuilder("// This code was generated by EtwEventTypeGen");
                sb.AppendLine(setName);
                sb.Append("namespace Tx.Windows.Counters.");
                sb.AppendLine(setName);
                sb.AppendLine();
                sb.AppendLine("{");

                foreach (string counter in allCounters[counterSet])
                {
                    EmitCounter(counterSet, counter, ref sb);
                }

                sb.AppendLine("}");
                generated.Add(setName, sb.ToString());
            }

            return generated;
        }
 public override void GenerateClass(StringBuilder b, int pad)
 {
     b.Append(' ', pad); b.AppendLine("public class " + Name);
     b.Append(' ', pad); b.AppendLine("{");
     GenerateFieldsAndFunctions(b, pad + 4);
     b.Append(' ', pad); b.AppendLine("}");
 }
Beispiel #8
0
 public string GetDetails()
 {
     StringBuilder sb = new StringBuilder();
     sb.AppendLine("This demo shows several fixtures,");
     sb.AppendLine("with varying restitution.");
     return sb.ToString();
 }
Beispiel #9
0
 /// <summary>
 /// Load the text to display
 /// </summary>
 protected override string LoadText(ISpyContext settings)
 {
     var sb = new StringBuilder();
     sb.AppendLine("TypeSpec.ID   : " + spec.Id.ToString());
     sb.AppendLine("TypeSpec.Name : " + spec.Name);
     return sb.ToString();
 }
Beispiel #10
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            foreach (PingReply pingReply in PingReplyList)
            {
                if (pingReply != null)
                {
                    switch (pingReply.Status)
                    {
                        case IPStatus.Success:
                            sb.AppendLine(string.Format("Reply from {0}: bytes={1} time={2}ms TTL={3}", pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl));
                            break;
                        case IPStatus.TimedOut:
                            sb.AppendLine("Request timed out.");
                            break;
                        default:
                            sb.AppendLine(string.Format("Ping failed: {0}", pingReply.Status.ToString()));
                            break;
                    }
                }
            }

            if (PingReplyList.Any(x => x.Status == IPStatus.Success))
            {
                sb.AppendLine(string.Format("Minimum = {0}ms, Maximum = {1}ms, Average = {2}ms", Min, Max, Average));
            }

            return sb.ToString().Trim();
        }
Beispiel #11
0
        public static IHtmlString Render(string identifier)
        {
            string shortname = Config.GetValue("disqus/shortname");
            var builder = new StringBuilder();

            if (string.IsNullOrWhiteSpace(identifier))
            {
                builder.AppendLine("<script type=\"text/javascript\">");
                builder.AppendLine(string.Format("var disqus_shortname = '{0}'; ", shortname));
                builder.AppendLine("</script>");
                builder.AppendLine(
                    string.Format("<script type=\"text/javascript\" src=\"//{0}.disqus.com/count.js\"></script>",
                        shortname));
            }
            else
            {
                builder.AppendLine("<script type=\"text/javascript\">");
                builder.AppendLine(string.Format("var disqus_shortname = '{0}'; ", shortname));
                builder.AppendLine(string.Format("var disqus_identifier = '{0}';", identifier));
                builder.AppendLine("</script>");
                builder.AppendLine(
                    string.Format("<script type=\"text/javascript\" src=\"//{0}.disqus.com/embed.js\"></script>",
                        shortname));
                builder.AppendLine(
                    string.Format("<script type=\"text/javascript\" src=\"//{0}.disqus.com/count.js\"></script>",
                        shortname));
            }

            string script = builder.ToString();
            return new NonEncodedHtmlString(script);
        }
Beispiel #12
0
 internal override string Introduce()
 {
     StringBuilder info = new StringBuilder();
     info.AppendLine("Boy: ");
     info.AppendLine(base.Introduce());
     return info.ToString();
 }
        public static string GenerateSrcFiles(string text, List<FileInfo> srcFiles, DirectoryInfo projectPath, string dirPrefix)
        {
            const string begin = "#BEGIN_AUTO_GENERATE_SRC_FILES";
            const string end = "#END_AUTO_GENERATE_SRC_FILES";

            int beginIndex = text.IndexOf(begin) + begin.Length;
            int endIndex = text.IndexOf(end);

            text = text.Remove(beginIndex, endIndex - beginIndex);
            StringBuilder result = new StringBuilder();
            result.AppendLine();
            result.AppendLine(@"LOCAL_SRC_FILES :=\");

            int i = srcFiles.Count;
            foreach (var fileInfo in srcFiles)
            {
                --i;
                string fileName = dirPrefix + fileInfo.FullName.Replace(projectPath.FullName, string.Empty).Remove(0, 1);
                fileName = fileName.Replace('\\', '/');
                if (i!=0)
                {
                    fileName += " \\";
                }

                result.AppendLine(fileName);
            }

            text = text.Insert(beginIndex, result.ToString());
            return text;
        }
Beispiel #14
0
        public override void CreateFiles(string schemaName)
        {
            var objectTypeUpper = ObjectType.ToUpperInvariant();
            var packages = DbContext.DBA_PROCEDURES
                .Where(
                    p =>
                        (schemaName == null || p.OWNER == schemaName) &&
                        (p.OBJECT_TYPE == objectTypeUpper && p.SUBPROGRAM_ID == 0))
                .OrderBy(p => p.OBJECT_TYPE)
                .ThenBy(p => p.OWNER)
                .ThenBy(p => p.OBJECT_NAME)
                .ToList();

            foreach (var package in packages)
            {
                var dbObject = DependencyMatrix.GetDbObject(objectTypeUpper, package.OWNER, package.OBJECT_NAME);

                var fileName = package.OBJECT_NAME.ToLowerInvariant() + SqlFileExtension;
                dbObject.FilePath = FileSystemHelper.GetOutputPath(SubFolderName, package.OWNER) + fileName;

                var sqlStringBuilder = new StringBuilder();

                sqlStringBuilder.AppendLine(new CommonHeaderFragmentCreator(DbContext, fileName,ObjectType,package.OBJECT_NAME).GetSqlString());
                sqlStringBuilder.AppendLine(new DependenciesSqlGenerator(DbContext, package, DependencyMatrix).GetSqlString());
                sqlStringBuilder.AppendLine(new PackageSqlGenerator(DbContext, package).GetSqlString());
                sqlStringBuilder.AppendLine(new CommonFileFooterFragmentCreator(DbContext, fileName).GetSqlString());

                FileSystemHelper.SaveContentToFile(dbObject.FilePath, sqlStringBuilder.ToString());
            }
        }
Beispiel #15
0
 /// <summary>
 /// Appends "Exit after stopping" or "Stopping"
 /// </summary>
 /// <param name="customInfo">The autopilot block's custom info</param>
 public override void AppendCustomInfo(StringBuilder customInfo)
 {
     if (m_exitAfter)
         customInfo.AppendLine("Exit after stopping");
     else
         customInfo.AppendLine("Stopping");
 }
        protected override string CreateInjectingCode(IDictionary<string, string> arguments)
        {
            string filename;
            StringBuilder sb = new StringBuilder();

            //When the Solution first opens, templateFile is null.
            //I wonder if that is a Bug!
            if (this.templateFile != null)
            {
                //Arguments are passed with the Key in lowercase.
                if (!arguments.TryGetValue("filename", out filename))
                    throw new DirectiveProcessorException("Required argument 'FileName' not specified.");

                if (string.IsNullOrEmpty(filename))
                    throw new DirectiveProcessorException("argument 'FileName' is null or empty.");

                string fullPath = Path.Combine(Path.GetDirectoryName(templateFile), filename);

                sb.AppendLine("private VsProjectFile _projectFile;");
                sb.AppendLine("private VsProjectFile ProjectFile");
                sb.AppendLine("{");
                sb.AppendLine("   get");
                sb.AppendLine("   {");
                sb.AppendLine("      if (_projectFile == null)");
                sb.AppendLine("         _projectFile = new VsProjectFile(@\"" + fullPath + "\");");
                sb.AppendLine("      return _projectFile;");
                sb.AppendLine("   }");
                sb.AppendLine("}");
            }

            return sb.ToString();
        }
        /// <summary>
        /// Formats the SQL in a SQL-Server friendly way, with DECLARE statements for the parameters up top.
        /// </summary>
        public string FormatSql(string commandText, List<SqlTimingParameter> parameters, IDbCommand command = null)
        {
            StringBuilder buffer = new StringBuilder();

            if (command != null && IncludeMetaData)
            {
                buffer.AppendLine("-- Command Type: " + command.CommandType);
                buffer.AppendLine("-- Database: " + command.Connection.Database);
                if (command.Transaction != null)
                {
                    buffer.AppendLine("-- Command Transaction Iso Level: " + command.Transaction.IsolationLevel);
                }
				if (Transaction.Current != null)
				{
					// transactions issued by TransactionScope are not bound to the database command but exists globally
					buffer.AppendLine("-- Transaction Scope Iso Level: " + Transaction.Current.IsolationLevel);
				}
                buffer.AppendLine();
            }

	        string baseOutput = base.FormatSql(commandText, parameters, command);

	        buffer.Append(baseOutput);

	        return buffer.ToString();
        }
Beispiel #18
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);
        }
Beispiel #19
0
        /// <summary>
        /// The build html.
        /// </summary>
        private string BuildHtml()
        {
            var text = this.Context.Request.QueryString["q"] != null
                           ? HttpUtility.HtmlEncode(this.Context.Request.QueryString["q"])
                           : BlogSettings.Instance.SearchDefaultText;
            var sb = new StringBuilder();
            sb.AppendLine("<div id=\"searchbox\">");
            sb.Append("<label for=\"searchfield\" style=\"display:none\">Search</label>");
            sb.AppendFormat(
                "<input type=\"text\" value=\"{0}\" id=\"searchfield\" onkeypress=\"if(event.keyCode==13) return BlogEngine.search('{1}')\" onfocus=\"BlogEngine.searchClear('{2}')\" onblur=\"BlogEngine.searchClear('{2}')\" />",
                text,
                Utils.RelativeWebRoot,
                text.Replace("'", "\\'"));
            sb.AppendFormat(
                "<input type=\"button\" value=\"{0}\" id=\"searchbutton\" onclick=\"BlogEngine.search('{1}');\" onkeypress=\"BlogEngine.search('{1}');\" />",
                BlogSettings.Instance.SearchButtonText,
                Utils.RelativeWebRoot);

            if (BlogSettings.Instance.EnableCommentSearch && BlogSettings.Instance.ShowIncludeCommentsOption)
            {
                var check = this.Context.Request.QueryString["comment"] != null ? "checked=\"checked\"" : string.Empty;
                sb.AppendFormat("<div id=\"search-include-comments\"><input type=\"checkbox\" id=\"searchcomments\" {0} />", check);
                if (!string.IsNullOrEmpty(BlogSettings.Instance.SearchCommentLabelText))
                {
                    sb.AppendFormat(
                        "<label for=\"searchcomments\">{0}</label></div>", BlogSettings.Instance.SearchCommentLabelText);
                }
            }

            sb.AppendLine("</div>");
            return sb.ToString();
        }
Beispiel #20
0
        public string Execute()
        {
            const int firstMultiple = 3;
            const int secondMultiple = 5;
            const int multiple = firstMultiple*secondMultiple;

            var resultBuilder = new StringBuilder();
            for (var currentNumber = 1; currentNumber <= 15; currentNumber++)
            {
                if (currentNumber%multiple == 0)
                {
                    resultBuilder.AppendLine("FizzBuzz");
                    continue;
                }

                if (currentNumber%3 == 0)
                {
                    resultBuilder.AppendLine("Fizz");
                    continue;
                }

                if (currentNumber%5 == 0)
                {
                    resultBuilder.AppendLine("Buzz");
                    continue;
                }

                resultBuilder.AppendLine($"{currentNumber}");
            }

            return resultBuilder.ToString();
        }
        public string Dump()
        {
            if (Results.Count == 0)
            {
                return "Overload resolution failed because there were no candidate operators.";
            }

            var sb = new StringBuilder();
            if (this.Best.HasValue)
            {
                sb.AppendLine("Overload resolution succeeded and chose " + this.Best.Signature.ToString());
            }
            else if (CountKind(OperatorAnalysisResultKind.Applicable) > 1)
            {
                sb.AppendLine("Overload resolution failed because of ambiguous possible best operators.");
            }
            else
            {
                sb.AppendLine("Overload resolution failed because no operator was applicable.");
            }

            sb.AppendLine("Detailed results:");
            foreach (var result in Results)
            {
                sb.AppendFormat("operator: {0} reason: {1}\n", result.Signature.ToString(), result.Kind.ToString());
            }

            return sb.ToString();
        }
Beispiel #22
0
    //Create an archive of PackedFile
    public static void CreateArchive(PackedFile[] packedFiles, string outputFile)
    {
        if(packedFiles == null || packedFiles.Length == 0)
        {
            EditorApplication.Beep();
            Debug.LogError("[TCP2 PackFile] No file to pack!");
            return;
        }

        System.Text.StringBuilder sbIndex = new System.Text.StringBuilder();
        System.Text.StringBuilder sbContent = new System.Text.StringBuilder();

        sbIndex.AppendLine("# TCP2 PACKED SHADERS");
        int cursor = 0;
        foreach(PackedFile pf in packedFiles)
        {
            sbContent.Append(pf.content);
            sbIndex.AppendLine( pf.path + ";" + cursor.ToString() + ";" + pf.content.Length );	// PATH ; START ; LENGTH
            cursor += pf.content.Length;
        }

        string archiveContent = sbIndex.ToString() + "###\n" + sbContent.ToString();

        string fullPath = Application.dataPath + "/" + outputFile;
        string directory = Path.GetDirectoryName(fullPath);
        if(!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        File.WriteAllText(fullPath, archiveContent);
        AssetDatabase.Refresh();
        Debug.Log("[TCP2 CreateArchive] Created archive:\n" + fullPath);
    }
Beispiel #23
0
		public static string ToCharacterSeparatedValues(this DataTable table, string delimiter, bool includeHeader)
		{
			var result = new StringBuilder();

			if (includeHeader)
			{
				foreach (DataColumn column in table.Columns)
				{
					result.Append(column.ColumnName);
					result.Append(delimiter);
				}

				result.Remove(result.Length, 0);
				result.AppendLine();
			}

			foreach (DataRow row in table.Rows)
			{
				for (var x = 0; x < table.Columns.Count; x++)
				{
					if (x != 0)
						result.Append(delimiter);

					result.Append(row[table.Columns[x]]);
				}

				result.AppendLine();
			}

			result.Remove(result.Length, 0);
			result.AppendLine();

			return result.ToString();
		}
Beispiel #24
0
 public override string ToString()
 {
     var stringBuilder = new StringBuilder();
     stringBuilder.AppendLine(this.Name);
     stringBuilder.AppendLine(string.Join(", ", this.Ingredients));
     return stringBuilder.ToString();
 }
        protected override void BuildViewResult(StringBuilder viewResult)
        {
            var bookings = this.Model as IEnumerable<Booking>;
            if (!bookings.Any())
            {
                viewResult.AppendLine("There are no bookings for this room.");
            }
            else
            {
                viewResult.AppendLine("Room bookings:");
            }

            foreach (var booking in bookings)
            {
                viewResult.AppendFormat(
                    "* {0:dd.MM.yyyy} - {1:dd.MM.yyyy} (${2:F2})",
                    booking.StartBookDate,
                    booking.EndBookDate,
                    booking.TotalPrice).AppendLine();

                viewResult.AppendFormat(
                    "Total booking price: ${0:F2}",
                    bookings.Sum(b => b.TotalPrice)).AppendLine();
            }
        }
        public override void ToString(StringBuilder builder)
        {
            builder.AppendFormatLine("Items: {0} (displayed: {1})", TotalItemCount, Items.Length);
            builder.AppendLine();

            foreach (var item in Items)
            {
                builder.AppendFormatLine("Auction Id: {0}  Item Entry: {1}", item.AuctionId, item.ItemEntry);

                for (uint i = 0; i < item.Enchantments.Length; ++i)
                {
                    var ench = item.Enchantments[i];
                    if (ench.Id != 0)
                        builder.AppendFormatLine("  Enchantment {0}: {1}", i, ench);
                }

                builder.AppendFormatLine("Property: {0}  RandomSuffix: {1}  Unknown: {2}",
                    item.PropertyId, item.SuffixFactor, item.Unknown);
                builder.AppendFormatLine("Stack Count: {0}  Charges: {1}", item.Count, item.SpellCharges);
                builder.AppendLine("Owner: " + item.Owner);
                builder.AppendFormatLine("Start Bid: {0}  Minimum Bid: {1}  BuyOut: {2}",
                    item.StartBid, item.MinimumBid, item.BuyOut);
                builder.AppendLine("Time Left: " + item.TimeLeftMs);
                builder.AppendFormatLine("Current Bid: {0}  Bidder: {1}", item.CurrentBid, item.CurrentBidder);

                builder.AppendLine();
            }

            builder.AppendLine("Delay: " + NextSearchDelayMs);
        }
Beispiel #27
0
        public static void Send(float ram, float cpu, List<DriveInfo> diskSummary, string subject, List<EventLogEntry> lastLogs)
        {
            MailAddress to = new MailAddress(Properties.Settings.Default.MailTo);
            MailAddress from = new MailAddress(Properties.Settings.Default.MailFrom);
            MailMessage mail = new MailMessage(Properties.Settings.Default.MailFrom, Properties.Settings.Default.MailTo);

            mail.Subject = subject;
            StringBuilder builder = new StringBuilder();
            builder.Append("Your CPU Usage: " +cpu+ "\n\nYour RAM Usage: " +ram+ "\n\n");

            foreach (DriveInfo disksToWrite in diskSummary)
            {
                builder.AppendLine(string.Format("{0} {1} GB Free Space of {2} GB Total Size;\n", disksToWrite.Name, ByteConverter.GetGigaBytesFromBytes(disksToWrite.TotalFreeSpace), ByteConverter.GetGigaBytesFromBytes(disksToWrite.TotalSize)));
            }

            foreach (EventLogEntry logsToWrite in lastLogs)
            {
                builder.AppendLine(string.Format("{0}; Event ID: {1}; {2}; {3};", logsToWrite.TimeGenerated, logsToWrite.InstanceId, logsToWrite.EntryType,
                                             logsToWrite.Message));
            }
            builder.AppendLine("\n\n" + subject);
            mail.Body = builder.ToString();
            SmtpClient smtp = new SmtpClient();
            smtp.Host = Properties.Settings.Default.MailSmtpServer;
            smtp.Port = Properties.Settings.Default.MailSmtpPort;

            smtp.Credentials = new NetworkCredential(
                Properties.Settings.Default.MailFrom, Properties.Settings.Default.MailPassword);
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
        internal static void AssertValid(this DbDatabaseMapping databaseMapping, bool shouldThrow)
        {
            var storageItemMappingCollection = databaseMapping.ToStorageMappingItemCollection();

            var errors = new List<EdmSchemaError>();
            storageItemMappingCollection.GenerateViews(errors);

            if (errors.Any())
            {
                var errorMessage = new StringBuilder();
                errorMessage.AppendLine();

                foreach (var error in errors)
                {
                    errorMessage.AppendLine(error.ToString());
                }

                if (shouldThrow)
                {
                    throw new MappingException(errorMessage.ToString());
                }

                Assert.True(false, errorMessage.ToString());
            }
        }
 public string GetUsage()
 {
     var usage = new StringBuilder();
     usage.AppendLine("HostCommander v0.1");
     usage.AppendLine("Usage:  HostCommander -m mode -h host -i ip");
     return usage.ToString();
 }
 public override string GetInfo()
 {
     var builder = new StringBuilder();
       builder.AppendLine("Auto balancing landing Leg");
       builder.AppendLine("By KerboKatz");
       return builder.ToString();
 }
Beispiel #31
0
        public static string DaubleTableToString(this double[] d)
        {
            var sb = new Text.StringBuilder();

            foreach (var r in d)
            {
                sb.AppendFormat("El: {0}", r);
                sb.AppendLine();
            }
            return(sb.ToString());
        }
Beispiel #32
0
 /// <summary>
 /// 返回异常所有信息
 /// </summary>
 /// <param name="webHuanHang">是否为web换行</param>
 /// <param name="style">样式: color:red;  </param>
 /// <returns></returns>
 public string GetAllExceptionMessage(bool webHuanHang = false, string style = "")
 {
     System.Text.StringBuilder message = new Text.StringBuilder("");
     if (_HasException)
     {
         int index = 0;
         _ExceptionCollection.Reverse().Distinct().ToList().ForEach(x => {
             if (webHuanHang)
             {
                 message.AppendFormat(@"<p style='{2}'>【{0}】:{1}</p>", index, x.Message, style);
             }
             else
             {
                 message.AppendLine(x.Message);
             }
             index++;
         });
     }
     return(message.ToString());
 }
Beispiel #33
0
        /// <summary>
        /// 返回异常所有信息
        /// </summary>
        /// <param name="webHuanHang">是否为web换行</param>
        /// <param name="style">样式: color:red;  </param>
        /// <returns></returns>
        public static string GetAllExceptionMessage(this Exception ex, bool webHuanHang = false, string style = "")
        {
            var exceptionList = new List <Exception>();

            bool hasInnerException = false;
            var  tmpException      = ex;

            if (ex != null)
            {
                exceptionList.Add(tmpException);
                hasInnerException = tmpException.InnerException != null;
            }
            while (hasInnerException)
            {
                tmpException = tmpException.InnerException;
                exceptionList.Add(tmpException);
                hasInnerException = tmpException.InnerException != null;
            }

            StringBuilder message = new Text.StringBuilder("");
            int           index   = 0;

            exceptionList.Reverse();
            exceptionList.Distinct().ToList().ForEach(x =>
            {
                if (webHuanHang)
                {
                    message.AppendFormat(@"<p style='{2}'>【{0}】:{1}</p>", index, x.Message, style);
                }
                else
                {
                    message.AppendLine(x.Message);
                }
                index++;
            });
            return(message.ToString());
        }
Beispiel #34
0
        public void CreateTable(SQLiteTable table)
        {
            StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("create table if not exists `");
            sb.Append(table.TableName);
            sb.AppendLine("`(");

            bool firstRecord = true;

            foreach (SQLiteColumn col in table.Columns)
            {
                if (col.ColumnName.Trim().Length == 0)
                {
                    throw new Exception("Column name cannot be blank.");
                }

                if (firstRecord)
                {
                    firstRecord = false;
                }
                else
                {
                    sb.AppendLine(",");
                }

                sb.Append(col.ColumnName);
                sb.Append(" ");

                if (col.AutoIncrement)
                {
                    sb.Append("integer primary key autoincrement");
                    continue;
                }

                switch (col.ColDataType)
                {
                case ColType.Text:
                    sb.Append("text"); break;

                case ColType.Integer:
                    sb.Append("integer"); break;

                case ColType.Decimal:
                    sb.Append("decimal"); break;

                case ColType.DateTime:
                    sb.Append("datetime"); break;

                case ColType.BLOB:
                    sb.Append("blob"); break;
                }

                if (col.PrimaryKey)
                {
                    sb.Append(" primary key");
                }
                else if (col.NotNull)
                {
                    sb.Append(" not null");
                }
                else if (col.DefaultValue.Length > 0)
                {
                    sb.Append(" default ");

                    if (col.DefaultValue.Contains(" ") || col.ColDataType == ColType.Text || col.ColDataType == ColType.DateTime)
                    {
                        sb.Append("'");
                        sb.Append(col.DefaultValue);
                        sb.Append("'");
                    }
                    else
                    {
                        sb.Append(col.DefaultValue);
                    }
                }
            }

            sb.AppendLine(");");

            _cmd.CommandText = sb.ToString();
            _cmd.ExecuteNonQuery();
        }
Beispiel #35
0
        private void btnProductGoods_Click(object sender, System.EventArgs e)
        {
            string text = "";

            if (!string.IsNullOrEmpty(base.Request["CheckBoxGroup"]))
            {
                text = base.Request["CheckBoxGroup"];
            }
            if (text.Length <= 0)
            {
                this.ShowMsg("请选要下载配货表的订单", false);
                return;
            }
            System.Collections.Generic.List <string> list = new System.Collections.Generic.List <string>();
            string[] array = text.Split(new char[]
            {
                ','
            });
            for (int i = 0; i < array.Length; i++)
            {
                string str = array[i];
                list.Add("'" + str + "'");
            }
            System.Data.DataSet       productGoods  = OrderHelper.GetProductGoods(string.Join(",", list.ToArray()));
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            stringBuilder.AppendLine("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=gb2312\"></head><body>");
            stringBuilder.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
            stringBuilder.AppendLine("<caption style='text-align:center;'>配货单(仓库拣货表)</caption>");
            stringBuilder.AppendLine("<tr style=\"font-weight: bold; white-space: nowrap;\">");
            stringBuilder.AppendLine("<td>商品名称</td>");
            stringBuilder.AppendLine("<td>货号</td>");
            stringBuilder.AppendLine("<td>规格</td>");
            stringBuilder.AppendLine("<td>拣货数量</td>");
            stringBuilder.AppendLine("<td>现库存数</td>");
            stringBuilder.AppendLine("</tr>");
            foreach (System.Data.DataRow dataRow in productGoods.Tables[0].Rows)
            {
                stringBuilder.AppendLine("<tr>");
                stringBuilder.AppendLine("<td>" + dataRow["ProductName"] + "</td>");
                stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat:@\">" + dataRow["SKU"] + "</td>");
                stringBuilder.AppendLine("<td>" + dataRow["SKUContent"] + "</td>");
                stringBuilder.AppendLine("<td>" + dataRow["ShipmentQuantity"] + "</td>");
                stringBuilder.AppendLine("<td>" + dataRow["Stock"] + "</td>");
                stringBuilder.AppendLine("</tr>");
            }
            stringBuilder.AppendLine("</table>");
            stringBuilder.AppendLine("</body></html>");
            base.Response.Clear();
            base.Response.Buffer  = false;
            base.Response.Charset = "GB2312";
            base.Response.AppendHeader("Content-Disposition", "attachment;filename=productgoods_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
            base.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            base.Response.ContentType     = "application/ms-excel";
            this.EnableViewState          = false;
            base.Response.Write(stringBuilder.ToString());
            base.Response.End();
        }
Beispiel #36
0
        public static void Write(string file, string section, string key, string value, string comment)
        {
            bool isModified = false;

            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            string content = GetText(file);

            System.Text.StringBuilder newValueContent = new System.Text.StringBuilder();
            #region 写入了节点
            if (!string.IsNullOrEmpty(section))
            {
                string          pattern = string.Format(@"\[\s*{0}\s*\](?'valueContent'[^\[\]]*)", section);
                MatchCollection matches = new Regex(pattern).Matches(content);
                if (matches.Count <= 0)
                {
                    stringBuilder.AppendLine(string.Format("[{0}]", section)); //检查节点是否存在
                    stringBuilder.AppendLine(string.Format("{0}={1}{2}", key, value, !string.IsNullOrEmpty(comment) ? (";" + comment) : ""));
                    stringBuilder.AppendLine(content);
                    isModified = true;
                }
                else
                {
                    Match    match        = matches[0];
                    string   valueContent = match.Groups["valueContent"].Value;
                    string[] lines        = valueContent.Split(new string[] { "\r\n" }, System.StringSplitOptions.None);

                    newValueContent.AppendLine(string.Format("[{0}]", section));
                    foreach (string line in lines)
                    {
                        if (string.IsNullOrEmpty(line) || line == "\r\n" || line.Contains("["))
                        {
                            continue;
                        }

                        string valueLine = line;
                        string comments  = "";
                        if (line.Contains(";"))
                        {
                            string[] seqPairs = line.Split(';');
                            if (seqPairs.Length > 1)
                            {
                                comments = seqPairs[1].Trim();
                            }
                            valueLine = seqPairs[0];
                        }
                        string[] keyValuePairs = valueLine.Split('=');
                        string   line_key      = keyValuePairs[0];
                        string   line_value    = "";
                        if (keyValuePairs.Length > 1)
                        {
                            line_value = keyValuePairs[1];
                        }
                        if (key.ToLower().Trim() == line_key.ToLower().Trim())
                        {
                            isModified = true;
                            newValueContent.AppendLine(string.Format("{0}={1}{2}", key, value, !string.IsNullOrEmpty(comment) ? (";" + comment) : ""));
                        }
                        else
                        {
                            newValueContent.AppendLine(line);
                        }
                    }
                    if (!isModified)
                    {
                        newValueContent.AppendLine(string.Format("{0}={1}{2}", key, value, !string.IsNullOrEmpty(comment) ? (";" + comment) : ""));
                    }
                    string newVal = newValueContent.ToString();
                    content = content.Replace(match.Value, newVal);
                    stringBuilder.Append(content);
                }
            }
            #endregion
            #region 没有指明节点
            else
            {
                string valueText = "";
                //如果节点为空
                MatchCollection matches = new Regex(@"\[\s*(?'section'[^\[\]\s]+)\s*\](?'valueContent'[^\[\]]*)").Matches(content);
                if (matches.Count > 0)
                {
                    valueText = matches[0].Index > 0 ? content.Substring(0, matches[0].Index) : "";
                    string[] lines = valueText.Split(new string[] { "\r\n" }, System.StringSplitOptions.None);
                    foreach (string line in lines)
                    {
                        if (string.IsNullOrEmpty(line) || line == "\r\n" || line.Contains("["))
                        {
                            continue;
                        }

                        string valueLine = line;
                        string comments  = "";
                        if (line.Contains(";"))
                        {
                            string[] seqPairs = line.Split(';');
                            if (seqPairs.Length > 1)
                            {
                                comments = seqPairs[1].Trim();
                            }
                            valueLine = seqPairs[0];
                        }
                        string[] keyValuePairs = valueLine.Split('=');
                        string   line_key      = keyValuePairs[0];
                        string   line_value    = "";
                        if (keyValuePairs.Length > 1)
                        {
                            line_value = keyValuePairs[1];
                        }
                        if (key.ToLower().Trim() == line_key.ToLower().Trim())
                        {
                            isModified = true;
                            newValueContent.AppendLine(string.Format("{0}={1}{2}", key, value, !string.IsNullOrEmpty(comment) ? (";" + comment) : ""));
                        }
                        else
                        {
                            newValueContent.AppendLine(line);
                        }
                    }
                    if (!isModified)
                    {
                        newValueContent.AppendLine(string.Format("{0}={1}{2}", key, value, !string.IsNullOrEmpty(comment) ? (";" + comment) : ""));
                    }
                    string newVal = newValueContent.ToString();
                    content = content.Replace(valueText, newVal);
                    stringBuilder.Append(content);
                }
                else
                {
                    stringBuilder.AppendLine(string.Format("{0}={1}{2}", key, value, !string.IsNullOrEmpty(comment) ? (";" + comment) : ""));
                }
            }
            #endregion
            System.IO.File.WriteAllText(file, stringBuilder.ToString(), Encoding);
        }
        private void GetClipboardData()
        {
            if (blnFirstTimeThrough)
            {
                blnFirstTimeThrough = false;
                return;
            }
            //
            // Data on the clipboard uses the
            // IDataObject interface
            //
            strClipboardText = "";
            string      sText;
            IDataObject iData   = new DataObject();
            string      strText = "clipmon";
            IntPtr      hData;

            try
            {
                iData = Clipboard.GetDataObject();

                //if ( ((string)iData.GetData(DataFormats.Text)).StartsWith("?")  )
                //{
                //    if (iData.GetDataPresent(DataFormats.UnicodeText))
                //    {
                //        //ctlClipboardText.Rtf = (string)iData.GetData(DataFormats.Rtf);
                //        string ss = (string)iData.GetData(DataFormats.UnicodeText);

                //    }


                //    //hData = GetClipboardData(CF_UNICODETEXT);
                //    //if (hData.ToInt32() == 0)
                //    //{
                //    //    return;
                //    //}

                //    //sText = ConvertToString(hData);
                //}

                //Clipboard.GetDataObject();
            }
            catch (System.Runtime.InteropServices.ExternalException externEx)
            {
                // Copying a field definition in Access 2002 causes this sometimes?
                Debug.WriteLine("InteropServices.ExternalException: {0}", externEx.Message);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }

            //
            // Get RTF if it is present
            //
            if (iData.GetDataPresent(DataFormats.Text))
            {
                //ctlClipboardText.Rtf = (string)iData.GetData(DataFormats.Rtf);

                //if(iData.GetDataPresent(DataFormats.Text))
                //{
                //    strText = "RTF";
                //}
            }
            else
            {
                //
                // Get Text if it is present
                //
                if (iData.GetDataPresent(DataFormats.UnicodeText))
                {
                    //ctlClipboardText.Text = (string)iData.GetData(DataFormats.Text);

                    //strText = "Text";

                    //Debug.WriteLine((string)iData.GetData(DataFormats.Text));
                }
                else
                {
                    //
                    // Only show RTF or TEXT
                    //
                    txtTrans.Text = "(cannot display this format)";
                    return;
                }
            }

            //   notAreaIcon.Tooltip = strText;

            if (ClipboardSearch(iData))
            {
                //
                // New word go look up.
                //
                System.Text.StringBuilder strBalloon = new System.Text.StringBuilder(100);

                //foreach (string objLink in _lookup)
                //{
                //    strBalloon.Append(objLink.ToString()  + "\n");
                //}

                //    WordDef wd = (WordDef)_lookup.Dequeue();

                WordDef wd = (WordDef)wdColl.Current;

                string t = wd.Tibetan;
                strBalloon.Append(wd.Wylie);
                strBalloon.Append(" - ");
                strBalloon.AppendLine(wd.Trans);
                wd = null;
                //FormatMenuBuild(iData);
                //SupportedMenuBuild(iData);
                //ContextMenuBuild();

                //if (_lookup.Count > 0)
                //{
                txtTibetan.Text = t;
                txtTrans.Text   = strBalloon.ToString();
                //   notAreaIcon.BalloonDisplay(NotificationAreaIcon.NOTIFYICONdwInfoFlags.NIIF_INFO, "Links", strBalloon.ToString());
                //}
            }
            else
            {
                txtTibetan.Text = strClipboardText;
                txtTrans.Text   = "Not Found";
            }
        }
        public void Parse_gfx_should_yield_results()
        {
            DISetup.SetupContainer();

            var sb = new StringBuilder();

            sb.AppendLine(@"bitmapfonts = {");
            sb.AppendLine(@"");
            sb.AppendLine(@"	### ship size icons ###");
            sb.AppendLine(@"");
            sb.AppendLine(@"	bitmapfont = {");
            sb.AppendLine(@"		name = ""GFX_text_military_size_1""");
            sb.AppendLine(@"		texturefile = ""gfx/interface/icons/text_icons/icon_text_military_size_1.dds""");
            sb.AppendLine(@"	}");
            sb.AppendLine(@"	");
            sb.AppendLine(@"	bitmapfont = {");
            sb.AppendLine(@"		name = ""GFX_text_military_size_2""");
            sb.AppendLine(@"		texturefile = ""gfx/interface/icons/text_icons/icon_text_military_size_2.dds""");
            sb.AppendLine(@"	}");
            sb.AppendLine(@"}");


            var sb2 = new StringBuilder();

            sb2.AppendLine(@"bitmapfonts = {");
            sb2.AppendLine(@"	bitmapfont = {");
            sb2.AppendLine(@"		name = ""GFX_text_military_size_1""");
            sb2.AppendLine(@"		texturefile = ""gfx/interface/icons/text_icons/icon_text_military_size_1.dds""");
            sb2.AppendLine(@"	}");
            sb2.AppendLine(@"}");


            var sb3 = new System.Text.StringBuilder();

            sb3.AppendLine(@"bitmapfonts = {");
            sb3.AppendLine(@"	bitmapfont = {");
            sb3.AppendLine(@"		name = ""GFX_text_military_size_2""");
            sb3.AppendLine(@"		texturefile = ""gfx/interface/icons/text_icons/icon_text_military_size_2.dds""");
            sb3.AppendLine(@"	}");
            sb3.AppendLine(@"}");


            var args = new ParserArgs()
            {
                ContentSHA      = "sha",
                ModDependencies = new List <string> {
                    "1"
                },
                File    = "gfx\\gfx.gfx",
                Lines   = sb.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries),
                ModName = "fake"
            };
            var parser = new GraphicsParser(new CodeParser(new Logger()), null);
            var result = parser.Parse(args).ToList();

            result.Should().NotBeNullOrEmpty();
            result.Count().Should().Be(2);
            for (int i = 0; i < 2; i++)
            {
                result[i].ContentSHA.Should().Be("sha");
                result[i].Dependencies.First().Should().Be("1");
                result[i].File.Should().Be("gfx\\gfx.gfx");
                switch (i)
                {
                case 0:
                    result[i].Id.Should().Be("GFX_text_military_size_1");
                    result[i].Code.Should().Be(sb2.ToString().Trim().ReplaceTabs());
                    result[i].ValueType.Should().Be(Common.ValueType.Object);
                    break;

                case 1:
                    result[i].Id.Should().Be("GFX_text_military_size_2");
                    result[i].Code.Should().Be(sb3.ToString().Trim().ReplaceTabs());
                    result[i].ValueType.Should().Be(Common.ValueType.Object);
                    break;

                default:
                    break;
                }
                result[i].ModName.Should().Be("fake");
                result[i].Type.Should().Be("gfx\\gfx");
            }
        }
Beispiel #39
0
        public void Arg()
        {
            var file = System.IO.File.ReadAllLines(@"C:\Users\root\Documents\Downloads\A-large.in");

//            var file2 = @"3
//11001001
//cats
//zig";
//            var file = file2.Replace("\r", "").Split('\n');

            int line  = 0;
            int cases = int.Parse(file[line++]);

            var sb = new System.Text.StringBuilder();

            for (int c = 1; c <= cases; c++)
            {
                var ln     = file[line++];
                var ch     = ln.ToCharArray();
                var distCh = ch.Distinct().ToArray();

                int realNum = distCh.Length;
                int baseNum = Math.Max(distCh.Length, 2);

                Dictionary <char, int> lookup = new Dictionary <char, int>();
                lookup.Add(ch[0], 1);

                if (realNum == 1)
                {
                }
                else
                {
                    int num = 0;
                    for (int i = 1; i < ch.Length; i++)
                    {
                        char cc = ch[i];
                        if (!lookup.ContainsKey(cc))
                        {
                            lookup.Add(cc, num);
                            num++;
                        }
                        if (num == 1)
                        {
                            num = 2;
                        }
                    }
                }

                long rtn = 0;
                for (int i = 0; i < ch.Length; i++)
                {
                    long val     = lookup[ch[i]];
                    long newBase = baseNum;
                    rtn *= newBase;
                    rtn += val;
                }

                sb.AppendFormat("Case #{0}: {1}", c, rtn.ToString());
                sb.AppendLine();
            }

            System.IO.File.WriteAllText(@"C:\Pub\a2.txt", sb.ToString());
        }
Beispiel #40
0
        /// <summary>
        /// 信息询问
        /// </summary>
        /// <param name="msg">信息内容</param>
        /// <param name="urla">确定后跳页面</param>
        /// <param name="urlb">取消后跳页面</param>
        /// <param name="target">页面跳转框架</param>
        protected static void JboxShowConfirm(string msg, string urla, string urlb, string target)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            sb.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>");

            sb.AppendLine(str_jboxres);

            sb.AppendLine("<script type=\"text/javascript\">");

            sb.AppendLine("var fun_submit = function (v, h, f) {");
            if (urla != "")
            {
                sb.AppendLine("" + target + ".location.href='" + urla + "';");
            }
            sb.AppendLine("return true;");
            sb.AppendLine("};");

            sb.AppendLine("var fun_cancel = function () {");
            if (urlb != "")
            {
                sb.AppendLine("" + target + ".location.href='" + urlb + "';");
            }
            sb.AppendLine("return true;");
            sb.AppendLine("};");

            sb.AppendLine("function jboxMsg(msg) {");
            sb.AppendLine("     $.jBox.confirm(msg , \"信息提示\", { submit : fun_submit ,cancel : fun_cancel , top: '30%' });");
            sb.AppendLine("}");
            sb.AppendLine("</script>");

            sb.AppendLine("<script language='javascript'>$(document).ready(function () {jboxMsg('" + msg + "');});</script>");

            sb.AppendLine("</head><body>");
            sb.AppendLine("</body></html>");

            System.Web.HttpContext.Current.Response.Write(sb.ToString());
            System.Web.HttpContext.Current.Response.End();
        }
Beispiel #41
0
        protected void btnExportButton_Click(object sender, System.EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["ActitivyTitle"]))
            {
                this.ActitivyTitle = this.Page.Request.QueryString["ActitivyTitle"];
            }
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["AddrReggion"]))
            {
                this.AddrReggion = base.Server.UrlDecode(this.Page.Request.QueryString["AddrReggion"]);
                this.SelReggion.SetSelectedRegionId(new int?(int.Parse(this.AddrReggion)));
            }
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["ShowTabNum"]))
            {
                this.ShowTabNum = base.Server.UrlDecode(this.Page.Request.QueryString["ShowTabNum"]);
            }
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["Receiver"]))
            {
                this.Receiver = base.Server.UrlDecode(this.Page.Request.QueryString["Receiver"]);
            }
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["ProductName"]))
            {
                this.ProductName = base.Server.UrlDecode(this.Page.Request.QueryString["ProductName"]);
            }
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["StartDate"]))
            {
                this.StartDate = base.Server.UrlDecode(this.Page.Request.QueryString["StartDate"]);
                this.calendarStartDate.SelectedDate = new System.DateTime?(System.DateTime.Parse(this.StartDate));
            }
            else
            {
                this.StartDate = "";
            }
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["EndDate"]))
            {
                this.EndDate = base.Server.UrlDecode(this.Page.Request.QueryString["EndDate"]);
                this.calendarEndDate.SelectedDate = new System.DateTime?(System.DateTime.Parse(this.EndDate));
            }
            else
            {
                this.EndDate = "";
            }
            PrizesDeliveQuery prizesDeliveQuery = new PrizesDeliveQuery();

            prizesDeliveQuery.Status        = int.Parse(this.ShowTabNum) - 1;
            prizesDeliveQuery.StartDate     = this.StartDate;
            prizesDeliveQuery.EndDate       = this.EndDate;
            prizesDeliveQuery.SortBy        = "WinTime";
            prizesDeliveQuery.PrizeType     = 2;
            prizesDeliveQuery.SortOrder     = SortAction.Desc;
            prizesDeliveQuery.PageIndex     = this.pager.PageIndex;
            prizesDeliveQuery.PageSize      = this.pager.PageSize;
            prizesDeliveQuery.ProductName   = this.ProductName;
            prizesDeliveQuery.Receiver      = this.Receiver;
            prizesDeliveQuery.ReggionId     = this.AddrReggion;
            prizesDeliveQuery.ActivityTitle = this.ActitivyTitle;
            Globals.EntityCoding(prizesDeliveQuery, true);
            DbQueryResult allPrizesDeliveryList = GameHelper.GetAllPrizesDeliveryList(prizesDeliveQuery, "", "*");

            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            stringBuilder.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
            stringBuilder.AppendLine("<tr style=\"font-weight: bold; white-space: nowrap;\">");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >活动名称</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >商品名称</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >奖品等级</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >中奖时间</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >收货人</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >联系电话</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >详细地址</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >快递公司</td>");
            stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >快递编号</td>");
            stringBuilder.AppendLine("</tr>");
            System.Data.DataTable dataTable = (System.Data.DataTable)allPrizesDeliveryList.Data;
            string text  = string.Empty;
            string text2 = string.Empty;

            new System.Collections.Generic.List <int>();
            if (!string.IsNullOrEmpty(this.hidLogId.Value) || !string.IsNullOrEmpty(this.hidPid.Value))
            {
                text  = this.hidLogId.Value;
                text2 = this.hidPid.Value;
                string[] collection = text.Split(new char[]
                {
                    ','
                });
                string[] collection2 = text2.Split(new char[]
                {
                    ','
                });
                System.Collections.Generic.List <string> list  = new System.Collections.Generic.List <string>(collection);
                System.Collections.Generic.List <string> list2 = new System.Collections.Generic.List <string>(collection2);
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    string item  = dataTable.Rows[i]["LogId"].ToString();
                    string item2 = dataTable.Rows[i]["Pid"].ToString();
                    if (list.Contains(item) || list2.Contains(item2))
                    {
                        stringBuilder.AppendLine("<tr>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["Title"] + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["ProductName"] + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + GameHelper.GetPrizeGradeName(dataTable.Rows[i]["PrizeGrade"].ToString()) + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["WinTime"] + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["Receiver"] + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["Tel"] + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["Address"] + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["ExpressName"] + "</td>");
                        stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[i]["CourierNumber"] + "</td>");
                        stringBuilder.AppendLine("</tr>");
                    }
                }
            }
            else
            {
                for (int j = 0; j < dataTable.Rows.Count; j++)
                {
                    dataTable.Rows[j]["LogId"].ToString();
                    stringBuilder.AppendLine("<tr>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["Title"] + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["ProductName"] + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + GameHelper.GetPrizeGradeName(dataTable.Rows[j]["PrizeGrade"].ToString()) + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["WinTime"] + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["Receiver"] + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["Tel"] + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["Address"] + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["ExpressName"] + "</td>");
                    stringBuilder.AppendLine("<td style=\"vnd.ms-excel.numberformat: @;\" >" + dataTable.Rows[j]["CourierNumber"] + "</td>");
                    stringBuilder.AppendLine("</tr>");
                }
            }
            if (dataTable.Rows.Count == 0)
            {
                stringBuilder.AppendLine("<tr><td></td></tr>");
            }
            stringBuilder.AppendLine("</table>");
            this.Page.Response.Clear();
            this.Page.Response.Buffer  = false;
            this.Page.Response.Charset = "UTF-8";
            this.Page.Response.AppendHeader("Content-Disposition", "attachment;filename=PrizeLists_" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
            this.Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            this.Page.Response.ContentType     = "application/ms-excel";
            this.Page.EnableViewState          = false;
            this.Page.Response.Write(stringBuilder.ToString());
            this.Page.Response.End();
        }
Beispiel #42
0
 public virtual void BuildTreeString(System.Text.StringBuilder builder, int indentLevel)
 {
     builder.Append(' ', indentLevel * 2);
     builder.AppendFormat(ToString());
     builder.AppendLine();
 }
Beispiel #43
0
        public static bool DoCommandLine(string[] args)
        {
            if (args.Length <= 1)
            {
                return(true);
            }

            patchList.Clear();
            System.Text.StringBuilder errorOutput = new System.Text.StringBuilder();
            errorOutput.AppendLine("-- ERROR LOG --");

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].Equals(CMD_HELP, StringComparison.OrdinalIgnoreCase))
                {
                    bHelp = true;
                    break;
                }
                else if ((!bEnablelog) && args[i].Equals(CMD_LOG, StringComparison.OrdinalIgnoreCase))
                {
                    bEnablelog = true;
                }
                else if ((!bInputfile) && args[i].Equals(CMD_INPUT, StringComparison.OrdinalIgnoreCase))
                {
                    if ((i + 1) < args.Length)
                    {
                        sInputpath = args[i + 1];
                        sInputpath = sInputpath.Trim();

                        if (sInputpath.Length > 0)
                        {
                            bInputfile = true;
                        }
                    }
                    else
                    {
                        errorOutput.AppendLine(CMD_INPUT + " switch without argument");
                    }
                }
                else if ((!bOutputfile) && args[i].Equals(CMD_OUTPUT, StringComparison.OrdinalIgnoreCase))
                {
                    if ((i + 1) < args.Length)
                    {
                        sOutputpath = args[i + 1];
                        sOutputpath = sOutputpath.Trim();

                        if (sOutputpath.Length > 0)
                        {
                            bOutputfile = true;
                        }
                    }
                    else
                    {
                        errorOutput.AppendLine(CMD_OUTPUT + " switch without argument");
                    }
                }
                else if ((!bUnpack) && args[i].Equals(CMD_UNPACK, StringComparison.OrdinalIgnoreCase))
                {
                    bUnpack = true;
                }
                else if ((!bDontfix) && args[i].Equals(CMD_DONTFIX, StringComparison.OrdinalIgnoreCase))
                {
                    bDontfix = true;
                }
                else if (args[i].Equals(CMD_PATCH, StringComparison.OrdinalIgnoreCase))
                {
                    if ((i + 1) < args.Length)
                    {
                        try
                        {
                            string[]   patchParams = args[i + 1].Split(new char[] { ',' }, 4);
                            PatchFiles pfTemp      = new PatchFiles();
                            pfTemp.file     = patchParams[0];
                            pfTemp.index    = Int32.Parse(patchParams[1]);
                            pfTemp.subindex = Int32.Parse(patchParams[2]);
                            pfTemp.compress = Int32.Parse(patchParams[3]);
                            patchList.Push(pfTemp);
                            bPatch = true;
                        }
                        catch
                        {
                            errorOutput.AppendLine(CMD_PATCH + " switch with incorrect argument (\"" + args[i + 1] + "\")");
                        }
                    }
                    else
                    {
                        errorOutput.AppendLine(CMD_PATCH + " switch without argument");
                    }
                }
                else if ((!bFullpatch) && args[i].Equals(CMD_FULLPATCH, StringComparison.OrdinalIgnoreCase))
                {
                    if ((i + 1) < args.Length)
                    {
                        sFullpatchPath = args[i + 1];
                        sFullpatchPath = sFullpatchPath.Trim();

                        if (sFullpatchPath.Length > 0)
                        {
                            bFullpatch = true;
                        }
                    }
                    else
                    {
                        errorOutput.AppendLine(CMD_FULLPATCH + " switch without argument");
                    }
                }
            }

            if (bHelp)
            {
                MessageBox.Show(MESSAGEBOX_HELP, "UO:KR Uop Dumper - Patch Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (bInputfile)
            {
                if (UopManager.getIstance().Load(sInputpath))
                {
                    if (bUnpack)
                    {
                        string thePath = Application.StartupPath + StaticData.UNPACK_DIR;;
                        if (!Directory.Exists(thePath))
                        {
                            Directory.CreateDirectory(thePath);
                        }

                        if (!UopManager.getIstance().UnPack(thePath))
                        {
                            errorOutput.AppendLine("Error while unpacking the uop file to (\"" + thePath + "\")");
                        }
                    }
                    else if (bFullpatch)
                    {
                        UopManager.UopPatchError upeError = UopManager.UopPatchError.Okay;

                        if (Directory.Exists(sFullpatchPath))
                        {
                            try
                            {
                                string   uopName    = Path.GetFileNameWithoutExtension(UopManager.getIstance().UopPath);
                                string[] filesFound = Directory.GetFiles(sFullpatchPath, uopName + "*.*", SearchOption.TopDirectoryOnly);
                                foreach (string currentFile in filesFound)
                                {
                                    string strippedName = Path.GetFileName(currentFile);
                                    if (!strippedName.StartsWith(uopName + "-", StringComparison.OrdinalIgnoreCase))
                                    {
                                        errorOutput.AppendLine("Error while patching \"" + strippedName + "\".");
                                        continue;
                                    }

                                    string parseName = strippedName.Substring(uopName.Length + 1);
                                    if (parseName.IndexOf('_') == -1)
                                    {
                                        errorOutput.AppendLine("Error while patching \"" + strippedName + "\".");
                                        continue;
                                    }

                                    int indexA = -1, indexB = -1;
                                    if (!Int32.TryParse(parseName.Substring(0, parseName.IndexOf('_')), out indexA))
                                    {
                                        errorOutput.AppendLine("Error while patching \"" + strippedName + "\".");
                                        continue;
                                    }

                                    parseName = parseName.Substring(parseName.IndexOf('_') + 1);
                                    if (!Int32.TryParse(parseName.Substring(0, parseName.IndexOf('.')), out indexB))
                                    {
                                        errorOutput.AppendLine("Error while patching \"" + strippedName + "\".");
                                        continue;
                                    }

                                    if ((indexA == -1) || (indexB == -1))
                                    {
                                        errorOutput.AppendLine("Error while patching \"" + strippedName + "\".");
                                        continue;
                                    }

                                    if (parseName.EndsWith("." + StaticData.UNPACK_EXT_COMP))
                                    {
                                        upeError = UopManager.getIstance().Replace(currentFile, indexA, indexB, false);
                                    }
                                    else if (parseName.EndsWith("." + StaticData.UNPACK_EXT_UCOMP))
                                    {
                                        upeError = UopManager.getIstance().Replace(currentFile, indexA, indexB, true);
                                    }
                                    else
                                    {
                                        errorOutput.AppendLine("Error while patching \"" + strippedName + "\".");
                                        continue;
                                    }

                                    if (upeError != UopManager.UopPatchError.Okay)
                                    {
                                        errorOutput.AppendLine("Error while patching \"" + strippedName + "\" (" + upeError.ToString() + ").");
                                        continue;
                                    }
                                }

                                if (!bOutputfile)
                                {
                                    sOutputpath = Utility.GetPathForSave(UopManager.getIstance().UopPath);
                                }

                                if (!bDontfix)
                                {
                                    UopManager.getIstance().FixOffsets(0, 0);
                                }

                                if (!UopManager.getIstance().Write(sOutputpath))
                                {
                                    errorOutput.AppendLine("Error while writing the new uop file (\"" + sOutputpath + "\")");
                                }
                            }
                            catch
                            {
                                errorOutput.AppendLine("Error while full-patching \"" + UopManager.getIstance().UopPath + "\" from \"" + sFullpatchPath + "\".");
                            }
                        }
                        else
                        {
                            errorOutput.AppendLine("Error while opening non-accessible directory \"" + sFullpatchPath + "\"");
                        }
                    }
                    else if (bPatch)
                    {
                        UopManager.UopPatchError upeError = UopManager.UopPatchError.Okay;
                        int iMinIndex = Int32.MaxValue, iMinSubindex = Int32.MaxValue;

                        foreach (PatchFiles pfCurrent in patchList)
                        {
                            iMinIndex    = Math.Min(iMinIndex, pfCurrent.index);
                            iMinSubindex = Math.Min(iMinSubindex, pfCurrent.subindex);
                            upeError     = UopManager.getIstance().Replace(pfCurrent.file, pfCurrent.index, pfCurrent.subindex, pfCurrent.compress > 0);

                            if (upeError != UopManager.UopPatchError.Okay)
                            {
                                errorOutput.AppendLine("Error (" + upeError.ToString() + ") while patching file \"" + pfCurrent.file + "\" to " + pfCurrent.index.ToString() + "," + pfCurrent.subindex.ToString() + " (" + ((pfCurrent.compress > 0) ? "UN" : "") + "compressed)");
                                break;
                            }
                        }

                        if (upeError == UopManager.UopPatchError.Okay)
                        {
                            if (!bOutputfile)
                            {
                                sOutputpath = Utility.GetPathForSave(UopManager.getIstance().UopPath);
                            }

                            if (bDontfix)
                            {
                                UopManager.getIstance().FixOffsets(iMinIndex, iMinSubindex);
                            }

                            if (!UopManager.getIstance().Write(sOutputpath))
                            {
                                errorOutput.AppendLine("Error while writing the new uop file (\"" + sOutputpath + "\")");
                            }
                        }
                    }
                }
                else
                {
                    errorOutput.AppendLine("Error while opening the uop file (\"" + UopManager.getIstance().UopPath + "\")");
                }
            }
            else
            {
                errorOutput.AppendLine("ERROR: No action defined.");
            }

            if (bEnablelog)
            {
                try
                {
                    File.WriteAllText(Application.StartupPath + @"\error.log", errorOutput.ToString());
                }
                catch { }
            }

            return(false);
        }
        public ActionResult PrintReport(string reportPath)
        {
            var model = this.GetReportViewerModel(Request);

            model.ViewMode   = ReportViewModes.Print;
            model.ReportPath = reportPath;

            var contentData = ReportServiceHelpers.ExportReportToFormat(model, ReportFormats.Html4_0);
            var content     = System.Text.Encoding.ASCII.GetString(contentData.ReportData);

            content = ReportServiceHelpers.ReplaceImageUrls(model, content);

            var sb = new System.Text.StringBuilder();

            sb.AppendLine("<html>");
            sb.AppendLine("	<body>");
            //sb.AppendLine($"		<img src='data:image/tiff;base64,{Convert.ToBase64String(contentData.ReportData)}' />");
            sb.AppendLine($"		{content}");
            sb.AppendLine("		<script type='text/javascript'>");
            sb.AppendLine("			(function() {");

            /*
             * sb.AppendLine("				var beforePrint = function() {");
             * sb.AppendLine("					console.log('Functionality to run before printing.');");
             * sb.AppendLine("				};");
             */
            sb.AppendLine("				var afterPrint = function() {");
            sb.AppendLine("					window.onfocus = function() { window.close(); };");
            sb.AppendLine("					window.onmousemove = function() { window.close(); };");
            sb.AppendLine("				};");

            sb.AppendLine("				if (window.matchMedia) {");
            sb.AppendLine("					var mediaQueryList = window.matchMedia('print');");
            sb.AppendLine("					mediaQueryList.addListener(function(mql) {");
            sb.AppendLine("						if (mql.matches) {");
            //sb.AppendLine("							beforePrint();");
            sb.AppendLine("						} else {");
            sb.AppendLine("							afterPrint();");
            sb.AppendLine("						}");
            sb.AppendLine("					});");
            sb.AppendLine("				}");

            //sb.AppendLine("				window.onbeforeprint = beforePrint;");
            sb.AppendLine("				window.onafterprint = afterPrint;");

            sb.AppendLine("			}());");
            sb.AppendLine("			window.print();");
            sb.AppendLine("		</script>");
            sb.AppendLine("	</body>");

            sb.AppendLine("<html>");

            return(Content(sb.ToString(), "text/html"));
        }
Beispiel #45
0
        public string GenerateHtmlTemplate(bool isLivePreview)
        {
            string value = string.Empty;

            if (System.IO.File.Exists(this.CssFilePath))
            {
                this._logger.Trace("Loading CSS file: " + this.CssFilePath);
                try
                {
                    value = System.IO.File.ReadAllText(this.CssFilePath);
                }
                catch (System.Exception exception)
                {
                    MessageBoxHelper.ShowErrorMessageBox(LocalizationProvider.GetLocalizedString("Error_OpeningCssFileMessage", true, "MarkdownPadStrings") + this.CssFilePath, LocalizationProvider.GetLocalizedString("Error_OpeningCssFileTitle", false, "MarkdownPadStrings"), exception, "");
                }
            }
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            string str = string.IsNullOrEmpty(this.Filename) ? "MarkdownPad Document" : System.IO.Path.GetFileNameWithoutExtension(this.Filename);

            if (!isLivePreview)
            {
                stringBuilder.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            }
            stringBuilder.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
            stringBuilder.AppendLine("<head>");
            stringBuilder.AppendLine("<title>" + str + "</title>");
            stringBuilder.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            stringBuilder.AppendLine("<style type=\"text/css\">");
            stringBuilder.AppendLine(value);
            stringBuilder.AppendLine("</style>");
            if (this.MarkdownProcessor == MarkdownProcessorType.GithubFlavoredMarkdown)
            {
                stringBuilder.AppendLine("<style type=\"text/css\">");
                stringBuilder.AppendLine(WebResources.PygmentsCss);
                stringBuilder.AppendLine("</style>");
            }
            if (isLivePreview)
            {
                stringBuilder.AppendLine("<script type='text/javascript'>function loadMarkdown(input) { document.body.innerHTML = input; var links = document.getElementsByTagName('a');var len = links.length;for(var i=0; i<len; i++){links[i].target = '_blank';} } </script>");
            }
            if (this.UseBaseRelativeImageWorkaround && !string.IsNullOrEmpty(this.Filename))
            {
                try
                {
                    stringBuilder.AppendLine("<base href='file:\\\\\\" + System.IO.Path.GetDirectoryName(this.Filename) + "\\'/>");
                }
                catch (System.Exception exception2)
                {
                    this._logger.ErrorException("Error setting relative base URL in HTML template", exception2);
                }
            }
            if (!string.IsNullOrEmpty(this.CustomHeadContent))
            {
                stringBuilder.AppendLine(this.CustomHeadContent);
            }
            stringBuilder.AppendLine("</head>");
            stringBuilder.AppendLine("<body>");
            stringBuilder.AppendLine(this.BodyContent);
            stringBuilder.AppendLine("</body>");
            stringBuilder.AppendLine("</html>");
            stringBuilder.AppendLine("<!-- This document was created with MarkdownPad, the Markdown editor for Windows (http://markdownpad.com) -->");
            return(stringBuilder.ToString());
        }
            public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
            {
                DataEntityToken token = (DataEntityToken)entityToken;

                IPublishControlled publishControlled = (IPublishControlled)DataFacade.GetDataFromDataSourceId(token.DataSourceId);

                ValidationResults validationResults = ValidationFacade.Validate((IData)publishControlled);

                if (validationResults.IsValid)
                {
                    UpdateTreeRefresher treeRefresher = new UpdateTreeRefresher(token.Data.GetDataEntityToken(), flowControllerServicesContainer);

                    if (actionToken is PublishActionToken)
                    {
                        publishControlled.PublicationStatus = Published;
                    }
                    else if (actionToken is DraftActionToken)
                    {
                        publishControlled.PublicationStatus = Draft;
                    }
                    else if (actionToken is AwaitingApprovalActionToken)
                    {
                        publishControlled.PublicationStatus = AwaitingApproval;
                    }
                    else if (actionToken is AwaitingPublicationActionToken)
                    {
                        publishControlled.PublicationStatus = AwaitingPublication;
                    }
                    else if (actionToken is UnpublishActionToken)
                    {
                        publishControlled.PublicationStatus = Draft;

                        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
                        {
                            IData data = DataFacade.GetDataFromOtherScope(token.Data, DataScopeIdentifier.Public).SingleOrDefault();

                            if (data != null)
                            {
                                IPage page = data as IPage;
                                if (page != null)
                                {
                                    IEnumerable <IData> referees;
                                    using (new DataScope(DataScopeIdentifier.Public))
                                    {
                                        referees = page.GetMetaData();
                                    }

                                    DataFacade.Delete(referees, CascadeDeleteType.Disable);
                                }


                                DataFacade.Delete(data, CascadeDeleteType.Disable);
                            }

                            transactionScope.Complete();
                        }
                    }
                    else if (actionToken is UndoPublishedChangesActionToken)
                    {
                        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
                        {
                            using (ProcessControllerFacade.NoProcessControllers)
                            {
                                var   administrativeData = (IPublishControlled)token.Data;
                                IData publishedData      = DataFacade.GetDataFromOtherScope(token.Data, DataScopeIdentifier.Public).Single();

                                publishedData.FullCopyChangedTo(administrativeData);
                                administrativeData.PublicationStatus = Draft;

                                DataFacade.Update(administrativeData);
                            }

                            transactionScope.Complete();
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Unknown action token", "actionToken");
                    }

                    DataFacade.Update(publishControlled);

                    treeRefresher.PostRefreshMesseges(publishControlled.GetDataEntityToken());
                }
                else
                {
                    var managementConsoleMessageService = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>();

                    StringBuilder sb = new System.Text.StringBuilder();
                    sb.AppendLine(StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "ValidationErrorMessage"));
                    foreach (ValidationResult result in validationResults)
                    {
                        sb.AppendLine(result.Message);
                    }

                    managementConsoleMessageService.ShowMessage(DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "ValidationErrorTitle"), sb.ToString());
                }

                return(null);
            }
        /// <summary>
        /// データ書き出し
        /// </summary>
        /// <param name="configurationFolder"></param>
        public override void Export(string directoryName, string savePath, List <ConfigurationFile> cnfigurationFile)
        {
            //ファイル名
            string cfgFilename = Common.File.CombinePath(savePath, directoryName + "_Departments" + ".cfg");

            //格納用
            var exportData = new System.Text.StringBuilder();


            //パーツ用書き出し用データ作成
            foreach (ConfigurationFile cfgFile in cnfigurationFile)
            {
                foreach (Text.TextData textData in cfgFile.TextDataList)
                {
                    if (textData.DataType == DataType.Departments)
                    {
                        var tData = (Text.TextDataDepartments)textData;
                        if (tData.TranslateTextList.Count >= 1)
                        {
                            //スペースが含まれている場合は、?に変換
                            string name = tData.Name;
                            name = name.Replace(" ", "?");

                            if (directoryName.Equals(VanillaDirectoryName, StringComparison.CurrentCultureIgnoreCase))
                            {
                                //(Vanilla
                                exportData.AppendLine(String.Format("@STRATEGY_DEPARTMENT:HAS[#name[{0}]]", name));
                            }
                            else
                            {
                                //MOD
                                exportData.AppendLine(String.Format("@STRATEGY_DEPARTMENT:HAS[#name[{0}]]:NEEDS[{1}]:FINAL", name, directoryName));
                            }
                            exportData.AppendLine("{");

                            exportData.AppendLine("\t//English Text");
                            exportData.AppendLine("\t//\t" + String.Format(@"@desc = {0}", tData.TranslateTextList[0].SourceText));
                            exportData.AppendLine("\t//Japanese Text");
                            if (tData.TranslateTextList[0].JapaneseText.Equals("") || tData.TranslateTextList[0].JapaneseText.Equals(tData.TranslateTextList[0].SourceText))
                            {
                                exportData.AppendLine("\t//\t" + @"@desc = ");
                            }
                            else
                            {
                                if (!tData.TranslateTextList[0].Comment.Equals(""))
                                {
                                    exportData.AppendLine("\t//\t" + tData.TranslateTextList[0].Comment);
                                }
                                exportData.AppendLine("\t\t" + String.Format(@"@desc = {0}", tData.TranslateTextList[0].JapaneseText));
                            }

                            exportData.AppendLine("}");
                            exportData.AppendLine("");
                        }
                    }
                }
            }


            //データがあればファイル書き出し
            this.DataWrite(cfgFilename, exportData);
        }
Beispiel #48
0
    public string _SaveSchemePages(DataTable dt, string[] column, int pageRow, int pageIndex, ref string returnHtml)
    {
        if (dt == null)
        {
            returnHtml = "<tr align=\"center\"><td colspan=\"6\">没有您的投注记录</td></tr>";
            return("");
        }
        if (dt.Rows.Count < 1)
        {
            returnHtml = "<tr align=\"center\"><td colspan=\"6\">没有您的投注记录</td></tr>";
            return("");
        }
        if (column == null)
        {
            returnHtml = "<tr align=\"center\"><td colspan=\"6\">没有您的投注记录</td></tr>";
            return("");
        }
        if (column.Length < 1)
        {
            returnHtml = "<tr align=\"center\"><td colspan=\"6\">没有您的投注记录</td></tr>";
            return("");
        }
        if (pageRow < 1)
        {
            pageRow = 10;
        }


        returnHtml = "<tr align=\"center\"><td colspan=\"6\">没有您的投注记录</td></tr>"; //
        int SumPageCount = 0;                                                     // 总页数


        // 总行
        SumPageCount = dt.Rows.Count;
        int xRows = 0;

        // 一行多少页
        if (pageIndex * pageRow > SumPageCount)
        {
            xRows = pageRow - (pageRow - SumPageCount % pageRow);
        }
        else
        {
            xRows = pageRow;
        }

        // 拼接Html
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        for (int row = (pageIndex - 1) * pageRow; row < (pageIndex - 1) * pageRow + xRows; row++)
        {
            sb.AppendLine("<tr align=\"center\">");
            for (int cols = 0; cols < column.Length; cols++)
            {
                if (column.Length - 1 == cols)
                {
                    DateTime time = Shove._Convert.StrToDateTime(dt.Rows[row]["EndTime"].ToString(), "2011-08-14 10:00:00");

                    if (DateTime.Compare(time, DateTime.Now) > 0)
                    {
                        sb.AppendLine("<td height=\"30px\"><a href=\"BuyConfirm.aspx?id=" + dt.Rows[row][column[cols]] + "&type=2\"><img src=\"/Home/Room/Images/bet.png\" /></a></td>");
                    }
                    else
                    {
                        sb.AppendLine("<td height=\"30px\">----</td>");
                    }
                }
                else
                {
                    sb.AppendLine("<td height=\"30px\">" + dt.Rows[row][column[cols]] + "</td>");
                }
            }
            sb.AppendLine("</tr>");
        }
        // 一共有多少页
        int SumPageNumber = SumPageCount % pageRow == 0 ? SumPageCount / pageRow : SumPageCount / pageRow + 1;

        // 制作 选也按钮
        sb.AppendLine("<tr style=\"height:20px;\">");
        sb.AppendLine("<td colspan=\"" + (column.Length) + "\" align=\"center\"  style=\"border:0px;\">");

        // 显示分页的索引
        int index = pageIndex < 2 ? 1 : pageIndex - 1;

        //Top
        if (pageIndex > 1)
        { // 当前页大于1
            sb.AppendLine("<a style=\"\" href=\"javascript:SaveSchemes(1)\">&lt;&lt;</a>");
            sb.AppendLine("<a style=\"\" href=\"javascript:SaveSchemes(" + (pageIndex - 1).ToString() + ")\">上一页</a>");
        }
        else
        {
            sb.AppendLine("<span style=\"color:Gray\">&lt;&lt;</span>");
            sb.AppendLine("<span style=\"color:Gray\">上一页</span>");
        }

        for (int i = 0; i < 6; i++)
        {
            if (SumPageNumber < index)
            {
                break;
            }
            if (index < 1)
            {
                index = 1;
            }
            if (SumPageCount - index > 1 && i == 5)
            {
                sb.AppendLine("<span class=\"currentPage\" style=\"margin-right:5px;\"><a href=\"javascript:Changepage(" + index + ")\" style=\"cursor:pointer;\">" + index + "</a> ..</span>");
            }
            else if (index > 1 && i == 0)
            {
                sb.AppendLine("<span class=\"currentPage\" style=\"margin-right:5px;\">.. <a href=\"javascript:Changepage(" + index + ")\" style=\"cursor:pointer;\">" + index + "</a></span>");
            }
            else if (SumPageNumber == 1)
            {
                sb.AppendLine("<span class=\"currentPage\" style=\"margin-right:5px;\">1</span>");
            }
            else
            {
                if (pageIndex == index)
                {
                    sb.AppendLine("<span class=\"currentPage\" style=\"margin-right:5px;color:Gray;\">" + index + "</span>");
                }
                else
                {
                    sb.AppendLine("<span class=\"currentPage\" style=\"margin-right:5px;\"><a href=\"javascript:Changepage(" + index + ")\" style=\"cursor:pointer;\">" + index + "</a></span>");
                }
            }

            index++;
        }

        // Down
        if (pageIndex == SumPageNumber)
        {
            sb.AppendLine("<span style=\"color:Gray\">下一页</span>");
            sb.AppendLine("<span style=\"color:Gray\">&gt;&gt;</span>");
        }
        else
        {
            sb.AppendLine("<a href=\"javascript:SaveSchemes(" + (pageIndex + 1).ToString() + ")\">下一页</a>");
            sb.AppendLine("<a href=\"javascript:SaveSchemes(" + SumPageNumber + ")\">&gt;&gt;</a>");
        }

        sb.AppendLine("</td></tr>");

        // 返回的Html代码
        returnHtml = sb.ToString();

        return(returnHtml);
    }
Beispiel #49
0
        /// <summary>
        /// 信息询问
        /// </summary>
        /// <param name="page">页面page对象</param>
        /// <param name="msg">信息内容</param>
        /// <param name="urla">确定后跳页面</param>
        /// <param name="urlb">取消后跳页面</param>
        /// <param name="target">页面跳转框架</param>
        protected static void JboxShowConfirm(System.Web.UI.Page page, string msg, string urla, string urlb, string target)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.AppendLine("");

            bool isjquey = false;

            //是否存在 jquery ,不需要重复导入
            for (int i = 0; i < page.Header.Controls.Count; i++)
            {
                System.IO.StringWriter sw         = new System.IO.StringWriter();
                HtmlTextWriter         html_write = new HtmlTextWriter(sw);
                page.Header.Controls[i].RenderControl(html_write);
                if (sw.ToString().ToLower().Contains("jquery"))
                {
                    isjquey = true;
                }
            }

            //加载需要的库
            string adminpath = "/";
            string str_res   = "<link rel=\"stylesheet\" href=\"" + adminpath + "/tool/JBox/Skins/Blue/jbox.css\" />\n";

            if (!isjquey)
            {
                str_res += "<script type=\"text/javascript\" src=\"" + adminpath + "/js/jquery1.4.js\"></script>\n";
            }
            str_res += "<script type=\"text/javascript\" src=\"" + adminpath + "/tool/JBox/jquery.jBox-2.3.min.js\"></script>\n";
            sb.AppendLine(str_res);


            sb.AppendLine("<script type=\"text/javascript\">");
            sb.AppendLine("var fun_submit = function (v, h, f) {");
            if (urla != "")
            {
                sb.AppendLine("" + target + ".location.href='" + urla + "';");
            }
            sb.AppendLine("return true;");
            sb.AppendLine("};");

            sb.AppendLine("var fun_cancel = function () {");
            if (urlb != "")
            {
                sb.AppendLine("" + target + ".location.href='" + urlb + "';");
            }
            sb.AppendLine("return true;");
            sb.AppendLine("};");

            sb.AppendLine("function jboxMsg(msg) {");
            sb.AppendLine("     $.jBox.confirm(msg , \"信息提示\", { submit : fun_submit ,cancel : fun_cancel , top: '30%' });");
            sb.AppendLine("}");
            sb.AppendLine("</script>");

            sb.AppendLine("<script language='javascript'>$(document).ready(function () {jboxMsg('" + msg + "');});</script>");
            sb.AppendLine("");

            page.Header.Controls.AddAt(0, new LiteralControl(sb.ToString()));
            //page.ClientScript.RegisterClientScriptBlock(page.GetType(), "jbox", sb.ToString());
        }
Beispiel #50
0
        static string TicksInfo()
        {
            System.Text.StringBuilder ticksInfoBuilder = new System.Text.StringBuilder("\r\n\r\n");
            ticksInfoBuilder.AppendLine("Ticks Info");
            ticksInfoBuilder.AppendLine("--------------------------------------------------------------");
            const string numberFmt = "{0,-22}{1,18:N0}";
            const string timeFmt   = "{0,-22}{1,26}";

            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Field", "Value"));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "-----", "-----"));

            // Display the maximum, minimum, and zero TimeSpan values.
            ticksInfoBuilder.AppendLine(System.String.Format(timeFmt, "Maximum TimeSpan", Align(System.TimeSpan.MaxValue)));
            ticksInfoBuilder.AppendLine(System.String.Format(timeFmt, "Minimum TimeSpan", Align(System.TimeSpan.MinValue)));
            ticksInfoBuilder.AppendLine(System.String.Format(timeFmt, "Zero TimeSpan", Align(System.TimeSpan.Zero)));
            ticksInfoBuilder.AppendLine();

            // Display the ticks-per-time-unit fields.
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per day", System.TimeSpan.TicksPerDay));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per hour", System.TimeSpan.TicksPerHour));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per minute", System.TimeSpan.TicksPerMinute));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per second", System.TimeSpan.TicksPerSecond));
            ticksInfoBuilder.AppendLine(System.String.Format(numberFmt, "Ticks per millisecond", System.TimeSpan.TicksPerMillisecond));
            ticksInfoBuilder.AppendLine("--------------------------------------------------------------");
            return(ticksInfoBuilder.ToString());
        }
Beispiel #51
0
        /// <summary>
        /// 输出jbox效果
        /// </summary>
        /// <param name="msg">信息提示</param>
        /// <param name="url">跳转地址</param>
        /// <param name="target">页面跳转框架</param>
        protected static void JboxShow(string msg, string url, string target)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
            sb.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>");

            sb.AppendLine(str_jboxres);

            sb.AppendLine("<script type=\"text/javascript\">");

            sb.AppendLine("var fun_submit = function (v, h, f) {");
            if (url != "")
            {
                sb.AppendLine("" + target + ".location.href='" + url + "';");
            }
            sb.AppendLine("return true;");
            sb.AppendLine("};");

            sb.AppendLine("var fun_close = function () {");
            if (url != "")
            {
                sb.AppendLine("" + target + ".location.href='" + url + "';");
            }
            sb.AppendLine("return true;");
            sb.AppendLine("};");

            sb.AppendLine("function jboxMsg(msg) {");
            sb.AppendLine("     $.jBox.info(msg , \"信息提示\", { submit : fun_submit ,closed : fun_close , top: '30%'});");

            /*
             * sb.AppendLine("$.jBox(msg, {");
             * sb.AppendLine(" title: \"信息提示\",");
             * sb.AppendLine("  width: 500,");
             * sb.AppendLine(" height: 350,");
             * sb.AppendLine(" buttons: { '关闭': true }");
             * sb.AppendLine("});");*/
            sb.AppendLine("}");
            sb.AppendLine("</script>");

            sb.AppendLine("<script language='javascript'>$(document).ready(function () {jboxMsg('" + msg + "');});</script>");

            sb.AppendLine("</head><body>");
            sb.AppendLine("</body></html>");

            System.Web.HttpContext.Current.Response.Write(sb.ToString());
            System.Web.HttpContext.Current.Response.End();
        }
Beispiel #52
0
        public static bool InsertFlowInfo(FlowModel model, string StepNo, string StepName, string StepActor)
        {
            ArrayList listADD = new ArrayList();
            bool      result  = false;

            try
            {
                #region  增加SQL语句
                StringBuilder sqlflow = new StringBuilder();
                sqlflow.AppendLine("INSERT INTO officedba.Flow");
                sqlflow.AppendLine("		(CompanyCD      ");
                sqlflow.AppendLine("		,DeptID         ");
                sqlflow.AppendLine("		,FlowNo         ");
                sqlflow.AppendLine("		,FlowName         ");
                sqlflow.AppendLine("		,BillTypeFlag         ");
                sqlflow.AppendLine("		,BillTypeCode         ");
                sqlflow.AppendLine("		,UsedStatus         ");
                sqlflow.AppendLine("		,IsMobileNotice     ");
                sqlflow.AppendLine("		,ModifiedDate         ");
                sqlflow.AppendLine("		,ModifiedUserID)        ");
                sqlflow.AppendLine("VALUES                  ");
                sqlflow.AppendLine("		(@CompanyCD,     ");
                sqlflow.AppendLine("		@DeptID ,     ");
                sqlflow.AppendLine("		@FlowNo ,     ");
                sqlflow.AppendLine("		@FlowName ,     ");
                sqlflow.AppendLine("		@BillTypeFlag,     ");
                sqlflow.AppendLine("		@BillTypeCode,     ");
                sqlflow.AppendLine("		@UsedStatus,     ");
                sqlflow.AppendLine("		@IsMobileNotice     ");
                sqlflow.AppendLine("		,@ModifiedDate     ");
                sqlflow.AppendLine("		,@ModifiedUserID)       ");
                SqlCommand comm = new SqlCommand();
                comm.CommandText = sqlflow.ToString();
                comm.Parameters.Add(SqlHelper.GetParameter("@CompanyCD", model.CompanyCD));
                comm.Parameters.Add(SqlHelper.GetParameter("@DeptID", model.DeptID));
                comm.Parameters.Add(SqlHelper.GetParameter("@FlowNo", model.FlowNo));
                comm.Parameters.Add(SqlHelper.GetParameter("@FlowName", model.FlowName));
                comm.Parameters.Add(SqlHelper.GetParameter("@BillTypeFlag", model.BillTypeFlag));
                comm.Parameters.Add(SqlHelper.GetParameter("@BillTypeCode", model.BillTypeCode));
                comm.Parameters.Add(SqlHelper.GetParameter("@UsedStatus", model.UsedStatus));
                comm.Parameters.Add(SqlHelper.GetParameter("@IsMobileNotice", model.IsMobileNotice));
                comm.Parameters.Add(SqlHelper.GetParameter("@ModifiedDate", model.ModifiedDate));
                comm.Parameters.Add(SqlHelper.GetParameter("@ModifiedUserID", model.ModifiedUserID));
                listADD.Add(comm);
                #endregion

                #region 流程步骤添加SQL语句
                if (!String.IsNullOrEmpty(StepNo) && !String.IsNullOrEmpty(StepName) && !String.IsNullOrEmpty(StepActor))
                {
                    string[] dStepNo    = StepNo.Split(',');
                    string[] dStepName  = StepName.Split(',');
                    string[] dStepActor = StepActor.Split(',');
                    //页面上这些字段都是必填,数组的长度必须是相同的
                    if (dStepNo.Length >= 1)
                    {
                        for (int i = 0; i < dStepNo.Length; i++)
                        {
                            System.Text.StringBuilder cmdsql = new System.Text.StringBuilder();
                            cmdsql.AppendLine("INSERT INTO officedba.FlowStepActor");
                            cmdsql.AppendLine("           (CompanyCD");
                            cmdsql.AppendLine("           ,FlowNo");
                            cmdsql.AppendLine("           ,StepNo");
                            cmdsql.AppendLine("           ,StepName");
                            cmdsql.AppendLine("           ,Actor");
                            cmdsql.AppendLine("           ,ModifiedDate");
                            cmdsql.AppendLine("           ,ModifiedUserID)");
                            cmdsql.AppendLine("     VALUES");
                            cmdsql.AppendLine("           (@CompanyCD");
                            cmdsql.AppendLine("           ,@FlowNo");
                            cmdsql.AppendLine("           ,@StepNo");
                            cmdsql.AppendLine("           ,@StepName");
                            cmdsql.AppendLine("           ,@Actor");
                            cmdsql.AppendLine("           ,@ModifiedDate");
                            cmdsql.AppendLine("           ,@ModifiedUserID)");
                            SqlCommand comms = new SqlCommand();
                            comms.CommandText = cmdsql.ToString();
                            comms.Parameters.Add(SqlHelper.GetParameter("@CompanyCD", model.CompanyCD));
                            comms.Parameters.Add(SqlHelper.GetParameter("@FlowNo", model.FlowNo));
                            if (dStepNo[i].ToString().Length > 0)
                            {
                                if (!string.IsNullOrEmpty(dStepNo[i].ToString().Trim()))
                                {
                                    comms.Parameters.Add(SqlHelper.GetParameter("@StepNo", dStepNo[i].ToString()));
                                }
                            }
                            if (dStepName[i].ToString().Length > 0)
                            {
                                if (!string.IsNullOrEmpty(dStepName[i].ToString().Trim()))
                                {
                                    comms.Parameters.Add(SqlHelper.GetParameter("@StepName", dStepName[i].ToString()));
                                }
                            }
                            if (dStepActor[i].ToString().Length > 0)
                            {
                                if (!string.IsNullOrEmpty(dStepActor[i].ToString().Trim()))
                                {
                                    comms.Parameters.Add(SqlHelper.GetParameter("@Actor", dStepActor[i].ToString()));
                                }
                            }
                            comms.Parameters.Add(SqlHelper.GetParameter("@ModifiedDate", model.ModifiedDate));
                            comms.Parameters.Add(SqlHelper.GetParameter("@ModifiedUserID", model.ModifiedUserID));

                            listADD.Add(comms);
                        }
                    }
                }
                #endregion
                if (SqlHelper.ExecuteTransWithArrayList(listADD))
                {
                    result = true;
                }
                return(result);
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #53
0
        /// <summary>
        /// 收款单取消确认
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancelConfirm_Click(object sender, RoutedEventArgs e)
        {
            var selectedEntites = GetSelectedSOIncomeList();

            if (selectedEntites.Count <= 0)
            {
                Window.Alert(ResCommon.Message_AtLeastChooseOneRecord);
                return;
            }

            var sysNoList       = new List <int>();
            var cancelSysNoList = new List <int>();

            selectedEntites.ForEach(w =>
            {
                bool isCanceled      = true; //是否取消选择
                bool isConfirmed     = false;
                DateTime confirmDate = DateTime.MinValue;

                if (w.IncomeStatus == SOIncomeStatus.Confirmed)
                {
                    isConfirmed = w.ConfirmTime.HasValue;
                    confirmDate = w.ConfirmTime ?? DateTime.MinValue;
                }

                #region 判断权限,如果不满足收款单确认的条件,则不向服务端提交

                if (isConfirmed && AuthMgr.HasFunctionPoint(AuthKeyConst.Invoice_SaleIncomeQuery_CancelConfirm_InConfirmDay))
                {
                    if (DateTime.Now.Subtract(confirmDate).Days == 0)
                    {
                        isCanceled = false;
                    }
                }
                if (isConfirmed && AuthMgr.HasFunctionPoint(AuthKeyConst.Invoice_SaleIncomeQuery_CancelConfirm_AfterConfirmDay))
                {
                    if (DateTime.Now.Subtract(confirmDate).Days > 0)
                    {
                        isCanceled = false;
                    }
                }

                #endregion 判断权限,如果不满足收款单确认的条件,则不向服务端提交

                if (!isCanceled)
                {
                    sysNoList.Add(w.SysNo.Value);
                }
                else
                {
                    cancelSysNoList.Add(w.SysNo.Value);
                }
            });

            soIncomeFacade.BatchCancelConfirm(sysNoList, msg =>
            {
                if (cancelSysNoList.Count > 0)
                {
                    //fixbug:修正提示信息
                    int matchIndex = 0;
                    msg            = System.Text.RegularExpressions.Regex.Replace(msg, "(\\d+)", match =>
                    {
                        matchIndex++;
                        if (matchIndex == 1 || matchIndex == 3)
                        {
                            return((int.Parse(match.Value) + cancelSysNoList.Count).ToString());
                        }
                        return(match.Value);
                    });

                    System.Text.StringBuilder cancelMsg = new System.Text.StringBuilder();
                    cancelMsg.AppendLine(ResSaleIncomeQuery.Message_RecordsNotSubmit);
                    cancelSysNoList.ForEach(w =>
                    {
                        cancelMsg.AppendLine(string.Format(ResSaleIncomeQuery.Message_NoOperatePermissionFormat, w));
                    });
                    msg += cancelMsg.ToString();
                }
                Window.Alert(msg, () => this.dgSaleIncomeQueryResult.Bind());
            });
        }
Beispiel #54
0
        public static Nullable <Guid> GetCodeMasterID(string Value, string CodeType, bool CreateIfNotExists = false)
        {
            if (Value == "PreMSC (Application)" && CodeType == "AccountManagerType")
            {
                return(new Guid("4063B324-60DE-4315-AC3B-711176AD823E"));
            }
            if (Value == "Business Analyst" && CodeType == "AccountManagerType")
            {
                return(new Guid("842D6F72-612D-4A21-9D01-FD11B9A407BE"));
            }
            if (Value == "Financial Analyst" && CodeType == "AccountManagerType")
            {
                return(new Guid("31F905A0-A4D9-421D-9534-690DF0ECA752"));
            }
            if (Value == "PostMSC (Application)" && CodeType == "AccountManagerType")
            {
                return(new Guid("F3538447-717D-4FBC-B32A-65C06D3AD294"));
            }
            SqlConnection  con = new SqlConnection(ConfigurationSettings.AppSettings["CRM"].ToString());
            SqlCommand     com = new SqlCommand();
            SqlDataAdapter ad  = new SqlDataAdapter(com);

            System.Text.StringBuilder sql = new System.Text.StringBuilder();
            sql.AppendLine("SELECT CodeMasterID");
            sql.AppendLine("FROM CodeMaster");
            sql.AppendLine("WHERE CodeType = @CodeType");
            sql.AppendLine("AND CodeName = @Value");

            com.CommandText = sql.ToString();
            com.CommandType = CommandType.Text;
            com.Connection  = con;

            //con.Open()
            try
            {
                com.Parameters.Add(new SqlParameter("@CodeType", CodeType));
                com.Parameters.Add(new SqlParameter("@Value", Value));

                DataTable dt = new DataTable();
                ad.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    return(new Guid(dt.Rows[0][0].ToString()));
                }
                else
                {
                    if (CreateIfNotExists)
                    {
                        return(CreateCodeMaster(Value, CodeType));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                con.Close();
            }
        }
Beispiel #55
0
        private string FormatCondensedJson(string str)
        {
            str = (str ?? "").Replace("{}", @"\{\}").Replace("[]", @"\[\]");

            var  inserts = new List <int[]>();
            bool quoted = false, escape = false;
            int  depth = 0 /*-1*/;

            char prev = '-';

            for (int i = 0, N = str.Length; i < N; i++)
            {
                var chr = str[i];

                if (!escape && !quoted)
                {
                    switch (chr)
                    {
                    //case '{':
                    case '[':
                        inserts.Add(new[] { i, +1, 0, INDENT_SIZE * ++depth });
                        //int n = (i == 0 || "{[,".Contains(str[i - 1])) ? 0 : -1;
                        //inserts.Add(new[] { i, n, INDENT_SIZE * ++depth * -n, INDENT_SIZE - 1 });
                        break;

                    case ',':
                        if (prev == '}' || prev == ']')
                        {
                            inserts.Add(new[] { i, +1, 0, INDENT_SIZE * depth });
                        }
                        else
                        {
                            inserts.Add(new[] { i, 0, 1, 1 });
                        }
                        //inserts.Add(new[] { i, -1, INDENT_SIZE * depth, INDENT_SIZE - 1 });
                        break;

                    //case '}':
                    case ']':
                        inserts.Add(new[] { i, -1, INDENT_SIZE * --depth, 0 });
                        //inserts.Add(new[] { i, -1, INDENT_SIZE * depth--, 0 });
                        break;

                    case ':':
                        inserts.Add(new[] { i, 0, 1, 1 });
                        break;
                    }
                }

                quoted = (chr == '"') ? !quoted : quoted;
                escape = (chr == '\\') && !escape;
                prev   = chr;
            }

            if (inserts.Count > 0)
            {
                var sb = new System.Text.StringBuilder(str.Length * 2);

                int lastIndex = 0;
                foreach (var insert in inserts)
                {
                    int  index = insert[0], before = insert[2], after = insert[3];
                    bool nlBefore = (insert[1] == -1), nlAfter = (insert[1] == +1);

                    sb.Append(str.Substring(lastIndex, index - lastIndex));

                    if (nlBefore)
                    {
                        sb.AppendLine();
                    }
                    if (before > 0)
                    {
                        sb.Append(new String(' ', before));
                    }

                    sb.Append(str[index]);

                    if (nlAfter)
                    {
                        sb.AppendLine();
                    }
                    if (after > 0)
                    {
                        sb.Append(new String(' ', after));
                    }

                    lastIndex = index + 1;
                }

                str = sb.ToString();
            }

            return(str.Replace(@"\{\}", "{}").Replace(@"\[\]", "[]"));
        }
        protected override CompanyProfileResult ConvertResult(Base.ConnectionInfo connInfo, System.IO.Stream stream, Base.SettingsBase settings)
        {
            CompanyProfileData res = null;

            System.Globalization.CultureInfo convCulture = new System.Globalization.CultureInfo("en-US");
            if (stream != null)
            {
                XParseDocument doc        = MyHelper.ParseXmlDocument(stream);
                XParseElement  resultNode = XPath.GetElement("//table[@id=\"yfncsumtab\"]/tr[2]", doc);

                if (resultNode != null)
                {
                    res = new CompanyProfileData();
                    res.SetID(FinanceHelper.CleanIndexID(((CompanyProfileDownloadSettings)settings).ID.ToUpper()));

                    XParseElement nameNode = XPath.GetElement("td[1]/b[1]", resultNode);
                    if (nameNode != null)
                    {
                        res.CompanyName = nameNode.Value;
                    }

                    XParseElement addressNode = XPath.GetElement("td[1]", resultNode);
                    if (addressNode != null)
                    {
                        System.Text.StringBuilder formattedAddress = new System.Text.StringBuilder();
                        try
                        {
                            string addNodeStr = addressNode.ToString();
                            if (addNodeStr != string.Empty)
                            {
                                addNodeStr = addNodeStr.Substring(addNodeStr.IndexOf("/>") + 2);
                                string[] rawAddress = addNodeStr.Substring(0, addNodeStr.IndexOf("Website")).Split(new string[] { "<b>", "<br />", "</b>", "\r", "\n", " - ", "</a>" }, StringSplitOptions.RemoveEmptyEntries);
                                if (rawAddress.Length >= 7)
                                {
                                    foreach (string line in rawAddress)
                                    {
                                        string l = line.Trim();
                                        if (l != string.Empty && !l.StartsWith("<a") && l != "Map")
                                        {
                                            formattedAddress.AppendLine(l);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        res.Address = formattedAddress.ToString().TrimEnd();
                    }

                    XParseElement indicesNode = XPath.GetElement("td[1]/table[2]/tr/td/table/tr/td[2]", resultNode);
                    if (indicesNode != null)
                    {
                        List <KeyValuePair <string, string> > lstIndices = new List <KeyValuePair <string, string> >();
                        foreach (XParseElement indexLink in indicesNode.Elements())
                        {
                            if (indexLink.Name.LocalName == "a")
                            {
                                string indexID = Uri.UnescapeDataString(MyHelper.GetXmlAttributeValue(indexLink, "href").ToUpper().Replace("HTTP://FINANCE.YAHOO.COM/Q?S=", "").Replace("&D=T", ""));
                                string name    = string.Empty;
                                foreach (string p in indexLink.Value.Split(new string[] { "\r\n" }, StringSplitOptions.None))
                                {
                                    name += p.Trim() + " ";
                                }
                                lstIndices.Add(new KeyValuePair <string, string>(indexID, name.TrimEnd()));
                            }
                        }
                        res.Details.IndexMembership = lstIndices.ToArray();
                    }

                    XParseElement sectorsNode = XPath.GetElement("td[1]/table[2]/tr/td/table/tr[2]/td[2]", resultNode);
                    if (sectorsNode != null)
                    {
                        foreach (XParseElement sectorLink in sectorsNode.Elements())
                        {
                            if (sectorLink.Name.LocalName == "a")
                            {
                                foreach (Sector sect in Enum.GetValues(typeof(Sector)))
                                {
                                    string name = string.Empty;
                                    foreach (string p in sectorLink.Value.Split(new string[] { "\r\n" }, StringSplitOptions.None))
                                    {
                                        name += p.Trim() + " ";
                                    }
                                    name = name.TrimEnd();
                                    if (sect.ToString().Replace("_", " ") == name)
                                    {
                                        res.Details.Sector = sect;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    XParseElement industryNode = XPath.GetElement("td[1]/table[2]/tr/td/table/tr[3]/td[2]", resultNode);
                    if (industryNode != null)
                    {
                        foreach (XParseElement industryLink in industryNode.Elements())
                        {
                            if (industryLink.Name.LocalName == "a")
                            {
                                int indIndex = 0;
                                if (int.TryParse(MyHelper.GetXmlAttributeValue(industryLink, "href").Replace("http://biz.yahoo.com/ic/", "").Replace(".html", ""), out indIndex))
                                {
                                    res.Details.Industry = (Industry)indIndex;
                                }
                            }
                        }
                    }

                    XParseElement employeesNode = XPath.GetElement("td[1]/table[2]/tr/td/table/tr[4]/td[2]", resultNode);
                    if (employeesNode != null)
                    {
                        int fte;
                        if (int.TryParse(employeesNode.Value.Trim(), System.Globalization.NumberStyles.Any, convCulture, out fte))
                        {
                            res.Details.FullTimeEmployees = fte;
                        }
                    }

                    XParseElement summaryNode = XPath.GetElement("td[1]/p[1]", resultNode);
                    if (summaryNode != null)
                    {
                        System.Text.StringBuilder summaryText = new System.Text.StringBuilder();
                        foreach (string line in summaryNode.Value.Split(new string[] { "\r\n" }, StringSplitOptions.None))
                        {
                            summaryText.Append(line.Trim() + " ");
                        }
                        res.BusinessSummary = summaryText.ToString().TrimEnd();
                    }

                    XParseElement websitesNodes = XPath.GetElement("td[1]/table[5]/tr/td", resultNode);
                    if (websitesNodes != null)
                    {
                        List <Uri> lstWebsites = new List <Uri>();
                        foreach (XParseElement linkNode in websitesNodes.Elements())
                        {
                            if (linkNode.Name.LocalName == "a")
                            {
                                lstWebsites.Add(new Uri(MyHelper.GetXmlAttributeValue(linkNode, "href")));
                            }
                        }
                        res.CompanyWebsites = lstWebsites.ToArray();
                    }



                    XParseElement governanceNode   = null;
                    XParseElement governanceHeader = XPath.GetElement("td[3]/table[1]/tr/th/span", resultNode);
                    if (governanceHeader != null && governanceHeader.Value.Contains("Governance"))
                    {
                        governanceNode = XPath.GetElement("td[3]/table[2]/tr/td", resultNode);
                    }
                    if (governanceNode != null)
                    {
                        System.Text.StringBuilder governanceText = new System.Text.StringBuilder();
                        foreach (string line in governanceNode.Value.Split(new string[] { "\r\n" }, StringSplitOptions.None))
                        {
                            governanceText.Append(line.Trim() + " ");
                        }
                        res.CorporateGovernance = governanceText.ToString().TrimEnd();
                    }



                    XParseElement executivesNode   = null;
                    XParseElement executivesHeader = XPath.GetElement("td[3]/table[3]/tr/th/span", resultNode);
                    if (executivesHeader != null && executivesHeader.Value.Contains("Executives"))
                    {
                        executivesNode = XPath.GetElement("td[3]/table[4]/tr/td/table", resultNode);
                    }
                    else
                    {
                        executivesNode = XPath.GetElement("td[3]/table[2]/tr/td/table", resultNode);
                    }

                    if (executivesNode != null)
                    {
                        List <ExecutivePersonInfo> lst = new List <ExecutivePersonInfo>();
                        bool isFirst = true;
                        foreach (XParseElement row in executivesNode.Elements())
                        {
                            if (!isFirst)
                            {
                                if (row.Name.LocalName == "tr")
                                {
                                    XParseElement[] enm = MyHelper.EnumToArray(row.Elements());
                                    if (enm.Length >= 3)
                                    {
                                        ExecutivePersonInfo exec = new ExecutivePersonInfo();

                                        string name = string.Empty;

                                        foreach (string l in MyHelper.EnumToArray(enm[0].Elements())[0].Value.Split(new string[] { "\r\n" }, StringSplitOptions.None))
                                        {
                                            name += l.Trim() + " ";
                                        }

                                        exec.Name = name.TrimEnd();

                                        string position = string.Empty;

                                        var enm2 = MyHelper.EnumToArray(enm[0].Elements());
                                        foreach (string l in enm2[enm2.Length - 1].Value.Split(new string[] { "\r\n" }, StringSplitOptions.None))
                                        {
                                            position += l.Trim() + " ";
                                        }

                                        exec.Position = position.Trim();


                                        string payStr = enm[1].Value.Replace("\r\n", "").Trim();
                                        if (!payStr.Contains("N/A"))
                                        {
                                            exec.Pay = FinanceHelper.GetMillionValue(payStr) * 1000000;
                                        }

                                        string exercisedStr = enm[2].Value.Replace("\r\n", "").Trim();
                                        if (!exercisedStr.Contains("N/A"))
                                        {
                                            double d = FinanceHelper.GetMillionValue(exercisedStr);
                                            exec.Exercised = (int)(d * 1000000);
                                        }

                                        lst.Add(exec);
                                    }
                                }
                            }
                            else
                            {
                                isFirst = false;
                            }
                        }
                        res.KeyExecutives = lst.ToArray();
                    }
                    if (res.BusinessSummary.StartsWith("There is no "))
                    {
                        res = null;
                    }
                }
            }

            return(new CompanyProfileResult(res));
        }
Beispiel #57
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sbWork">StringBuilder to append method</param>
        /// <param name="classNamespace">class name</param>
        /// <param name="methodName">method name</param>
        /// <param name="method">Ajax method</param>
        /// <param name="parameters">List of parameters</param>
        /// <param name="ajaxClass"> </param>
        /// <param name="useTraditionalParameterForm"> Use traditional parameters, like function(parm1,parm2,parm3) instead function(options), calling myFunc({data:'data'});</param>
        /// <returns></returns>
        public virtual void CreateMethodBody(ref System.Text.StringBuilder sbWork, string classNamespace, string methodName, AjaxMethodItem method, IList <Entities.Parameter> parameters, AjaxClassItem ajaxClass, bool useTraditionalParameterForm = false)
        {
            var functionBody = new StringBuilder("function(");

            if (useTraditionalParameterForm)
            {
                for (var index = 0; index < parameters.Count; index++)
                {
                    if (index != 0)
                    {
                        functionBody.Append(",");
                    }
                    var parameter = parameters[index];
                    functionBody.Append(parameter.Name);
                }
                functionBody.Append((parameters.Count > 0 ? "," : "") + "callbackSuccess,callbackError,callbackComplete,uploadProgress");
            }
            else
            {
                functionBody.Append("options");
            }

            functionBody.Append("){" + GetNewLineTab(1));


            functionBody.Append(GetNewLineTab(1));
            functionBody.Append("var mtnOptions = (typeof options === 'undefined' || options == null)?{}:options;");
            functionBody.Append(GetNewLineTab(1));
            functionBody.Append("mtnOptions.data = mtnOptions.data || {};");
            functionBody.Append(GetNewLineTab(1));
            if (useTraditionalParameterForm)
            {
                functionBody.Append(GetNewLineTab(1));
                functionBody.
                Append("mtnOptions.callbackSuccess = callbackSuccess;").Append(GetNewLineTab(1)).
                Append("mtnOptions.callbackError = callbackError;").Append(GetNewLineTab(1)).
                Append("mtnOptions.callbackComplete = callbackComplete;").Append(GetNewLineTab(1)).
                Append("mtnOptions.uploadProgress = uploadProgress;");
                functionBody.Append(GetNewLineTab(1));

                if (parameters.Count > 0)
                {
                    functionBody.Append("mtnOptions.data = {");

                    for (var index = 0; index < parameters.Count; index++)
                    {
                        var parameter = parameters[index];
                        functionBody.Append(GetNewLineTab(2));
                        functionBody.Append((index != 0 ? "," : ""))
                        .Append(parameter.Name).Append(":").Append(parameter.Name);
                    }


                    functionBody.Append(GetNewLineTab(1));
                    functionBody.Append("};");
                }
                functionBody.Append(GetNewLineTab(1));
            }

            for (var index = 0; index < parameters.Count; index++)
            {
                var parameter = parameters[index];
                if (parameter.Type.IsPrimitiveMtn() || parameter.Type.FullName.ToLower().Contains("httppostedfile"))
                {
                    continue;
                }

                functionBody.Append(GetNewLineTab(1));
                functionBody.AppendFormat("mtnOptions.data.{0} = JSON.stringify(mtnOptions.data.{0});", parameter.Name);
                functionBody.Append(GetNewLineTab(1));
            }

            functionBody.AppendFormat("mtnOptions.data.__MtnClassHash = '{0}';", ajaxClass.Key);
            functionBody.Append(GetNewLineTab(1));
            functionBody.AppendFormat("mtnOptions.data.__MtnMethodHash = '{0}';", method.Key);
            functionBody.Append(GetNewLineTab(1));
            switch (Mode)
            {
            case WebModeType.AjaxHandler:
                functionBody.Append("mtnOptions.url='")
                .Append(HostUrl).Append("/")
                .Append(classNamespace.ToLowerInvariant()).Append(".").Append(methodName)
                .Append(".").Append(Utils.Parameter.AjaxExtension)
                .Append("';");
                break;

            case WebModeType.MvcController:
                functionBody.Append("mtnOptions.url='")
                .Append(HostUrl).Append("/{MtnMvcRoute}")
                .Append(classNamespace.Replace(".", Web.Utils.Parameter.SeoCharacter).ToLowerInvariant()).Append("/").Append(methodName.ToLowerInvariant())
                .Append("/';");
                break;

            default:
                functionBody.Append("mtnOptions.url='")
                .Append(HostUrl).Append("/{MtnMvcRoute}")
                .Append(classNamespace.Replace(".", Web.Utils.Parameter.SeoCharacter).ToLowerInvariant()).Append("/").Append(methodName.ToLowerInvariant())
                .Append("/';");
                break;
            }
            functionBody.Append(GetNewLineTab(1));

            functionBody.AppendFormat("mtnOptions.responseType = '{0}';", method.AjaxMethod.ResponseType.ToString().ToLowerInvariant());
            functionBody.Append(GetNewLineTab(1));
            string ajaxTmpl = "";

            switch (method.AjaxMethod.RequestType)
            {
            case RequestType.Post:
                ajaxTmpl = AjaxPostFunctionTemplate;
                break;

            case RequestType.Get:
                ajaxTmpl = AjaxGetFunctionTemplate;
                break;
            }
            ajaxTmpl = String.Format(ajaxTmpl, HasFileUpload(parameters).ToString().ToLower());
            functionBody.AppendLine(ajaxTmpl);

            functionBody.AppendLine("};");
            if (RootNamespace.IsNullOrWhiteSpaceMtn())
            {
                sbWork.AppendFormat("{0}.{1} = {2}", classNamespace, methodName, functionBody.ToString());
            }
            else
            {
                sbWork.AppendFormat("{0}.{1}.{2}  = {3}", RootNamespace, classNamespace, methodName, functionBody.ToString());
            }
            sbWork.AppendLine();
        }
Beispiel #58
0
        void Init()
        {
            DynamicLayout p1, p2;

            StackLayout t1;

            p1 = UI.Shared.Common.GetDefaultContainer();
            p2 = UI.Shared.Common.GetDefaultContainer();

            p1.Width = 380;
            p2.Width = 470;

            t1 = new StackLayout();
            t1.Items.Add(new StackLayoutItem(p1));
            t1.Items.Add(new StackLayoutItem(p2));
            t1.Orientation = Orientation.Horizontal;

            Padding = new Padding(10);

            if (flowsheet.SensAnalysisCollection.Count == 0)
            {
                flowsheet.SensAnalysisCollection.Add(new DWSIM.SharedClasses.Flowsheet.Optimization.SensitivityAnalysisCase());
            }

            mycase = flowsheet.SensAnalysisCollection.First();

            var su = flowsheet.FlowsheetOptions.SelectedUnitSystem;
            var nf = flowsheet.FlowsheetOptions.NumberFormat;

            s.CreateAndAddLabelRow2(this, "Use the Sensitivity Analysis tool to study/analyze the influence of a process variable on other variables in the flowsheet.");

            this.Add(t1);

            s.CreateAndAddLabelRow(p1, "Case ID");
            s.CreateAndAddFullTextBoxRow(p1, mycase.name, (arg3, arg2) => { mycase.name = arg3.Text; });

            s.CreateAndAddLabelRow(p1, "Case Description");
            s.CreateAndAddFullTextBoxRow(p1, mycase.description, (arg3, arg2) => { mycase.description = arg3.Text; });

            s.CreateAndAddLabelRow(p1, "Independent Variable");

            var objlist = flowsheet.SimulationObjects.Values.Select((x2) => x2.GraphicObject.Tag).ToList();

            objlist.Insert(0, "");

            var spinner = s.CreateAndAddDropDownRow(p1, "Object", objlist, 0, null);

            var spinner2 = s.CreateAndAddDropDownRow(p1, "Property", new List <string>(), 0, null);

            List <string> proplist = new List <string>();

            spinner.SelectedIndexChanged += (sender, e) =>
            {
                if (spinner.SelectedIndex > 0)
                {
                    mycase.iv1.objectID  = flowsheet.GetFlowsheetSimulationObject(objlist[spinner.SelectedIndex]).Name;
                    mycase.iv1.objectTAG = objlist[spinner.SelectedIndex];
                    proplist             = flowsheet.GetFlowsheetSimulationObject(objlist[spinner.SelectedIndex]).GetProperties(PropertyType.WR).ToList();
                    proplist.Insert(0, "");
                    spinner2.Items.Clear();
                    spinner2.Items.AddRange(proplist.Select(x => new ListItem {
                        Key = x, Text = flowsheet.GetTranslatedString(x)
                    }).ToList());
                    spinner2.SelectedIndex = (proplist.IndexOf(mycase.iv1.propID));
                }
                else
                {
                    spinner2.Items.Clear();
                }
            };
            if (flowsheet.SimulationObjects.ContainsKey(mycase.iv1.objectID))
            {
                spinner.SelectedIndex = (objlist.IndexOf(flowsheet.SimulationObjects[mycase.iv1.objectID].GraphicObject.Tag));
            }

            var txtLowerLimit = s.CreateAndAddTextBoxRow(p1, nf, "Initial Value", 0, null);
            var txtUpperLimit = s.CreateAndAddTextBoxRow(p1, nf, "Final Value", 0, null);
            var txtSteps      = s.CreateAndAddTextBoxRow(p1, "0", "Number of Steps", 0, null);

            txtLowerLimit.Text = mycase.iv1.lowerlimit.GetValueOrDefault().ToString(nf);
            txtUpperLimit.Text = mycase.iv1.upperlimit.GetValueOrDefault().ToString(nf);
            txtSteps.Text      = mycase.iv1.points.ToString();

            var labelUnits = s.CreateAndAddTwoLabelsRow(p1, "Property Units", "");

            spinner2.SelectedIndexChanged += (sender, e) =>
            {
                if (spinner2.SelectedIndex > 0)
                {
                    mycase.iv1.propID = proplist[spinner2.SelectedIndex];
                    mycase.iv1.unit   = flowsheet.GetFlowsheetSimulationObject(objlist[spinner.SelectedIndex]).GetPropertyUnit(proplist[spinner2.SelectedIndex], su);
                    labelUnits.Text   = mycase.iv1.unit;
                }
            };

            double dummy = 0.0f;

            txtLowerLimit.TextChanged += (sender2, e2) =>
            {
                if (double.TryParse(txtLowerLimit.Text.ToString(), out dummy))
                {
                    mycase.iv1.lowerlimit = Double.Parse(txtLowerLimit.Text);
                }
            };

            txtUpperLimit.TextChanged += (sender2, e2) =>
            {
                if (double.TryParse(txtUpperLimit.Text.ToString(), out dummy))
                {
                    mycase.iv1.upperlimit = Double.Parse(txtUpperLimit.Text);
                }
            };

            txtSteps.TextChanged += (sender2, e2) =>
            {
                if (double.TryParse(txtSteps.Text.ToString(), out dummy))
                {
                    mycase.iv1.points = Int32.Parse(txtSteps.Text);
                }
            };

            s.CreateAndAddEmptySpace(p1);
            s.CreateAndAddEmptySpace(p1);
            s.CreateAndAddEmptySpace(p1);
            s.CreateAndAddEmptySpace(p1);
            s.CreateAndAddEmptySpace(p1);
            s.CreateAndAddEmptySpace(p1);

            var btnAddDepVar = s.CreateAndAddBoldLabelAndButtonRow(p2, "Dependent Variables", "Add New", null, null);

            var ll = new StackLayout {
                Orientation = Orientation.Vertical, Padding = new Eto.Drawing.Padding(2), Spacing = 10
            };

            ll.RemoveAll();

            var sc = new Scrollable {
                Border = BorderType.None, Content = ll
            };

            s.CreateAndAddControlRow(p2, sc);

            t1.SizeChanged += (sender, e) => {
                if (p1.ParentWindow != null)
                {
                    p1.Width  = (int)(p1.ParentWindow.Width / 2 - 10);
                    p2.Width  = (int)(p2.ParentWindow.Width / 2 - 10);
                    p1.Height = p1.ParentWindow.Height - 170;
                    p2.Height = p1.Height;
                    sc.Height = p2.Height - btnAddDepVar.Height - 30;
                    //foreach (var item in ll.Items)
                    //{
                    //    item.Control.Width = sc.Width - 25;
                    //}
                }
            };

            foreach (var dvar in mycase.depvariables.Values)
            {
                AddDepVar(ll, dvar, objlist);
            }

            btnAddDepVar.Click += (sender2, e2) =>
            {
                var depvar = new DWSIM.SharedClasses.Flowsheet.Optimization.SAVariable();
                depvar.id = Guid.NewGuid().ToString();
                mycase.depvariables.Add(depvar.id, depvar);
                AddDepVar(ll, depvar, objlist);
            };

            var btnRun = s.CreateAndAddButtonRow(this, "Run Analysis", null, null);

            var btnAbort = s.CreateAndAddButtonRow(this, "Abort Run", null, null);

            btnAbort.Enabled = false;

            resulttextbox = new TextArea {
                Height = 400, Text = "", Font = Fonts.Monospace(GlobalSettings.Settings.ResultsReportFontSize), ReadOnly = true
            };

            s.CreateAndAddLabelRow(this, "Results");

            var btnrt = s.CreateAndAddLabelAndButtonRow(this, "View Results Report", "View Report", null, (sender, e) =>
            {
                var form = s.GetDefaultEditorForm("Sensitivity Analysis Report", 500, 500, resulttextbox, true);
                form.Show();
            });

            btnrt.Enabled = false;

            resultschart = new Eto.OxyPlot.Plot {
                Height = 400
            };

            var btnrc = s.CreateAndAddLabelAndButtonRow(this, "View Results Chart", "View Chart", null, (sender, e) =>
            {
                var form = s.GetDefaultEditorForm("Sensitivity Analysis Result", 500, 500, resultschart, true);
                form.Show();
            });

            btnrc.Enabled = false;

            s.CreateAndAddEmptySpace(this);
            s.CreateAndAddEmptySpace(this);

            btnRun.Click += (sender2, e2) =>
            {
                int    iv1np, i;
                double iv1ll, iv1ul, iv1val, iv1val0;
                string iv1id, iv1prop;
                List <List <double> > results = new List <List <double> >();

                iv1ll   = Converter.ConvertToSI(mycase.iv1.unit, mycase.iv1.lowerlimit.GetValueOrDefault());
                iv1ul   = Converter.ConvertToSI(mycase.iv1.unit, mycase.iv1.upperlimit.GetValueOrDefault());
                iv1np   = mycase.iv1.points - 1;
                iv1id   = mycase.iv1.objectID;
                iv1prop = mycase.iv1.propID;

                flowsheet.SupressMessages = true;

                Application.Instance.Invoke(() =>
                {
                    btnAbort.Enabled = true;
                    btnrt.Enabled    = false;
                    btnrc.Enabled    = false;
                    flowsheet.ShowMessage("Starting Sensitivity Analysis, please wait...", IFlowsheet.MessageType.Information);
                });

                var task = new Task(() =>
                {
                    flowsheet.SolveFlowsheet(true);

                    iv1val0 = Convert.ToDouble(flowsheet.SimulationObjects[iv1id].GetPropertyValue(iv1prop));

                    for (i = 0; i <= iv1np; i++)
                    {
                        iv1val = iv1ll + i * (iv1ul - iv1ll) / iv1np;
                        flowsheet.SimulationObjects[iv1id].SetPropertyValue(iv1prop, iv1val);
                        flowsheet.SolveFlowsheet(true);
                        List <double> depvarvals = new List <double>();
                        foreach (var depvar in mycase.depvariables.Values)
                        {
                            depvar.currentvalue = Convert.ToDouble(flowsheet.SimulationObjects[depvar.objectID].GetPropertyValue(depvar.propID));
                            depvarvals.Add(depvar.currentvalue);
                        }
                        results.Add(depvarvals);
                    }

                    mycase.results = new System.Collections.ArrayList();

                    foreach (var res in results)
                    {
                        mycase.results.Add(res.ToArray());
                    }

                    flowsheet.SimulationObjects[iv1id].SetPropertyValue(iv1prop, iv1val0);
                    flowsheet.SolveFlowsheet(true);
                }, GlobalSettings.Settings.TaskCancellationTokenSource.Token);

                task.ContinueWith((t) =>
                {
                    flowsheet.SupressMessages = false;

                    if (t.Exception != null)
                    {
                        Application.Instance.Invoke(() =>
                        {
                            btnAbort.Enabled = false;
                            btnrt.Enabled    = false;
                            btnrc.Enabled    = false;

                            flowsheet.ShowMessage("Error: " + t.Exception.Message, IFlowsheet.MessageType.GeneralError);
                        });
                    }
                    else
                    {
                        Application.Instance.Invoke(() =>
                        {
                            btnAbort.Enabled = false;
                            btnrt.Enabled    = true;
                            btnrc.Enabled    = true;

                            flowsheet.ShowMessage("Sensitivity Analysis finished successfully.", IFlowsheet.MessageType.Information);
                            if (t.Status == TaskStatus.RanToCompletion)
                            {
                                var str = new System.Text.StringBuilder();
                                str.AppendLine("Sensitivity Analysis Run Results");
                                str.AppendLine();
                                str.AppendLine("Independent Variable: " + flowsheet.SimulationObjects[iv1id].GraphicObject.Tag + " / " + flowsheet.GetTranslatedString(mycase.iv1.propID));
                                str.AppendLine();
                                str.AppendLine("Range: " + mycase.iv1.lowerlimit.GetValueOrDefault() + " to " + mycase.iv1.upperlimit.GetValueOrDefault() + " " + mycase.iv1.unit + ", " + mycase.iv1.points + " steps");
                                str.AppendLine();
                                str.AppendLine("Dependent Variables:");
                                int count = 1;
                                str.AppendLine();
                                foreach (var dvar in mycase.depvariables.Values)
                                {
                                    str.AppendLine(count + " - " + flowsheet.SimulationObjects[dvar.objectID].GraphicObject.Tag + " / " + flowsheet.GetTranslatedString(dvar.propID) + " (" + dvar.unit + ")");
                                    count += 1;
                                }
                                str.AppendLine();
                                str.AppendLine("Ind var\t\tDep. vars");
                                int cnt                  = 0;
                                List <double> px         = new List <double>();
                                List <List <double> > py = new List <List <double> >();
                                foreach (var dvar in mycase.depvariables.Values)
                                {
                                    py.Add(new List <double>());
                                }
                                foreach (double[] res in mycase.results)
                                {
                                    var dv = Converter.ConvertFromSI(mycase.iv1.unit, iv1ll + cnt * (iv1ul - iv1ll) / iv1np);
                                    px.Add(dv);
                                    string line = dv.ToString(nf) + "\t\t";
                                    int j       = 0;
                                    foreach (var d in res)
                                    {
                                        py[j].Add(Converter.ConvertFromSI(mycase.depvariables.Values.ElementAt(j).unit, d));
                                        line += Converter.ConvertFromSI(mycase.depvariables.Values.ElementAt(j).unit, d).ToString(nf) + "\t\t";
                                        j    += 1;
                                    }
                                    str.AppendLine(line);
                                    cnt += 1;
                                }

                                Application.Instance.Invoke(() => resulttextbox.Text = str.ToString());

                                var model = new PlotModel()
                                {
                                    Subtitle = "Sensitivity Analysis Run Results", Title = flowsheet.FlowsheetOptions.SimulationName
                                };
                                model.TitleFontSize    = 14;
                                model.SubtitleFontSize = 11;
                                model.Axes.Add(new LinearAxis()
                                {
                                    MajorGridlineStyle = LineStyle.Dash,
                                    MinorGridlineStyle = LineStyle.Dot,
                                    Position           = AxisPosition.Bottom,
                                    FontSize           = 12,
                                    Title = mycase.iv1.objectTAG + " / " + flowsheet.GetTranslatedString(mycase.iv1.propID) + " (" + mycase.iv1.unit + ")"
                                });
                                int cnt2 = 0;
                                foreach (var dvar in mycase.depvariables.Values)
                                {
                                    model.Axes.Add(new LinearAxis()
                                    {
                                        MajorGridlineStyle = LineStyle.Dash,
                                        MinorGridlineStyle = LineStyle.Dot,
                                        FontSize           = 12,
                                        Title = dvar.objectTAG + " / " + flowsheet.GetTranslatedString(dvar.propID) + " (" + dvar.unit + ")"
                                    });
                                    model.Axes[cnt2 + 1].Key           = cnt2.ToString();
                                    model.Axes[cnt2 + 1].PositionTier  = cnt2;
                                    model.Axes[cnt2 + 1].AxislineStyle = LineStyle.Solid;
                                    model.AddLineSeries(px, py[cnt2]);
                                    model.Series[cnt2].Title = dvar.objectTAG + " / " + flowsheet.GetTranslatedString(dvar.propID);
                                    ((OxyPlot.Series.LineSeries)(model.Series[cnt2])).YAxisKey = cnt2.ToString();
                                    cnt2 += 1;
                                }
                                model.LegendFontSize           = 11;
                                model.LegendPlacement          = LegendPlacement.Outside;
                                model.LegendOrientation        = LegendOrientation.Vertical;
                                model.LegendPosition           = LegendPosition.BottomCenter;
                                model.TitleHorizontalAlignment = TitleHorizontalAlignment.CenteredWithinView;

                                Application.Instance.Invoke(() => { resultschart.Model = model; resultschart.Invalidate(); });
                            }
                        });
                    }
                });

                btnAbort.Click += (sender, e) =>
                {
                    GlobalSettings.Settings.TaskCancellationTokenSource.Cancel();
                };

                task.Start();
            };
        }
Beispiel #59
0
        public void SetPieceToggleText(Enums.Piece piece)
        {
            System.Text.StringBuilder tooltip = new System.Text.StringBuilder();
            switch (piece)
            {
            case Enums.Piece.Pawn:
                //ToggleDisable();
                _isPawn = true;
                tooltip.Append("Pawn");
                tooltip.AppendLine("No bonuses");
                //PieceToggle.image.sprite = ImgPawn;
                break;

            case Enums.Piece.Bishop:
                tooltip.Append("Bishop");
                tooltip.AppendLine("OFF: Start battle with 100% mana");
                tooltip.AppendLine("ON: Get 2X mana");
                //PieceToggle.image.sprite = ImgBishop;
                break;

            case Enums.Piece.Knight:
                tooltip.Append("Knight");
                tooltip.AppendLine("Passive: get bonus attack speed");
                tooltip.AppendLine("OFF: Transcend grand distances quickly");
                tooltip.AppendLine("ON: Double the Range");
                //PieceToggle.image.sprite = ImgKnight;
                break;

            case Enums.Piece.Rook:
                tooltip.Append("Rook");
                tooltip.AppendLine("Passive: get bonus attack damage");
                tooltip.AppendLine("OFF: Bonus armor, magic resist and attack damage");
                tooltip.AppendLine("ON: Higher bonuses but unable to cast abilities");
                //PieceToggle.image.sprite = ImgRook;
                break;

            case Enums.Piece.Queen:
                tooltip.Append("Queen");
                tooltip.AppendLine("OFF: Bonus on all stats");
                tooltip.AppendLine("ON: On start of the battle get shield equal to 100% of HP");
                //PieceToggle.image.sprite = ImgQueen;
                break;
            }
            //PieceToggle.GetComponent<FigureTooltip>().SetTooltip(tooltip.ToString());
        }
Beispiel #60
0
        private static void InsertIntoMOFMaklumatSyarikat()
        {
            using (SqlConnection Connection = SQLHelper.GetConnectionMOF())
            {
                try
                {
                    SqlCommand com = new SqlCommand();
                    System.Text.StringBuilder sql = new System.Text.StringBuilder();
                    sql.AppendLine("INSERT INTO AccountCluster ");
                    sql.AppendLine("(");
                    sql.AppendLine("[CompanyName],[MSCFileID],[CoreActivities],[ROCNumber],[URL],[ACMeetingDate],[ApprovalLetterDate]");
                    sql.AppendLine(",[YearOfApproval],[DateofIncorporation],[OperationalStatus] ,[FinancialIncentive] ,[Cluster],[BusinessPhone]");
                    sql.AppendLine(",[Fax],[TaxRevenueLoss],[Tier],[SubmitDate],[MSCCertNo],[BA],[SubmitType],[SyncDate]");
                    sql.AppendLine(")");
                    sql.AppendLine("VALUES(");
                    sql.AppendLine("@CompanyName, @MSCFileID, @CoreActivities, @ROCNumber,@URL,@ACMeetingDate,@ApprovalLetterDate");
                    sql.AppendLine("@YearOfApproval, @DateofIncorporation, @OperationalStatus, @FinancialIncentive, @Cluster, @BusinessPhone");
                    sql.AppendLine("@Fax, @TaxRevenueLoss, @Tier, @SubmitDate, @MSCCertNo, @BA,@SubmitType,@SyncDate");
                    sql.AppendLine(")");

                    com.Parameters.Add(new SqlParameter("@CompanyName", ""));
                    com.Parameters.Add(new SqlParameter("@MSCFileID", ""));
                    com.Parameters.Add(new SqlParameter("@CoreActivities", ""));
                    com.Parameters.Add(new SqlParameter("@ROCNumber", ""));
                    com.Parameters.Add(new SqlParameter("@URL", ""));
                    com.Parameters.Add(new SqlParameter("@ACMeetingDate", ""));
                    com.Parameters.Add(new SqlParameter("@ApprovalLetterDate", ""));
                    com.Parameters.Add(new SqlParameter("@DateofIncorporation", ""));
                    com.Parameters.Add(new SqlParameter("@OperationalStatus", ""));
                    com.Parameters.Add(new SqlParameter("@FinancialIncentive", ""));
                    com.Parameters.Add(new SqlParameter("@Cluster", ""));
                    com.Parameters.Add(new SqlParameter("@BusinessPhone", ""));
                    com.Parameters.Add(new SqlParameter("@Fax", ""));
                    com.Parameters.Add(new SqlParameter("@TaxRevenueLoss", ""));
                    com.Parameters.Add(new SqlParameter("@Tier", ""));
                    com.Parameters.Add(new SqlParameter("@SubmitDate", ""));
                    com.Parameters.Add(new SqlParameter("@MSCCertNo", ""));
                    com.Parameters.Add(new SqlParameter("@BA", ""));
                    com.Parameters.Add(new SqlParameter("@SubmitType", ""));
                    com.Parameters.Add(new SqlParameter("@SyncDate", ""));

                    com.CommandText    = sql.ToString();
                    com.CommandType    = CommandType.Text;
                    com.Connection     = Connection;
                    com.CommandTimeout = int.MaxValue;
                    com.ExecuteNonQuery();
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }