ToString() public method

public ToString ( ) : string
return string
Example #1
0
        public static EditProblemViewModel GetEditProblemViewModel(Problem problem)
        {
            var epvm = new EditProblemViewModel();
            epvm.Author = problem.Author.UserName;
            epvm.Name = problem.Name;
            epvm.Text = problem.Text;
            epvm.SelectedCategoryId = problem.CategoryId;
            epvm.IsBlocked = problem.IsBlocked;

            var sb = new StringBuilder();
            foreach (var tag in problem.Tags)
            {
                sb.Append(tag.Name);
                sb.Append(',');
            }

            epvm.TagsString = sb.ToString();

            sb.Clear();

            foreach (var ans in problem.CorrectAnswers)
            {
                sb.Append(ans.Text);
                sb.Append(';');
            }

            sb.Remove(sb.Length - 1, 1);
            epvm.Answers = sb.ToString();

            return epvm;
        }
        public override TokenStream TokenStream(string fieldName, TextReader reader)
        {
            string str = reader.ReadToEnd();
            StringBuilder builder = new StringBuilder(str);
            builder.Replace('.', ' ');
            builder.Replace('<', ' ');
            builder.Replace('>', ' ');
            builder.Replace('[', ' ');
            builder.Replace(']', ' ');
            builder.Replace('(', ' ');
            builder.Replace(')', ' ');
            builder.Replace(',', ' ');

            builder.Replace("  ", " ");

            str = builder.ToString();
            
            for (int i = builder.Length - 1; i > 0; i--)
            {
                if (char.IsUpper(builder[i]))
                    builder.Insert(i, ' ');
            }

            builder.Append(' ').Append(str);

            return new LowerCaseFilter(new WhitespaceTokenizer(new StringReader(builder.ToString())));
        }
Example #3
0
 public static string GetSignature(string name, MosaMethodSignature sig, bool shortSig)
 {
     StringBuilder result = new StringBuilder();
     if (shortSig)
     {
         result.Append(name);
         result.Append("(");
         for (int i = 0; i < sig.Parameters.Count; i++)
         {
             if (i != 0)
                 result.Append(", ");
             result.Append(sig.Parameters[i].ParameterType.Name);
         }
         result.Append(") : ");
         result.Append(sig.ReturnType.Name);
         return result.ToString();
     }
     else
     {
         result.Append(sig.ReturnType.FullName);
         result.Append(" ");
         result.Append(name);
         result.Append("(");
         for (int i = 0; i < sig.Parameters.Count; i++)
         {
             if (i != 0)
                 result.Append(", ");
             result.Append(sig.Parameters[i].ParameterType.FullName);
         }
         result.Append(")");
         return result.ToString();
     }
 }
 public static IEnumerable<string> BreakToWords(this string text)
 {
     var stringBuilder = new StringBuilder();
     bool flag = true;
     foreach (char ch in text)
     {
         switch (ch)
         {
             case ' ':
             case '\t':
             case '\n':
             case '\r':
             case NBSP:
                 if (flag)
                 {
                     if (stringBuilder.Length > 0)
                     {
                         yield return stringBuilder.ToString();
                         stringBuilder.Remove(0, stringBuilder.Length);
                     }
                     yield return string.Empty;
                     flag = false;
                 }
                 break;
             default:
                 flag = true;
                 stringBuilder.Append(ch);
                 break;
         }
     }
     if (stringBuilder.Length > 0)
     {
         yield return stringBuilder.ToString();
     }
 }
        protected override void CreateSign()
        {
            StringBuilder sb = new StringBuilder();

            ArrayList akeys = new ArrayList();
            akeys.Add("spid");
            akeys.Add("trans_time");
            akeys.Add("stamp");
            akeys.Add("cft_signtype");
            akeys.Add("mchtype");


            foreach (string k in akeys)
            {
                string v = (string)Parameters[k];
                if (null != v && "".CompareTo(v) != 0
                    && "sign".CompareTo(k) != 0 && "key".CompareTo(k) != 0)
                {
                    sb.Append(k + "=" + v + "&");
                }
            }

            sb.Append("key=" + this.GetKey());
            string sign = MD5UtilHelper.GetMD5(sb.ToString(), GetCharset()).ToLower();

            this.SetParameter("sign", sign);

            //debug信息
            this.SetDebugInfo(sb.ToString() + " => sign:" + sign);
        }
        public static string Describe(this IColorSwitchState state)
        {
            var result = new StringBuilder();

            if (state == null)
            {
                return result.ToString();
            }

            if (state.Value == null)
            {
                result.Append("Unknown Color");
            }
            else
            {
                var color = state.Value;

                result.Append(color.ToHexString());

                var name = color.Name;

                if (name != null && name.Value != null)
                {
                    result.Append("(");
                    result.Append(name.Value);
                    result.Append(")");
                }
            }

            return result.ToString();
        }
Example #7
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        M_InfoModel info = InfoModelBll.GetModel(2);
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        int maxWidth = Function.CheckNumber(txtMaxWidth.Text) == true ? int.Parse(txtMaxWidth.Text) : 0;
        int maxHeight = Function.CheckNumber(txtMaxHeight.Text) == true ? int.Parse(txtMaxHeight.Text) : 0;
        int bili = Function.CheckNumber(txtBili.Text) == true ? int.Parse(txtBili.Text) : 0;
        for (int i = 1; i < 13; i++)
        {
            HtmlInputFile file = Page.FindControl("File" + i) as HtmlInputFile;
            if (file.PostedFile != null && file.PostedFile.FileName != "")
            {
                B_UpLoadPic up = new B_UpLoadPic();
                string imgName = up.GetUpLoadPicPath(file, picSavePath, IsWatermark.Checked, IsNewSize.Checked, maxWidth, maxHeight, IsBiLi.Checked, bili,info.UploadSize);
                sb.Append(imgName);
                sb.Append(",");
            }
        }

        //返回文件名
        if (sb.ToString() == "")
        {
            LitMsg.Text = "<script type='text/javascript'>alert('未上传任何图片')</script>";
            return;
        }
        else
        {
            imgNames.Text = sb.ToString();
            btnReturnValue.Visible = true;
            btnUpload.Visible = false;
        }
    }
Example #8
0
 /// <summary>
 /// 删除
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void Delete_Click(object sender, ImageClickEventArgs e)
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     for (int i = 0; i < rpt_userinfo.Items.Count; i++)
     {
         CheckBox chk = rpt_userinfo.Items[i].FindControl("chkPro") as CheckBox;
         if (chk.Checked)
         {
             HiddenField hidd = rpt_userinfo.Items[i].FindControl("hiddId") as HiddenField;
             sb.Append(hidd.Value + ",");
         }
     }
     if (sb.Length == 0)
     {
         ScriptManager.RegisterStartupScript(Page, typeof(Page), "ListArea", "alert('您没有选择任何项');", true);
         return;
     }
     else
     {
         try
         {
             UserManageBLL.Delete(sb.ToString().Substring(0,sb.ToString().Length-1));
             LoadDataBind(strWhere);
         }
         catch
         {
             ScriptManager.RegisterStartupScript(Page, typeof(Page), "ListArea", "alert('出现错误!请重新尝试!');", true);
         }
     }
 }
Example #9
0
        public string BuildMessage(List<JiraModel> sameJiraIssueKeyEvents)
        {
            var stringBuilder = new StringBuilder();

            var firstEvent = sameJiraIssueKeyEvents.First();

            if (CreatedIssueThenUpdated(sameJiraIssueKeyEvents, firstEvent))
            {
                BuildIssueCreatedMessage(firstEvent, stringBuilder);

                return stringBuilder.ToString();
            }

            if (OnlyUpdatedIssue(sameJiraIssueKeyEvents))
            {
                BuildChangeLogMessage(sameJiraIssueKeyEvents.Last(), stringBuilder);

                return stringBuilder.ToString();
            }

            switch (firstEvent.webhookEvent)
            {
                case "jira:issue_created":
                    BuildIssueCreatedMessage(firstEvent, stringBuilder);
                    break;

                case "jira:issue_updated":
                    BuildChangeLogMessage(firstEvent, stringBuilder);
                    break;
            }

            return stringBuilder.ToString();
        }
Example #10
0
 public static string NumberToWords(int number)
 {
     int thousands = number / 1000;
     int hundreds = (number % 1000) / 100;
     int belowHundredRemainder = (number % 1000) % 100;
     int scores = ((number % 1000) % 100) / 10;
     int digits = ((number % 1000) % 100) % 10;
     var stringBuilder = new StringBuilder();
     if (thousands > 0) {
         stringBuilder.AppendFormat("{0} thousand", Numerals[thousands - 1]);
     }
     if (hundreds > 0) {
         if (stringBuilder.Length > 0) stringBuilder.Append(" and ");
         stringBuilder.AppendFormat("{0} hundred", Numerals[hundreds - 1]);
     }
     if (belowHundredRemainder == 0) return stringBuilder.ToString();
     if (belowHundredRemainder < 20) {
         //1-19 special case
         if (stringBuilder.Length > 0) stringBuilder.AppendFormat(" and ");
         stringBuilder.Append(Numerals[belowHundredRemainder - 1]);
     }
     else {
         //20-99
         if (stringBuilder.Length > 0) stringBuilder.Append(" and ");
         if (scores > 0) {
             stringBuilder.AppendFormat("{0}", Scores[scores - 1]);
         }
         if (digits > 0) {
             if(scores>0) stringBuilder.Append("-");
             stringBuilder.Append(Numerals[digits - 1]);
         }
     }
     return stringBuilder.ToString();
 }
Example #11
0
        public IEnumerable<string> Wrap(string input)
        {
            var builder = new StringBuilder();
            int pos = 0;
            var result = new List<string>();
            foreach (var chr in input)
            {
                if (!(chr == ' ' && pos == 0))
                {
                    builder.Append(chr);
                    ++pos;
                    if (pos == rowLength)
                    {
                        result.Add(builder.ToString());
                        builder.Clear();
                        pos = 0;
                    }
                }
            }

            if(builder.Length > 0)
                result.Add(builder.ToString());

            return result.AsReadOnly();
        }
        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());
            }
        }
Example #13
0
File: Js.cs Project: pczy/Pub.Class
 /// <summary>
 /// 运行JS代码
 /// </summary>
 /// <param name="Page">指定Page</param>
 /// <param name="strCode">要注册的代码</param>
 /// <param name="isTop">是否在头部/否则在尾部</param>
 /// <param name="IDStr">Key</param>
 public static void Run(System.Web.UI.Page Page, string strCode, bool isTop, string IDStr) {
     StringBuilder sb = new StringBuilder();
     sb.Append("<script language=\"javascript\">\n");
     sb.Append(strCode.Trim());
     sb.Append("\n</script>\n");
     if (isTop) Page.RegisterClientScriptBlock(IDStr, sb.ToString()); else Page.RegisterStartupScript(IDStr, sb.ToString());
 }
Example #14
0
 protected override void ExecuteTask()
 {
     //Check the file exists
     string docPath = Project.ExpandProperties(_xmldoc, Location).Replace(@"file:\", "");
     if (!File.Exists(docPath))
     {
         throw new BuildException("The xml document specified does not exist");
     }
     // Load the document and run the selection
     XmlDocument doc = new XmlDocument();
     doc.Load(docPath);
     XmlNodeList list = doc.SelectNodes(_selection);
     Project.Log(Level.Info, "Found " + list.Count.ToString() + " nodes");
     StringBuilder builder = new StringBuilder();
     foreach (XmlNode node in list)
     {
         builder.Append(node.InnerText);
         builder.Append(",");
     }
     if (builder.Length > 0)
     {
         builder.Length -= 1;
     }
     if (Project.Properties.Contains(_property))
     {
         Project.Properties[_property] = builder.ToString();
     }
     else
     {
         Project.Properties.Add(_property, builder.ToString());
     }
 }
        private string RunInternal(string arguments, string fileName)
        {
            StringBuilder result = new StringBuilder();

            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = Path.Combine(typeof(MediaConvertor).Assembly.GetAssemblyDirectory(), string.Format(@"AVConv\{0}", fileName));
            startInfo.Arguments = arguments;
            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;

            process.StartInfo = startInfo;
            process.ErrorDataReceived += (sender, args) => Common.Log.Error("Error during video converion: '{0}'", args.Data);
            process.OutputDataReceived += (sender, args) => Common.Log.Debug("Video converting: {0}", args.Data);
            process.Start();
            while (!process.StandardError.EndOfStream)
            {
                string line = process.StandardError.ReadLine();
                result.AppendLine(line);
                Common.Log.Debug("Video converting: {0}", line);
            }

            process.WaitForExit();

            if (process.ExitCode != 0)
                throw new AvConvException("File converion failed", result.ToString());

            return result.ToString();
        }
        public void Add(ITraceEvent traceEvent)
        {
            var message = new StringBuilder();
            if (HttpContext.Current != null)
            {
                message.Append("During HTTP request to: ");
                message.Append(HttpContext.Current.Request.Url);
                message.AppendLine();
            }

            message.Append("Instance ");
            message.Append(traceEvent.Source.TraceId);
            message.Append(" of type ");
            message.Append(traceEvent.Source.GetType());
            message.Append(" reported: ");
            message.Append(traceEvent.Message);
            message.AppendLine();

            if (traceEvent.IsError)
            {
                log.Error(message.ToString());
            }
            else
            {
                log.Debug(message.ToString());
            }
        }
Example #17
0
        private static IDictionary<string, string> ParseProperties(IEnumerable<Symbol> header)
        {
            IDictionary<string, string> result = new Dictionary<string, string>();
            StringBuilder data = new StringBuilder();
            string previous = string.Empty;
            foreach (Symbol sym in header)
            {
                if (IsProperty(sym))
                {
                    if (previous != null)
                    {
                        result.Add(previous, data.ToString());
                    }

                    previous = sym.ToString();
                    data.Length = 0;
                    continue;
                }
                
                if (sym == Symbol.Assign)
                {
                    break;
                }

                data.Append(sym.ToString());
            }

            if (previous != null)
            {
                result.Add(previous, data.ToString());
            }

            return result;
        }
Example #18
0
      public Image GetImageFromCache(GMapType type, Point pos, int zoom, string language)
      {
         Image ret = null;
         try
         {
            StringBuilder dir = new StringBuilder(tileCache);
            dir.AppendFormat("{0}{1}{2}{3}{4}{5}{6}{7}", zoom, Path.DirectorySeparatorChar, language, Path.DirectorySeparatorChar, pos.X, Path.DirectorySeparatorChar, pos.Y, Path.DirectorySeparatorChar);
            {
               dir.AppendFormat("{0}.png", type.ToString());
            }

            if(File.Exists(dir.ToString()))
            {
               FileInfo f = new FileInfo(dir.ToString());
               if(f.Length == 0)
               {
                  f.Delete();
               }
               else
               {
                  using(FileStream s = f.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                  {
                     ret = Image.FromStream(s);
                     s.Close();
                  }
               }
            }
         }
         catch
         {
            ret = null;
         }

         return ret;
      }
        private static void NullableTypesTests()
        {
            Console.WriteLine("--- {0} ---", System.Reflection.MethodBase.GetCurrentMethod().Name);
            int?i = null;

            Console.WriteLine(i == null);
            // Translates to
            Nullable <int> j = new Nullable <int>();

            Console.WriteLine(j.HasValue);
            object o = "string";
            int?   x = o as int?;

            Console.WriteLine(x.HasValue);
            Console.WriteLine(null == null);                // True
            Console.WriteLine((bool?)null == (bool?)null);  // True
            bool?n = null, f = false, t = true;

            Console.WriteLine("Null | Null  = {0}", n | n); // (null)
            Console.WriteLine("Null | False = {0}", n | f); // (null)
            Console.WriteLine("Null | True  = {0}", n | t); // True
            Console.WriteLine("Null & Null  = {0}", n & n); // (null)
            Console.WriteLine("Null & False = {0}", n & f); // False
            Console.WriteLine("Null & True  = {0}", n & t); // (null)
            int?z = null;
            int y = z ?? 5;                                 // y is 5
            int?a = null, b = null, c = 123;

            Console.WriteLine("a (null) ?? b (null) ?? c (123) = {0}", a ?? b ?? c);     // 123
            System.Text.StringBuilder sb = null;
            int?length  = sb?.ToString().Length;
            int length2 = sb?.ToString().Length ?? 0;

            Console.WriteLine("=====================================================================");
        }
 public string GetValue(string section, string key)
 {
     var temp = new StringBuilder (255);
     GetPrivateProfileString (section, key, "", temp, 255, _path);
     if (temp.ToString () == "") throw new Exception ("Key has empty Value");
     return temp.ToString ();
 }
        /// <summary>
        /// Loads the profile data for all users from the steam service
        /// </summary>
        /// <returns>The async task context.</returns>
        public async Task LoadSteamAsync(string apiKey)
        {
            var builder = new StringBuilder();
            for (var i = 0; i < Players.Count; i++)
                builder.Append(Players[i].SteamId + ",");

            using (var client = new HttpClient())
            {
                client.BaseAddress = new System.Uri("https://api.steampowered.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = await client.GetAsync(string.Format("ISteamUser/GetPlayerSummaries/v0002/?key={0}&steamids={1}", apiKey, builder.ToString()));
                if (response.IsSuccessStatusCode)
                    using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        LinkSteamProfiles(await reader.ReadToEndAsync());
                    }
                else
                    throw new System.Exception("The Steam API request was unsuccessful. Are you using a valid key?");

                response = await client.GetAsync(string.Format("ISteamUser/GetPlayerBans/v1/?key={0}&steamids={1}", apiKey, builder.ToString()));
                if (response.IsSuccessStatusCode)
                    using (var reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        LinkSteamBans(await reader.ReadToEndAsync());
                    }
                else
                    throw new System.Exception("The Steam API request was unsuccessful. Are you using a valid key?");
            }
            SteamLoaded = true;
        }
        public void AppendIntTest()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
              StringBuilder stringBuilder = new StringBuilder();

              stringBuilder.AppendNumber(1234567890);
              Assert.AreEqual("1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(-1234567890);
              Assert.AreEqual("-1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.None);
              Assert.AreEqual("1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.PositiveSign);
              Assert.AreEqual("+1234567890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.NumberGroup);
              Assert.AreEqual("1,234,567,890", stringBuilder.ToString());

              stringBuilder.Clear();
              stringBuilder.AppendNumber(1234567890, AppendNumberOptions.PositiveSign | AppendNumberOptions.NumberGroup);
              Assert.AreEqual("+1,234,567,890", stringBuilder.ToString());
        }
Example #23
0
                public string ProtocoloBinario()
                {
                        System.Text.StringBuilder Comando = new System.Text.StringBuilder();
                        Comando.Append(CaracteresDeControl.PROTO_STX);      // STX Start of Frame

                        Comando.Append((char)Secuencia); // SN Sequence Number


                        byte[] Cmd = new byte[1] { (byte)CodigoComando };
                        Comando.Append(DefaultEncoding.GetChars(Cmd)); // Comando

                        if (Campos != null && Campos.Length > 0) {
                                // Params
                                foreach (string Param in Campos) {
                                        Comando.Append(CaracteresDeControl.PROTO_FS); // FS Field Separator
                                        Comando.Append(Param);
                                }
                        }

                        Comando.Append(CaracteresDeControl.PROTO_ETX);	// ETX End of Frame

                        //Calculo el BCC
                        long BCC = 0;
                        byte[] ComandoBytes = DefaultEncoding.GetBytes(Comando.ToString());
                        for (int n = 0; n < ComandoBytes.Length; n++) {
                                BCC += ComandoBytes[n];
                        }
                        Comando.Append(System.Convert.ToString(BCC, 16).ToUpper().PadLeft(4, '0'));

                        return Comando.ToString();
                }
Example #24
0
File: MD5.cs Project: mbsky/albian
        /// <summary>
        /// MD5加密字符串.
        /// </summary>
        /// <param name="input">需要加密的字符串.</param>
        /// <param name="bit">加密的位数.</param>
        /// <param name="isUpper">加密的结果是否需要大写.</param>
        /// <returns>经过MD5加密的字符串</returns>
        public static string Encrypt(string input, MD5Mode bit, bool isUpper)
        {
            var md5 = new MD5CryptoServiceProvider();
            byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));
            var stringBuilder = new StringBuilder();

            switch (bit)
            {
                case MD5Mode.Low:
                    {
                        for (int i = 4; i <= 11; i++)
                        {
                            stringBuilder.Append(data[i].ToString("x2"));
                        }
                        break;
                    }
                case MD5Mode.High:
                    {
                        for (int i = 0; i <= 15; i++)
                        {
                            stringBuilder.Append(data[i].ToString("x2"));
                        }
                        break;
                    }
            }
            if (isUpper)
                return stringBuilder.ToString().ToUpper();
            return stringBuilder.ToString().ToLower();
        }
Example #25
0
 public int Add(Person model)
 {
     StringBuilder strSql = new StringBuilder();
     strSql.Append("insert into Person(");
     strSql.Append("username,password,age,registerDate,address)");
     strSql.Append(" values (");
     strSql.Append("@username,@password,@age,@registerDate,@address)");
     //
     DbHelperSql.Insert(strSql.ToString(), model);
     //
     DbHelperSql.InsertReturnId(strSql.ToString(), model);
     //
     var mList=new List<Person>();
     mList.Add(new Person() {age = 1});
     mList.Add(new Person() {age = 1});
     mList.Add(new Person() {age = 1});
     DbHelperSql.InsertBatch(strSql.ToString(), mList);
     //
     var modeList = new List<Person>();
     for (int i = 0; i < 1000000; i++)
     {
         modeList.Add(new Person() {age = i,username = "******",address = "address",password = "******" });
     }
     DbHelperSql.InsertBatchBySqlBulkCopy(modeList);
     //
     return 1;
 }
        public IEnumerable<string> GetEdgesCsv(IEnumerable<OnergeDetay> onergeDetays)
        {
            // SOURCE_NODE_TYPE, SOURCE_NODE_NAME, EDGE_TYPE, TARGET_NODE_TYPE, TARGET_NODE_NAME, WEIGHT
            var quote = "\"";

            var nodes = new HashSet<string>();
            int batchCount = 1;

            var ret = new StringBuilder();

            foreach (var detay in onergeDetays)
            {
                if (nodes.Count + 3 >= batchCount * 500)
                {
                    yield return ret.ToString();

                    batchCount++;
                    ret.Clear();
                }

                ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Milletvekili", detay.OnergeninSahibi, "UYE", "Parti", detay.Parti, 1);
                ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Milletvekili", detay.OnergeninSahibi, "SAHIP", "Soru Önergesi", detay.EsasNumarasi, 1);
                ret.AppendFormat("{0}, {1}, {2}, {3}, {4}, {5}\n", "Soru Önergesi", quote + detay.EsasNumarasi + quote, "MUHATAP", "Bakan", quote + detay.OnergeninMuhatabi + quote, 1);

                nodes.Add(detay.OnergeninSahibi);
                nodes.Add(detay.Parti);
                nodes.Add(detay.EsasNumarasi);
                nodes.Add(detay.OnergeninMuhatabi);
            }

            yield return ret.ToString();
        }
Example #27
0
        public CipherDecoder(string secretCode, string cipher)
        {
            cipherItems = new List<CipherItem>();

            StringBuilder currentCipher = new StringBuilder();
            char lastChar = '\0';
            foreach (char ch in cipher)
            {
                if (ch >= 'A' && ch <= 'Z')
                {
                    if (currentCipher.Length > 0)
                    {
                        cipherItems.Add(new CipherItem(lastChar, currentCipher.ToString()));
                        currentCipher.Clear();
                    }
                    lastChar = ch;
                }
                else
                {
                    currentCipher.Append(ch);
                }
            }
            if (currentCipher.Length > 0)
            {
                cipherItems.Add(new CipherItem(lastChar, currentCipher.ToString()));
            }

            this.secretCode = secretCode;
        }
Example #28
0
        /// <summary>
        /// Execute any update statements required to clear data, followed by delete statements for all tables.
        /// </summary>
        /// <param name="updateCommands">Update commands to execute</param>
        /// <param name="tables">Tables to delete from</param>
        /// <param name="timeout">Maximum time for a statement</param>
        /// <param name="deleteBatch">Batch delete statements into groups, saves times on databases with large numbers of tables.</param>
        public void Zap(IEnumerable<string> updateCommands, IEnumerable<string> tables, int timeout = 30, int deleteBatch = 1)
        {
            foreach (var item in updateCommands)
            {
                dao.ExecuteNonQuery(item, timeout);
            }

            var sb = new StringBuilder();
            var count = 0;
            foreach (var item in tables)
            {
                sb.AppendLine(string.Format("DELETE FROM {0};", item));
                count++;
                if (count % deleteBatch != 0)
                {
                    continue;
                }

                dao.ExecuteNonQuery(sb.ToString(), timeout);
                sb.Clear();
            }

            var lastCmd = sb.ToString();
            if (!string.IsNullOrEmpty(lastCmd))
            {
                dao.ExecuteNonQuery(lastCmd, timeout);
            }
        }
        public static IEnumerable<string> GetItemsFromDelimitedString(string s)
        {
            bool escaped = false;
            var sb = new StringBuilder();

            foreach (char c in s)
            {
                if ((c == '\\') && !escaped)
                {
                    escaped = true;
                }
                else if ((c == ',') && !escaped)
                {
                    yield return sb.ToString();
                    sb.Length = 0;
                }
                else
                {
                    sb.Append(c);
                    escaped = false;
                }
            }

            yield return sb.ToString();
        }
Example #30
0
        public async Task put_blob_70MB()
        {
            var containerName = "testContainer";
            var blobKey = "testKey";

            using (var client = new RavenAzureClient(AzureAccountName, AzureAccountKey, containerName, isTest: true))
            {
                await client.PutContainer();
                var sb = new StringBuilder();
                for (var i = 0; i < 70 * 1024 * 1024; i++)
                {
                    sb.Append("a");
                }

                await client.PutBlob(blobKey, new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())),
                    new Dictionary<string, string>
                    {
                        {"property1", "value1"},
                        {"property2", "value2"}
                    });

                var blob = await client.GetBlob(blobKey);
                Assert.NotNull(blob);

                using (var reader = new StreamReader(blob.Data))
                    Assert.Equal(sb.ToString(), reader.ReadToEnd());

                var property1 = blob.Metadata.Keys.Single(x => x.Contains("property1"));
                var property2 = blob.Metadata.Keys.Single(x => x.Contains("property2"));

                Assert.Equal("value1", blob.Metadata[property1]);
                Assert.Equal("value2", blob.Metadata[property2]);
            }
        }
Example #31
0
 /// <summary>
 /// Разбить на слова.
 /// </summary>
 /// <param name="src">Исходная строка.</param>
 /// <returns>Разбитая на слова строка.</returns>
 public IEnumerable<string> Split(string src)
 {
     var sb = new StringBuilder();
     for (int i = 0; i < src.Length; i++)
     {
         var ch = src[i];
         if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n')
         {
             sb.Append(' ');
             yield return sb.ToString();
             sb.Clear();
         }
         else
         {
             sb.Append(ch);
             //if (ch == '.' || ch == ',' || ch == ':' || ch == '/' || ch == '\\' || ch == '#' || ch =='?' || ch == '!' || ch == '*' || ch == '-')
             if (char.IsPunctuation(ch) || ch == '.' || ch == ',' || ch == ':' || ch == '/' || ch == '\\' || ch == '#' || ch == '?' || ch == '!' || ch == '*' || ch == '-')
             {
                 yield return sb.ToString();
                 sb.Clear();
             }
         }
     }
     if (sb.Length > 0)
     {
         yield return sb.ToString();
     }
 }
Example #32
0
        /// <summary>
        /// An extension method to join an array of strings with a separator. Sort of a fluent
        /// interface for System.string.Join.
        /// </summary>
        /// <param name="parts">The strings to join.</param>
        /// <param name="separator">The separator to insert between each string value. Defaults to the empty string.</param>
        /// <returns>The joined string.</returns>
        public static string Join(this string[] parts, string separator)
        {
            if (parts is null)
            {
                throw new ArgumentNullException(nameof(parts));
            }

            if (parts.Length == 0)
            {
                return(string.Empty);
            }

            if (separator is null)
            {
                separator = string.Empty;
            }

            var sb = new Text.StringBuilder(parts[0]);

            for (var i = 1; i < parts.Length; ++i)
            {
                sb.Append(separator)
                .Append(parts[i]);
            }

            return(sb.ToString());
        }
Example #33
0
        internal static string EscapeDisplayName(string internalName)
        {
            // initial capacity = length of internalName.
            // Maybe we won't have to escape anything.
            var res = new Text.StringBuilder(internalName.Length);

            foreach (char c in internalName)
            {
                switch (c)
                {
                case '+':
                case ',':
                case '[':
                case ']':
                case '*':
                case '&':
                case '\\':
                    res.Append('\\').Append(c);
                    break;

                default:
                    res.Append(c);
                    break;
                }
            }
            return(res.ToString());
        }
            public CreationInfo(string customMessage, IEnumerable <Exception> innerExceptions)
            {
                var exceptions = new List <Exception>();
                var result     = new Text.StringBuilder(string.Format(_baseMessage, customMessage));
                var first      = true;

                _exception = null;
                foreach (var exception in innerExceptions)
                {
                    if (exception == null)
                    {
                        throw new ArgumentException("An element of innerExceptions is null.");
                    }
                    if (first)
                    {
                        _exception = exception;
                        first      = false;
                    }
                    exceptions.Add(exception);
                    result.Append(Environment.NewLine);
                    result.Append("[ ");
                    result.Append(exception);
                    result.Append(" ]");
                    result.Append(Environment.NewLine);
                }
                _string          = result.ToString();
                _innerExceptions = exceptions.AsReadOnly();
            }
Example #35
0
        public static String Format(IFormatProvider provider, String format, params Object[] args)
        {
            var sb = new Text.StringBuilder();

            sb.AppendFormat(provider, format, args);
            return(sb.ToString());
        }
Example #36
0
        public static String Concat(String str0, String str1)
        {
            var sb = new Text.StringBuilder();

            sb.Append(str0);
            sb.Append(str1);
            return(sb.ToString());
        }
Example #37
0
        /// <summary>
        /// Determines if the <see cref="String"/> representation of a <see cref="System.Text.StringBuilder"/> is equal to another <see cref="System.Text.StringBuilder"/> value.
        /// </summary>
        /// <param name="other">The <see cref="System.Text.StringBuilder"/> to compare to this instance.</param>
        /// <param name="comparisonType">One of the enumeration values that specifies how the strings will be compared.</param>
        /// <returns><c>True</c> if the values are equal; otherwisde <c>False</c>.</returns>
        public bool Equals(Text.StringBuilder other, StringComparison comparisonType)
        {
            if (other == null)
            {
                return(false);
            }

            return(this.ToString().Equals(other.ToString()));
        }
Example #38
0
        public static String Concat(params String[] values)
        {
            var sb = new Text.StringBuilder();

            foreach (var value in values)
            {
                sb.Append(value);
            }

            return(sb.ToString());
        }
Example #39
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());
        }
Example #40
0
        public static void Example01()
        {
            Console.WriteLine("**********ExpressionsAndOperators.Example01 BEGIN**********");

            Console.WriteLine($"Constant expression: {12}");
            Console.WriteLine($"Expression operands: {12*30}");
            Console.WriteLine($"Complex expression:  {1+(12*30)}");
            Console.WriteLine($"Primary expression:  {Math.Log(1)}");
            Console.WriteLine(1);   // void expression

            // assignment expressions evaluated from right to left
            var x = 1;

            x = x * 5;
            var y = 5 * (x = 2);

            // compound assignment operators
            x  *= 2;   // equivalent to x = x * 2
            x <<= 1;   // equivalent to x = x << 1

            //left associative operators
            Console.WriteLine($"left associative operators:  {(8 / 4 / 2)}");

            //rigth associative operators
            x = y = 3;
            Console.WriteLine($"right associative operators:  {x},{y}");

            //Null Coalescing Operator
            string s1 = null;
            string s2 = s1 ?? "nothing";   // s2 evaluates to "nothing"

            Console.WriteLine($"Null Coalescing Operator:  {s1},{s2}");

            //Null-conditional Operator
            System.Text.StringBuilder sb = null;
            Console.WriteLine($"Null Conditional Operator1:  {sb?.ToString()}");           // No error; s instead evaluates to null
            Console.WriteLine($"Null Conditional Operator2:  {sb?.ToString().ToUpper()}"); // No error; s instead evaluates to null
            Console.WriteLine($"Null Conditional Operator2:  {sb?.ToString() ?? "nothing"}");

            Console.WriteLine("**********ExpressionsAndOperators.Example01 END*************");
        }
Example #41
0
    static void Main(string[] args)
    {
        // the null coalescing operator gives you the value, or the
        // default if the value is null
        string s1 = null;
        string s2 = s1 ?? "nothing";

        // the elvis operator allows you to access members and methods
        // like the dot operator, but if the operand on the left is null,
        // the expression evaluates to null (rather than throwing a NullReferenceException)
        System.Text.StringBuilder sb = null;
        string s3 = sb?.ToString();   // No error; s instead evaluates to null

        Console.WriteLine(s2);
        Console.WriteLine(s3 ?? "it's null...");
    }
Example #42
0
        string GetDisplayFullName(DisplayNameFormat flags)
        {
            bool wantAssembly  = (flags & DisplayNameFormat.WANT_ASSEMBLY) != 0;
            bool wantModifiers = (flags & DisplayNameFormat.NO_MODIFIERS) == 0;
            var  sb            = new Text.StringBuilder(name.DisplayName);

            if (nested != null)
            {
                foreach (var n in nested)
                {
                    sb.Append('+').Append(n.DisplayName);
                }
            }

            if (generic_params != null)
            {
                sb.Append('[');
                for (int i = 0; i < generic_params.Count; ++i)
                {
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }
                    if (generic_params [i].assembly_name != null)
                    {
                        sb.Append('[').Append(generic_params [i].DisplayFullName).Append(']');
                    }
                    else
                    {
                        sb.Append(generic_params [i].DisplayFullName);
                    }
                }
                sb.Append(']');
            }

            if (wantModifiers)
            {
                GetModifierString(sb);
            }

            if (assembly_name != null && wantAssembly)
            {
                sb.Append(", ").Append(assembly_name);
            }

            return(sb.ToString());
        }
Example #43
0
    static void Main()
    {
        // null 合并运算符
        // 如果 ? ? 表达式的左侧不是 null , 那么,右侧的表达式不回执行
        string s1 = null;
        string s2 = s1 ?? "nothing";

        Console.WriteLine(s2);
        // null 条件运算符
        // "? ." 称为null条件运算符或者Elvis运算符,这个运算符可以像"."预算符那样
        // 访问成员以及调用方法,当运算符左侧为null,这个表达式的结果也是null而且
        // 不回抛出NullReferenceException异常
        System.Text.StringBuilder sb = null;
        string s = sb? .ToString();

        Console.WriteLine(s);
        string s3 = (sb == null ? null : sb.ToString());
    }
Example #44
0
        internal static string UnescapeInternalName(string displayName)
        {
            var res = new Text.StringBuilder(displayName.Length);

            for (int i = 0; i < displayName.Length; ++i)
            {
                char c = displayName[i];
                if (c == '\\')
                {
                    if (++i < displayName.Length)
                    {
                        c = displayName[i];
                    }
                }
                res.Append(c);
            }
            return(res.ToString());
        }
Example #45
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());
 }
        /**
         *
         */
        private static string htmlContato(List <LogEmailDestino> listaDestinos)
        {
            System.Text.StringBuilder html = new Text.StringBuilder();

            //listaDestinos = listaDestinos.DistinctBy(x => x.emailDestino).ToList();
            listaDestinos = listaDestinos.ToList();

            listaDestinos.ForEach(item => {
                if (!String.IsNullOrEmpty(item.nomeDestino) && !item.nomeDestino.Equals(item.emailDestino))
                {
                    html.Append(String.Concat(item.nomeDestino, " <", item.emailDestino, "> "));
                }
                else
                {
                    html.Append(item.emailDestino);
                }
                html.Append("; ");
            });

            return(html.ToString());
        }
Example #47
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());
        }
Example #48
0
        public void Arg()
        {
            var file = System.IO.File.ReadAllLines(@"C:\Users\root\Documents\Downloads\B-large.in");
//            var file2 = @"3
//3
//3 0 -4 0 0 3
//-3 -2 -1 3 0 0
//-3 -1 2 0 3 0
//3
//-5 0 0 1 0 0
//-7 0 0 1 0 0
//-6 3 0 1 0 0
//4
//1 2 3 1 2 3
//3 2 1 3 2 1
//1 0 0 0 0 -1
//0 10 0 0 -10 -1";
//            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++)
            {
                int N = int.Parse(file[line++]);

                F[] flys = new F[N];
                for (int i = 0; i < N; i++)
                {
                    flys[i] = new F(file[line++]);
                }

                //find inital location
                double xi = 0;
                double yi = 0;
                double zi = 0;

                double xiv = 0;
                double yiv = 0;
                double ziv = 0;

                foreach (F f in flys)
                {
                    xi += f.x;
                    yi += f.y;
                    zi += f.z;

                    xiv += f.vx;
                    yiv += f.vy;
                    ziv += f.vz;
                }

                double dN = N;
                xi /= dN;
                yi /= dN;
                zi /= dN;

                xiv /= dN;
                yiv /= dN;
                ziv /= dN;

                //we have a set of three solve it
                double[] move = new double[3];
                move[0] = xiv;
                move[1] = yiv;
                move[2] = ziv;

                //xi + move[0] * t
                //yi + move[1] * t
                //zi + move[2] * t

                //double timeX = move[0] * move[0] + move[1] * move[1] + move[2] * move[2];
                //double timeY = ((xi + move[0]) * move[0]) +
                //    ((yi + move[1]) * move[1]) +
                //    ((zi + move[2]) * move[2]);
                double timeB = move[0] * move[0] + move[1] * move[1] + move[2] * move[2];

                double timeT = (move[0] * xi) +
                               (move[1] * yi) +
                               (move[2] * zi);

                double time = -(timeT / timeB);
                if (timeB == 0)
                {
                    time = 0;
                }

                if (time < 0)
                {
                    time = 0;
                }

                double res = Distance(xi + time * move[0],
                                      yi + time * move[1],
                                      zi + time * move[2]);

                sb.AppendFormat("Case #{0}: {1:0.00000000} {2:0.00000000}", c, res, time);
                sb.AppendLine();
            }

            System.IO.File.WriteAllText(@"C:\Pub\b.txt", sb.ToString());
        }
Example #49
0
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string LoginName = this.txtLoginName.Value.Trim();

        ViewState["Criteria"] = "";
        System.Text.StringBuilder strCriteria = new System.Text.StringBuilder();
        //if (this.ddlType.SelectedValue.ToString().Trim() != "-1")
        //{
        //    strCriteria.Append(" NewsTypeID=");
        //    strCriteria.Append(this.ddlType.SelectedValue.ToString().Trim());
        //}
        if (strCriteria.ToString() == "")
        {
            if (this.txtNuber.Value.Trim() != "")   //根据ID
            {
                strCriteria.Append(" InfoID like  '%" + this.txtNuber.Value.Trim() + "%'");
            }
        }
        if (strCriteria.ToString() == "")
        {
            if (this.txtTitle.Value.Trim() != "")   //根据标题
            {
                strCriteria.Append(" Title like  '%" + this.txtTitle.Value.Trim() + "%'");
            }
        }
        if (strCriteria.ToString() == "")
        {
            if (this.txtLoginName.Value.ToString().Trim() != "" && ddlStatus.SelectedValue.ToString().Trim() != "5")
            {
                strCriteria.Append("LoginName='" + LoginName + "'");
                strCriteria.Append(" and AuditingStatus =" + this.ddlStatus.SelectedValue.ToString().Trim());
            }
            else
            {
                if (txtLoginName.Value.ToString().Trim() != "")
                {
                    strCriteria.Append("LoginName='" + LoginName + "'");
                }
            }
        }


        if (strCriteria.ToString() == "")
        {
            switch (this.ddlStatus.SelectedValue.ToString().Trim())
            {
            case "0":
                strCriteria.Append(" AuditingStatus=");
                strCriteria.Append(this.ddlStatus.SelectedValue.ToString().Trim());
                break;

            case "1":
                strCriteria.Append(" AuditingStatus=");
                strCriteria.Append(this.ddlStatus.SelectedValue.ToString().Trim());
                break;

            case "2":
                strCriteria.Append(" AuditingStatus=");
                strCriteria.Append(this.ddlStatus.SelectedValue.ToString().Trim());
                break;

            default:
                break;
            }
        }

        ViewState["Criteria"] = strCriteria.ToString();
        GetInfoNews();
    }
Example #50
0
        public ArrayList datosempleado()
        {
            SqlTransaction trODBC;

            try
            {
                System.Text.StringBuilder strQuery = new System.Text.StringBuilder();
                this.m_ConnODBC2009 = new SqlConnection(conexionSQL);
                this.m_ConnODBC2009.Open();
                trODBC = m_ConnODBC2009.BeginTransaction(IsolationLevel.RepeatableRead);
                SqlCommand commODBC = new SqlCommand("", m_ConnODBC2009, trODBC);

                strQuery.Remove(0, 0);
                strQuery.Append("SELECT numero as numero,nombres as nombre ,apellido_paterno as app ,apellido_materno as apm  ,clave_puesto as cpt ,clave_depto as cld ,clave_frecuencia_pago as clfp ,num_reg_patronal as numrp ,forma_pago as formap ,contrato as contrato ,jornada as jornada ,regimen_fiscal as regimenf ,fecha_ingreso as fechai ,estatus as estatus  ,tipo_salario as tipos ,salario_diario as sald ,salario_integrado as sali ,rfc as rfc ,curp as curp ,registro_imss as regimss,direccion as direccion,cp as cp, contrato_sat as contratosat FROM usuario ");
                commODBC.CommandText = strQuery.ToString();
                SqlDataReader OdbcDr = commODBC.ExecuteReader();



                while (OdbcDr.Read())
                {
                    Vempleados c = new Vempleados();

                    c.numero              = Convert.ToString(OdbcDr["numero"]);
                    c.nombres             = Convert.ToString(OdbcDr["nombre"]);
                    c.apellido_paterno    = Convert.ToString(OdbcDr["app"]);
                    c.apellido_pmaterno   = Convert.ToString(OdbcDr["apm"]);
                    c.clavepuesto         = Convert.ToString(OdbcDr["cpt"]);
                    c.clavedepto          = Convert.ToString(OdbcDr["cld"]);
                    c.clavefrecuenciapago = Convert.ToString(OdbcDr["clfp"]);
                    c.regpatronal         = Convert.ToString(OdbcDr["numrp"]);
                    c.formapago           = Convert.ToString(OdbcDr["formap"]);
                    c.contrato            = Convert.ToString(OdbcDr["contrato"]);
                    c.jornada             = Convert.ToString(OdbcDr["jornada"]);
                    c.regimenfiscal       = Convert.ToString(OdbcDr["regimenf"]);
                    c.fechaingreso        = Convert.ToString(OdbcDr["fechai"]);
                    c.estatus             = Convert.ToString(OdbcDr["estatus"]);
                    c.tiposalario         = Convert.ToString(OdbcDr["tipos"]);
                    c.salariodiario       = Convert.ToString(OdbcDr["sald"]);
                    c.salariointegrado    = Convert.ToString(OdbcDr["sali"]);
                    c.rfc          = Convert.ToString(OdbcDr["rfc"]);
                    c.curp         = Convert.ToString(OdbcDr["curp"]);
                    c.registroimss = Convert.ToString(OdbcDr["regimss"]);
                    c.direccion    = Convert.ToString(OdbcDr["direccion"]);
                    if (c.direccion == "CIUDAD DE MEXICO" | c.direccion == "MEXICO")
                    {
                        c.direccion = "DIF";
                    }
                    if (c.direccion == "PUEBLA")
                    {
                        c.direccion = "PUE";
                    }
                    if (c.direccion == "OAXACA")
                    {
                        c.direccion = "OAX";
                    }

                    c.cp          = Convert.ToString(OdbcDr["cp"]);
                    c.contratosat = Convert.ToString(OdbcDr["contratosat"]);
                    c.mensaje     = c.numero + "," + c.nombres + "," + c.apellido_paterno + "," + c.apellido_pmaterno + "," + c.clavepuesto + "," + c.clavedepto + "," + c.clavefrecuenciapago + "," + c.regpatronal + "," + c.formapago + "," + c.contrato + "," + c.jornada + "," + c.regimenfiscal + "," + c.fechaingreso + "," + c.estatus + "," + c.tiposalario + "," + c.salariodiario + "," + c.salariointegrado + "," + c.rfc + "," + c.curp + "," + c.registroimss + "," + c.direccion + "," + c.cp + "," + c.contratosat;
                    arreDatos.Add(c);
                }

                this.m_ConnODBC2009.Close();
                OdbcDr.Close();


                return(arreDatos);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #51
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string activityId = context.Request["activity_id"];

            if (string.IsNullOrEmpty(activityId))
            {
                apiResp.code = 1;
                apiResp.msg  = "activity_id 为必填项,请检查";
                bll.ContextResponse(context, apiResp);
                return;
            }
            JuActivityInfo juInfo = bll.GetJuActivity(int.Parse(activityId), true);

            if (juInfo == null)
            {
                apiResp.code = 4;
                apiResp.msg  = "活动不存在!";
                bll.ContextResponse(context, apiResp);
                return;
            }
            #region 是否可以报名
            if (juInfo.ActivityStatus.Equals(1))
            {
                apiResp.code = 2;
                apiResp.msg  = "活动已停止";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (juInfo.MaxSignUpTotalCount > 0)//检查报名人数
            {
                if (juInfo.SignUpTotalCount > (juInfo.MaxSignUpTotalCount - 1))
                {
                    apiResp.code = 3;
                    apiResp.msg  = "报名人数已满";
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (juInfo.ActivityIntegral > 0)
            {
                if (CurrentUserInfo.TotalScore < juInfo.ActivityIntegral)
                {
                    apiResp.code = 4;
                    apiResp.msg  = "您的积分不足";
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (juInfo.GuaranteeCreditAcount > 0)
            {
                if (CurrentUserInfo.CreditAcount < juInfo.GuaranteeCreditAcount)
                {
                    apiResp.code = 6;
                    apiResp.msg  = "您的信用金不足";
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            #endregion


            dicPar = bll.GetRequestParameter();
            //string weixinOpenID = null;
            string activityIdBySignUp = juInfo.SignUpActivityID;
            string spreadUserId       = null;
            dicPar.TryGetValue("SpreadUserID", out spreadUserId);
            string strDistinctKeys = null;//检查重复的字段,多个字段用,分隔, //没有此参数默认用手机检查
            dicPar.TryGetValue("DistinctKeys", out strDistinctKeys);
            string monitorPlanID = null;
            dicPar.TryGetValue("MonitorPlanID", out monitorPlanID);
            string name = null;
            dicPar.TryGetValue("Name", out name);
            string phone = null;
            dicPar.TryGetValue("Phone", out phone);
            ActivityInfo activity = bll.Get <ActivityInfo>(string.Format("ActivityID='{0}'", activityIdBySignUp));

            #region IP限制
            //获取用户IP;
            string userHostAddress = context.Request.UserHostAddress;
            var    count           = DataCache.GetCache(userHostAddress);
            if (count != null)
            {
                int newCount = int.Parse(count.ToString()) + 1;
                DataCache.SetCache(userHostAddress, newCount);
                int limitCount = 1000;
                if (activity != null)
                {
                    limitCount = activity.LimitCount;
                }
                if (newCount >= limitCount)
                {
                    apiResp.code = 5;
                    apiResp.msg  = "您的提交过于频繁,请稍后再试";
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            else
            {
                DataCache.SetCache(userHostAddress, 1, DateTime.MaxValue, new TimeSpan(4, 0, 0));
            }

            #endregion

            #region 活动权限验证
            if (juInfo == null)
            {
                apiResp.code = 6;
                apiResp.msg  = "活动不存在!";
                bll.ContextResponse(context, apiResp);
                return;
            }
            if (juInfo.ActivityStatus.Equals(1))
            {
                apiResp.code = 7;
                apiResp.msg  = "活动已关闭!";
                bll.ContextResponse(context, apiResp);
                return;
            }

            if (activity.IsDelete.Equals(1))
            {
                apiResp.code = 8;
                apiResp.msg  = "活动已删除!";
                bll.ContextResponse(context, apiResp);
                return;
            }
            #endregion

            #region 判断必填项
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(phone))
            {
                apiResp.code = 9;
                apiResp.msg  = "姓名和手机不能为空!";
                bll.ContextResponse(context, apiResp);
                return;
            }

            if ((!phone.StartsWith("1")) || (!phone.Length.Equals(11)))
            {
                apiResp.code = 10;
                apiResp.msg  = "手机号码无效!";
                bll.ContextResponse(context, apiResp);
                return;
            }

            #endregion

            #region 检查自定义必填项
            List <ActivityFieldMappingInfo> listRequiredField = bll.GetList <ActivityFieldMappingInfo>(string.Format("ActivityID='{0}' And FieldIsNull=1", activity.ActivityID));
            if (listRequiredField.Count > 0)
            {
                foreach (var requiredField in listRequiredField)
                {
                    if (string.IsNullOrEmpty(dicPar.SingleOrDefault(p => p.Key.Equals(string.Format("K{0}", requiredField.ExFieldIndex))).Value))
                    {
                        apiResp.code = 11;
                        apiResp.msg  = string.Format(" {0} 必填", requiredField.MappingName);
                        bll.ContextResponse(context, apiResp);
                        return;
                    }
                }
            }
            #endregion

            #region 检查数据格式
            //检查数据格式
            List <ActivityFieldMappingInfo> activityFieldMapping = bll.GetList <ActivityFieldMappingInfo>(string.Format("ActivityID='{0}'", activity.ActivityID));
            foreach (var item in activityFieldMapping)
            {
                string value = dicPar.SingleOrDefault(p => p.Key.Equals(string.Format("K{0}", item.ExFieldIndex))).Value;

                if (string.IsNullOrWhiteSpace(value))
                {
                    continue;
                }

                //检查数据格式
                if (item.FormatValiFunc == "email")//email检查
                {
                    if (!ZentCloud.Common.ValidatorHelper.EmailLogicJudge(value))
                    {
                        apiResp.code = 12;
                        apiResp.msg  = string.Format("{0}格式不正确", item.MappingName);
                        bll.ContextResponse(context, apiResp);
                        return;
                    }
                }
                if (item.FormatValiFunc == "url")                                                                                                             //url检查
                {
                    System.Text.RegularExpressions.Regex regUrl = new System.Text.RegularExpressions.Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"); //网址
                    System.Text.RegularExpressions.Match m      = regUrl.Match(value);
                    if (!m.Success)
                    {
                        apiResp.code = 13;
                        apiResp.msg  = string.Format("{0}格式不正确", item.MappingName);
                        bll.ContextResponse(context, apiResp);
                        return;
                    }
                }
            }
            #endregion

            #region 检查是否已经报名
            if (!string.IsNullOrEmpty(strDistinctKeys))
            {
                if (!strDistinctKeys.Equals("none"))//自定义检查重复
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder("1=1 ");
                    string[] distinctKeys        = strDistinctKeys.Split(',');
                    foreach (var item in distinctKeys)
                    {
                        sb.AppendFormat("And {0}='{1}' ", item, dicPar.Single(p => p.Key.Equals(item)).Value);
                    }
                    sb.Append("  and IsDelete = 0  ");
                    if (bll.GetCount <ActivityDataInfo>(sb.ToString()) > 0)
                    {
                        apiResp.code = 14;
                        apiResp.msg  = "重复的报名!";
                        bll.ContextResponse(context, apiResp);
                        return;
                    }
                }
                else//不检查重复
                {
                }
            }
            else//默认检查
            {
                if (bll.GetCount <ActivityDataInfo>(string.Format("ActivityID='{0}' And Phone='{1}' and IsDelete = 0 ", activityIdBySignUp, phone)) > 0)
                {
                    apiResp.code = 15;
                    apiResp.msg  = "已经报过名了!";
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }



            #endregion


            var newActivityUID       = 1001;
            var lastActivityDataInfo = bll.Get <ActivityDataInfo>(string.Format("ActivityID='{0}' order by UID DESC", activityIdBySignUp));
            if (lastActivityDataInfo != null)
            {
                newActivityUID = lastActivityDataInfo.UID + 1;
            }
            ActivityDataInfo model = bll.ConvertRequestToModel <ActivityDataInfo>(new ActivityDataInfo());
            model.UID          = newActivityUID;
            model.SpreadUserID = spreadUserId;
            model.ActivityID   = activityIdBySignUp;
            if (juInfo.GuaranteeCreditAcount > 0)
            {
                if (model.GuaranteeCreditAcount < juInfo.GuaranteeCreditAcount)
                {
                    apiResp.code = 18;
                    apiResp.msg  = string.Format("担保信用金不能少于{0}!", Convert.ToDouble(juInfo.GuaranteeCreditAcount));
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (!string.IsNullOrEmpty(monitorPlanID))
            {
                model.MonitorPlanID = int.Parse(monitorPlanID);
            }
            model.WebsiteOwner = bll.WebsiteOwner;
            model.UserId       = CurrentUserInfo.UserID;
            model.WeixinOpenID = CurrentUserInfo.WXOpenId;
            if (context.Request["limit_userid_signupcount"] == "1")//限制每个登录账号只能报名一次
            {
                if (bll.GetCount <ActivityDataInfo>(string.Format(" UserId='{0}' AND ActivityID={1} AND IsDelete=0 "
                                                                  , model.UserId, juInfo.SignUpActivityID)) > 0)
                {
                    apiResp.code = 14;
                    apiResp.msg  = "重复的报名!";
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            if (context.Request["limit_wxopenid_signupcount"] == "1")//限制每个微信只能报名一次
            {
                if (bll.GetCount <ActivityDataInfo>(string.Format(" UserId='{0}' AND ActivityID={1} AND IsDelete=0 "
                                                                  , model.WeixinOpenID, juInfo.SignUpActivityID)) > 0)
                {
                    apiResp.code = 14;
                    apiResp.msg  = "重复的报名!";
                    bll.ContextResponse(context, apiResp);
                    return;
                }
            }
            model.ArticleType = juInfo.ArticleType;
            model.CategoryId  = juInfo.CategoryId;
            if (bll.Add(model))
            {
                bll.PlusNumericalCol("SignUpCount", juInfo.JuActivityID);//报名数+1
                //发消息给发布约会的人
                PubUser = bllUser.GetUserInfo(juInfo.UserID);
                if (PubUser != null && context.Request["notice_publisher"] == "1")
                {
                    bllSystemNotice.SendSystemMessage("“" + bllUser.GetUserDispalyName(CurrentUserInfo) + "”报名您的约会", juInfo.ActivityName, BLLJIMP.BLLSystemNotice.NoticeType.AppointmentNotice, BLLJIMP.BLLSystemNotice.SendType.Personal, PubUser.UserID, juInfo.JuActivityID.ToString());
                }
                //发消息给自己
                if (CurrentUserInfo != null && context.Request["notice_signupuser"] == "1")
                {
                    bllSystemNotice.SendSystemMessage("你报名了一个约会冻结" + Convert.ToDouble(model.GuaranteeCreditAcount) + "信用金", juInfo.ActivityName, BLLJIMP.BLLSystemNotice.NoticeType.FinancialNotice, BLLJIMP.BLLSystemNotice.SendType.Personal, CurrentUserInfo.UserID, juInfo.JuActivityID.ToString());
                }
                apiResp.msg    = "ok";
                apiResp.code   = 0;
                apiResp.status = true;
                #region 当ActivityIntegral>0   扣积分
                if (juInfo.ActivityIntegral > 0)//扣积分
                {
                    CurrentUserInfo.TotalScore -= juInfo.ActivityIntegral;
                    if (bll.Update(CurrentUserInfo, string.Format("TotalScore={0}", CurrentUserInfo.TotalScore), string.Format(" AutoID={0}", CurrentUserInfo.AutoID)) <= 0)
                    {
                        apiResp.code = 16;
                        apiResp.msg  = "扣除用户积分失败";
                        bll.ContextResponse(context, apiResp);
                        return;
                    }
                    else
                    {
                        //
                        BLLJIMP.Model.WBHScoreRecord scoreRecord = new BLLJIMP.Model.WBHScoreRecord();
                        scoreRecord.Nums         = "b55";
                        scoreRecord.InsertDate   = DateTime.Now;
                        scoreRecord.WebsiteOwner = bll.WebsiteOwner;
                        scoreRecord.UserId       = CurrentUserInfo.UserID;
                        scoreRecord.RecordType   = "2";
                        scoreRecord.NameStr      = "参加活动:" + juInfo.ActivityName;
                        scoreRecord.ScoreNum     = string.Format("-{0}", juInfo.ActivityIntegral);
                        if (!bll.Add(scoreRecord))
                        {
                            apiResp.code = 17;
                            apiResp.msg  = "插入积分记录失败";
                            bll.ContextResponse(context, apiResp);
                            return;
                        }
                    }
                }
                #endregion

                #region 当ActivityIntegral>0   扣信用金
                if (juInfo.GuaranteeCreditAcount > 0)//扣积分
                {
                    bllUser.AddUserCreditAcountDetails(CurrentUserInfo.UserID, "ApplyCost", bllUser.WebsiteOwner, 0 - model.GuaranteeCreditAcount
                                                       , string.Format("报名【{0}】消耗{1}信用金", juInfo.ActivityName, Convert.ToDouble(model.GuaranteeCreditAcount)));
                }
                #endregion
            }
            else
            {
                apiResp.code = 1;
                apiResp.msg  = "报名失败,请重试或联系管理员!";
            }
            bll.ContextResponse(context, apiResp);
        }
Example #52
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);
        }
Example #53
0
        public void Render(ViewContext viewContext, TextWriter writer)
        {
            // generate view into string

            /* var sb = new System.Text.StringBuilder();
             * TextWriter tw = new System.IO.StringWriter(sb);
             * _result.View.Render(viewContext, tw);
             * var resultCache = sb.ToString();
             *
             * var ms = new MemoryStream();
             * var document = new Document();
             * var pdfWriter = PdfWriter.GetInstance(document, ms);
             * var worker = new HTMLWorker(document);
             * document.Open();
             * worker.StartDocument();
             *
             * pdfWriter.CloseStream = false;
             *
             * worker.Parse(new StringReader(resultCache));
             * worker.EndDocument();
             * worker.Close();
             * document.Close();
             *
             * // this is as close as we can get to being "success" before writing output
             * // so set the content type now
             * viewContext.HttpContext.Response.ContentType = "application/pdf";
             * pdfWriter.Flush();
             * pdfWriter.Close();
             *
             * viewContext.HttpContext.Response.BinaryWrite(ms.ToArray()); */
            // generate view into string
            var        sb = new System.Text.StringBuilder();
            TextWriter tw = new System.IO.StringWriter(sb);

            _result.View.Render(viewContext, tw);
            var resultCache = sb.ToString();

            // detect itext (or html) format of response
            XmlParser parser;

            using (var reader = GetXmlReader(resultCache.Replace("\r", "").Replace("\n", "")))
            {
                while (reader.Read() && reader.NodeType != XmlNodeType.Element)
                {
                    // no-op
                }

                if (reader.NodeType == XmlNodeType.Element && reader.Name == "itext")
                {
                    parser = new XmlParser();
                }
                else
                {
                    parser = new HtmlParser();
                }
            }

            // Create a document processing context
            var document = new Document();

            document.Open();

            // associate output with response stream
            var pdfWriter = PdfWriter.GetInstance(document, viewContext.HttpContext.Response.OutputStream);

            pdfWriter.CloseStream = false;

            // this is as close as we can get to being "success" before writing output
            // so set the content type now
            viewContext.HttpContext.Response.ContentType = "application/pdf";

            // parse memory through document into output
            using (var reader = GetXmlReader(resultCache))
            {
                parser.Go(document, reader);
            }

            pdfWriter.Close();
        }
        internal void WriteBootConfig()
        {
            // boot settings string format
            // <boot setting>:<value>[;<boot setting>:<value>]*
            bool firstEntry = true;
            var  sb         = new System.Text.StringBuilder();

            foreach (var kvp in bootConfigSettings)
            {
                if (!firstEntry)
                {
                    sb.Append(";");
                }
                sb.Append($"{kvp.Key}:{kvp.Value}");
                firstEntry = false;
            }

            string buildTargetName = BuildPipeline.GetBuildTargetName(buildReport.summary.platform);

            EditorUserBuildSettings.SetPlatformSettings(buildTargetName, kXrBootSettingsKey, sb.ToString());
        }
Example #55
0
        /// <summary>
        /// 动态调用web服务(WS的描述,只存在多个对象类)
        /// </summary>
        /// <param name="url">WSDL服务地址</param>
        /// <param name="classname">类名</param>
        /// <param name="methodname">方法名</param>
        /// <param name="args">参数</param>
        /// <returns>结果</returns>
        /// <exception cref="System.Exception">无法动态编译类</exception>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            //##随意固定一个命名空间
            const string @namespace = "DynamicInvokerServiceNS.DynamicWebCalling";

            //##获取类名
            if (String.IsNullOrEmpty(classname))
            {
                classname = GetWsClassName(url);
            }

            //##执行
            try
            {
                //##获取WSDL
                WebClient wc     = new WebClient();
                Stream    stream = wc.OpenRead(url + "?WSDL");

                //##动态生成Code的准备
                ServiceDescription         sd  = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace   cn  = new CodeNamespace(@namespace);
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider icc = new CSharpCodeProvider();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;       //在内存中编译
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //##编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (cr.Errors.HasErrors)
                {//##存在错误的时候
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //##生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                return(mi.Invoke(obj, args));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
Example #56
0
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Text.StringBuilder qstring = new System.Text.StringBuilder();
        int qsCount = Request.QueryString.Count;

        #region processreceipt
        if (qsCount > 0 && Request.QueryString["sta"] != null && Request.QueryString["tid"] != null)
        {
            TransactionRecord tr = new TransactionRecord();
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(string.Format("IDBI Web payment transaction response [{0}]", Request.QueryString["sta"]));
            tr.Status = Request.QueryString["sta"].ToString().Equals("50020");
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Web payment transaction complete. Status: " + (tr.Status ? "Success" : "Failure"));

            string IpAddress = System.Configuration.ConfigurationManager.AppSettings["KoDTicketingIPAddress"];
            #region parsereference

            String   refNo     = Request.QueryString["tid"].ToString();
            string[] refTokens = refNo.Split('_');
            if (refTokens.Length < 2)
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Payment Response: Tokenization of reference string did not result in enough tokens. --> " + refNo);
                return;
            }

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Transaction reference: " + refTokens[0].ToString());
            tr.ReferenceNo = long.Parse(refTokens[0].ToString());

            string[] refSubTokens = refTokens[1].Split('~');

            if (refSubTokens.Length < 3)
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Payment Response: Tokenization of reference substring did not result in enough sub tokens. --> " + refTokens[1].ToString());
                return;
            }

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Booking ID: " + refSubTokens[0]);
            tr.BookingID = long.Parse(refSubTokens[0]);

            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Agent Code: " + refSubTokens[1]);
            tr.AgentCode = refSubTokens[1];
            #endregion parsereference
            Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Amount: " + Request.QueryString["amt"].ToString());
            tr.TotalAmount = decimal.Parse(Request.QueryString["amt"].ToString());
            try
            {
                if (true == tr.Status)
                {
                    HandleSuccess(ref tr, ref qstring);
                }
                else //failure
                {
                    GTICKV.LogEntry(tr.ReferenceNo.ToString(), "Payment Not Successful", "17", tr.BookingID.ToString());
                    GTICKBOL.ON_Session_out(tr.ReferenceNo.ToString());
                    GTICKV.LogEntry(tr.ReferenceNo.ToString(), "Seats Unlocked", "18", tr.BookingID.ToString());
                    long      BookingID = long.Parse(tr.ReferenceNo.ToString());
                    DataTable dt        = TransactionBOL.Select_Temptransaction_REFIDWISE(BookingID);
                    ReceiptUtils.PaymentNotCaptureResponse(tr.ReceiptNo.ToString(), dt.Rows[0], "");
                    qstring.Append("?err=pay");
                }
            }
            catch (Exception ex)
            {
                Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(ex.Message);
                HandleFailure(tr);
                qstring.Append("?err=seat");
            }
        }

        #endregion processreceipt

        Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write("IDBI Transaction Complete. " + Request.QueryString["rec"]);
        Server.Transfer("../Print-Receipt.aspx" + qstring.ToString(), false);
    }
Example #57
0
    IEnumerator SetModelAsync(string renderModelName)
    {
        if (string.IsNullOrEmpty(renderModelName))
        {
            yield break;
        }

        // Preload all render models before asking for the data to create meshes.
        using (var holder = new RenderModelInterfaceHolder())
        {
            var renderModels = holder.instance;
            if (renderModels == null)
            {
                yield break;
            }

            // Gather names of render models to preload.
            string[] renderModelNames;

            var count = renderModels.GetComponentCount(renderModelName);
            if (count > 0)
            {
                renderModelNames = new string[count];

                for (int i = 0; i < count; i++)
                {
                    var capacity = renderModels.GetComponentName(renderModelName, (uint)i, null, 0);
                    if (capacity == 0)
                    {
                        continue;
                    }

                    var componentName = new System.Text.StringBuilder((int)capacity);
                    if (renderModels.GetComponentName(renderModelName, (uint)i, componentName, capacity) == 0)
                    {
                        continue;
                    }

                    capacity = renderModels.GetComponentRenderModelName(renderModelName, componentName.ToString(), null, 0);
                    if (capacity == 0)
                    {
                        continue;
                    }

                    var name = new System.Text.StringBuilder((int)capacity);
                    if (renderModels.GetComponentRenderModelName(renderModelName, componentName.ToString(), name, capacity) == 0)
                    {
                        continue;
                    }

                    var s = name.ToString();

                    // Only need to preload if not already cached.
                    var model = models[s] as RenderModel;
                    if (model == null || model.mesh == null)
                    {
                        renderModelNames[i] = s;
                    }
                }
            }
            else
            {
                // Only need to preload if not already cached.
                var model = models[renderModelName] as RenderModel;
                if (model == null || model.mesh == null)
                {
                    renderModelNames = new string[] { renderModelName };
                }
                else
                {
                    renderModelNames = new string[0];
                }
            }

            // Keep trying every 100ms until all components finish loading.
            while (true)
            {
                var loading = false;
                foreach (var name in renderModelNames)
                {
                    if (string.IsNullOrEmpty(name))
                    {
                        continue;
                    }

                    var pRenderModel = System.IntPtr.Zero;

                    var error = renderModels.LoadRenderModel_Async(name, ref pRenderModel);
                    if (error == EVRRenderModelError.Loading)
                    {
                        loading = true;
                    }
                    else if (error == EVRRenderModelError.None)
                    {
                        // Preload textures as well.
                        var renderModel = (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));

                        // Check the cache first.
                        var material = materials[renderModel.diffuseTextureId] as Material;
                        if (material == null || material.mainTexture == null)
                        {
                            var pDiffuseTexture = System.IntPtr.Zero;

                            error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                            if (error == EVRRenderModelError.Loading)
                            {
                                loading = true;
                            }
                        }
                    }
                }

                if (loading)
                {
                    yield return(new WaitForSeconds(0.1f));
                }
                else
                {
                    break;
                }
            }
        }

        bool success = SetModel(renderModelName);

        SteamVR_Utils.Event.Send("render_model_loaded", this, success);
    }
Example #58
0
    private bool LoadComponents(RenderModelInterfaceHolder holder, string renderModelName)
    {
        // Disable existing components (we will re-enable them if referenced by this new model).
        // Also strip mesh filter and renderer since these will get re-added if the new component needs them.
        var t = transform;

        for (int i = 0; i < t.childCount; i++)
        {
            var child = t.GetChild(i);
            child.gameObject.SetActive(false);
            StripMesh(child.gameObject);
        }

        // If no model specified, we're done; return success.
        if (string.IsNullOrEmpty(renderModelName))
        {
            return(true);
        }

        var renderModels = holder.instance;

        if (renderModels == null)
        {
            return(false);
        }

        var count = renderModels.GetComponentCount(renderModelName);

        if (count == 0)
        {
            return(false);
        }

        for (int i = 0; i < count; i++)
        {
            var capacity = renderModels.GetComponentName(renderModelName, (uint)i, null, 0);
            if (capacity == 0)
            {
                continue;
            }

            var componentName = new System.Text.StringBuilder((int)capacity);
            if (renderModels.GetComponentName(renderModelName, (uint)i, componentName, capacity) == 0)
            {
                continue;
            }

            // Create (or reuse) a child object for this component (some components are dynamic and don't have meshes).
            t = FindComponent(componentName.ToString());
            if (t != null)
            {
                t.gameObject.SetActive(true);
            }
            else
            {
                t                  = new GameObject(componentName.ToString()).transform;
                t.parent           = transform;
                t.gameObject.layer = gameObject.layer;

                // Also create a child 'attach' object for attaching things.
                var attach = new GameObject(k_localTransformName).transform;
                attach.parent           = t;
                attach.localPosition    = Vector3.zero;
                attach.localRotation    = Quaternion.identity;
                attach.localScale       = Vector3.one;
                attach.gameObject.layer = gameObject.layer;
            }

            // Reset transform.
            t.localPosition = Vector3.zero;
            t.localRotation = Quaternion.identity;
            t.localScale    = Vector3.one;

            capacity = renderModels.GetComponentRenderModelName(renderModelName, componentName.ToString(), null, 0);
            if (capacity == 0)
            {
                continue;
            }

            var componentRenderModelName = new System.Text.StringBuilder((int)capacity);
            if (renderModels.GetComponentRenderModelName(renderModelName, componentName.ToString(), componentRenderModelName, capacity) == 0)
            {
                continue;
            }

            // Check the cache or load into memory.
            var model = models[componentRenderModelName] as RenderModel;
            if (model == null || model.mesh == null)
            {
                if (verbose)
                {
                    Debug.Log("Loading render model " + componentRenderModelName);
                }

                model = LoadRenderModel(renderModels, componentRenderModelName.ToString(), renderModelName);
                if (model == null)
                {
                    continue;
                }

                models[componentRenderModelName] = model;
            }

            t.gameObject.AddComponent <MeshFilter>().mesh             = model.mesh;
            t.gameObject.AddComponent <MeshRenderer>().sharedMaterial = model.material;
        }

        return(true);
    }
    public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
    {
        Undo.undoRedoPerformed -= Undo_UndoRedoPerformed;
        Undo.undoRedoPerformed += Undo_UndoRedoPerformed;
        Material targetMat = materialEditor.target as Material;

        if (cachedTitle == null)
        {
            cachedTitle = "Shader Generator        v:" + MicroSplatVersion;
        }
        if (GUI.enabled == false || string.IsNullOrEmpty(AssetDatabase.GetAssetPath(targetMat)))
        {
            EditorGUILayout.HelpBox("You must edit the template material, not the instance being used. You can find this in the MicroSplatData directory, or assigned on your MicroSplatTerrain component", MessageType.Info);
            return;
        }
        EditorGUI.BeginChangeCheck(); // sync materials

        Texture2DArray diff = targetMat.GetTexture("_Diffuse") as Texture2DArray;

        var keywordSO = MicroSplatUtilities.FindOrCreateKeywords(targetMat);

        cachedKeywordCount = keywordSO.keywords.Count; // for undo
        cachedMaterial     = targetMat;

        compiler.Init();
        // must unpack everything before the generator draws- otherwise we get IMGUI errors
        for (int i = 0; i < compiler.extensions.Count; ++i)
        {
            var ext = compiler.extensions[i];
            ext.Unpack(keywordSO.keywords.ToArray());
        }

        string shaderName = targetMat.shader.name;

        DrawModules();

        EditorGUI.BeginChangeCheck(); // needs compile
        var propTex = FindOrCreatePropTex(targetMat);

        Undo.RecordObjects(new Object[3] {
            targetMat, keywordSO, propTex
        }, "MicroSplat Material Edit");

        if (MicroSplatUtilities.DrawRollup(cachedTitle))
        {
            shaderName = EditorGUILayout.DelayedTextField(CShaderName, shaderName);

            if (DrawRenderLoopGUI(keywordSO, targetMat))
            {
                needsCompile = true;
            }

            for (int i = 0; i < compiler.extensions.Count; ++i)
            {
                var e = compiler.extensions[i];
                if (e.GetVersion() == MicroSplatVersion)
                {
                    //using (new GUILayout.VerticalScope(GUI.skin.box))
                    {
                        e.DrawFeatureGUI(keywordSO);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("Extension : " + e + " is version " + e.GetVersion() + " and MicroSplat is version " + MicroSplatVersion + ", please update", MessageType.Error);
                }
            }

            for (int i = 0; i < availableRenderLoops.Count; ++i)
            {
                var rl = availableRenderLoops[i];
                if (rl.GetVersion() != MicroSplatVersion)
                {
                    EditorGUILayout.HelpBox("Render Loop : " + rl.GetDisplayName() + " is version " + rl.GetVersion() + " and MicroSplat is version " + MicroSplatVersion + ", please update", MessageType.Error);
                }
            }
        }
        needsCompile = needsCompile || EditorGUI.EndChangeCheck();

        int featureCount = keywordSO.keywords.Count;

        // note, ideally we wouldn't draw the GUI for the rest of stuff if we need to compile.
        // But we can't really do that without causing IMGUI to split warnings about
        // mismatched GUILayout blocks
        if (!needsCompile)
        {
            for (int i = 0; i < compiler.extensions.Count; ++i)
            {
                var ext = compiler.extensions[i];
                if (ext.GetVersion() == MicroSplatVersion)
                {
                    ext.DrawShaderGUI(this, keywordSO, targetMat, materialEditor, props);
                }
                else
                {
                    EditorGUILayout.HelpBox("Extension : " + ext + " is version " + ext.GetVersion() + " and MicroSplat is version " + MicroSplatVersion + ", please update so that all modules are using the same version.", MessageType.Error);
                }
            }


            if (diff != null && MicroSplatUtilities.DrawRollup("Per Texture Properties"))
            {
                perTexIndex = MicroSplatUtilities.DrawTextureSelector(perTexIndex, diff);

                for (int i = 0; i < compiler.extensions.Count; ++i)
                {
                    var ext = compiler.extensions[i];
                    if (ext.GetVersion() == MicroSplatVersion)
                    {
                        ext.DrawPerTextureGUI(perTexIndex, keywordSO, targetMat, propTex);
                    }
                }
            }
        }

        if (!needsCompile)
        {
            if (featureCount != keywordSO.keywords.Count)
            {
                needsCompile = true;
            }
        }


        int arraySampleCount   = 0;
        int textureSampleCount = 0;
        int maxSamples         = 0;
        int tessSamples        = 0;
        int depTexReadLevel    = 0;

        builder.Length = 0;
        for (int i = 0; i < compiler.extensions.Count; ++i)
        {
            var ext = compiler.extensions[i];
            if (ext.GetVersion() == MicroSplatVersion)
            {
                ext.ComputeSampleCounts(keywordSO.keywords.ToArray(), ref arraySampleCount, ref textureSampleCount, ref maxSamples, ref tessSamples, ref depTexReadLevel);
            }
        }
        if (MicroSplatUtilities.DrawRollup("Debug"))
        {
            string shaderModel = compiler.GetShaderModel(keywordSO.keywords.ToArray());
            builder.Append("Shader Model : ");
            builder.AppendLine(shaderModel);
            if (maxSamples != arraySampleCount)
            {
                builder.Append("Texture Array Samples : ");
                builder.AppendLine(arraySampleCount.ToString());

                builder.Append("Regular Samples : ");
                builder.AppendLine(textureSampleCount.ToString());
            }
            else
            {
                builder.Append("Texture Array Samples : ");
                builder.AppendLine(arraySampleCount.ToString());
                builder.Append("Regular Samples : ");
                builder.AppendLine(textureSampleCount.ToString());
            }
            if (tessSamples > 0)
            {
                builder.Append("Tessellation Samples : ");
                builder.AppendLine(tessSamples.ToString());
            }
            if (depTexReadLevel > 0)
            {
                builder.Append(depTexReadLevel.ToString());
                builder.AppendLine(" areas with dependent texture reads");
            }

            EditorGUILayout.HelpBox(builder.ToString(), MessageType.Info);
        }

        if (EditorGUI.EndChangeCheck() && !needsCompile)
        {
            MicroSplatTerrain.SyncAll();
#if __MICROSPLAT_MESH__
            MicroSplatMesh.SyncAll();
#endif
        }

        if (needsCompile)
        {
            needsCompile = false;
            keywordSO.keywords.Clear();
            for (int i = 0; i < compiler.extensions.Count; ++i)
            {
                compiler.extensions[i].Pack(keywordSO);
            }
            if (compiler.renderLoop != null)
            {
                keywordSO.EnableKeyword(compiler.renderLoop.GetRenderLoopKeyword());
            }

            // horrible workaround to GUI warning issues
            compileMat     = targetMat;
            compileName    = shaderName;
            targetCompiler = compiler;
            EditorApplication.delayCall += TriggerCompile;
        }
    }
    List <GameObject> FilterList(List <GameObject> mrss, HashSet <GameObject> objectsAlreadyIncludedInBakers, GameObject dontAddMe)
    {
        int numInSelection             = 0;
        int numStaticExcluded          = 0;
        int numEnabledExcluded         = 0;
        int numLightmapExcluded        = 0;
        int numOBuvExcluded            = 0;
        int numMatExcluded             = 0;
        int numShaderExcluded          = 0;
        int numRegExExcluded           = 0;
        int numAlreadyIncludedExcluded = 0;

        System.Text.RegularExpressions.Regex regex = null;
        if (searchRegEx != null && searchRegEx.Length > 0)
        {
            try
            {
                regex           = new System.Text.RegularExpressions.Regex(searchRegEx);
                regExParseError = "";
            }
            catch (Exception ex)
            {
                regExParseError = ex.Message;
            }
        }
        Dictionary <int, MB_Utility.MeshAnalysisResult> meshAnalysisResultsCache = new Dictionary <int, MB_Utility.MeshAnalysisResult>(); //cache results
        List <GameObject> newMomObjs = new List <GameObject>();

        for (int j = 0; j < mrss.Count; j++)
        {
            if (mrss[j] == null)
            {
                continue;
            }
            Renderer mrs = mrss[j].GetComponent <Renderer>();
            if (mrs is MeshRenderer || mrs is SkinnedMeshRenderer)
            {
                if (mrs.GetComponent <TextMesh>() != null)
                {
                    continue; //don't add TextMeshes
                }
                numInSelection++;
                if (!newMomObjs.Contains(mrs.gameObject))
                {
                    bool addMe = true;
                    if (!mrs.gameObject.isStatic && onlyStaticObjects)
                    {
                        numStaticExcluded++;
                        addMe = false;
                        continue;
                    }

                    if (!mrs.enabled && onlyEnabledObjects)
                    {
                        numEnabledExcluded++;
                        addMe = false;
                        continue;
                    }

                    if (lightmapIndex != -2)
                    {
                        if (mrs.lightmapIndex != lightmapIndex)
                        {
                            numLightmapExcluded++;
                            addMe = false;
                            continue;
                        }
                    }

                    if (excludeMeshesAlreadyAddedToBakers && objectsAlreadyIncludedInBakers.Contains(mrs.gameObject))
                    {
                        numAlreadyIncludedExcluded++;
                        addMe = false;
                        continue;
                    }

                    Mesh mm = MB_Utility.GetMesh(mrs.gameObject);
                    if (mm != null)
                    {
                        MB_Utility.MeshAnalysisResult mar;
                        if (!meshAnalysisResultsCache.TryGetValue(mm.GetInstanceID(), out mar))
                        {
                            MB_Utility.hasOutOfBoundsUVs(mm, ref mar);
                            meshAnalysisResultsCache.Add(mm.GetInstanceID(), mar);
                        }
                        if (mar.hasOutOfBoundsUVs && excludeMeshesWithOBuvs)
                        {
                            numOBuvExcluded++;
                            addMe = false;
                            continue;
                        }
                    }

                    if (shaderMat != null)
                    {
                        Material[] nMats      = mrs.sharedMaterials;
                        bool       usesShader = false;
                        foreach (Material nMat in nMats)
                        {
                            if (nMat != null && nMat.shader == shaderMat.shader)
                            {
                                usesShader = true;
                            }
                        }
                        if (!usesShader)
                        {
                            numShaderExcluded++;
                            addMe = false;
                            continue;
                        }
                    }

                    if (mat != null)
                    {
                        Material[] nMats   = mrs.sharedMaterials;
                        bool       usesMat = false;
                        foreach (Material nMat in nMats)
                        {
                            if (nMat == mat)
                            {
                                usesMat = true;
                            }
                        }
                        if (!usesMat)
                        {
                            numMatExcluded++;
                            addMe = false;
                            continue;
                        }
                    }

                    if (regex != null)
                    {
                        if (!regex.IsMatch(mrs.gameObject.name))
                        {
                            numRegExExcluded++;
                            addMe = false;
                            continue;
                        }
                    }

                    if (addMe && mrs.gameObject != dontAddMe)
                    {
                        if (!newMomObjs.Contains(mrs.gameObject))
                        {
                            newMomObjs.Add(mrs.gameObject);
                        }
                    }
                }
            }
        }

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //sb.AppendFormat("Total objects in selection {0}\n", numInSelection);
        //Debug.Log( "Total objects in selection " + numInSelection);
        if (numStaticExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they were not static\n", numStaticExcluded);
            Debug.Log(numStaticExcluded + " objects were excluded because they were not static\n");
        }
        if (numEnabledExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they were disabled\n", numEnabledExcluded);
            Debug.Log(numEnabledExcluded + " objects were excluded because they were disabled\n");
        }
        if (numOBuvExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they were had out of bounds uvs\n", numOBuvExcluded);
            Debug.Log(numOBuvExcluded + " objects were excluded because they had out of bounds uvs\n");
        }
        if (numLightmapExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they did not match lightmap filter.\n", numLightmapExcluded);
            Debug.Log(numLightmapExcluded + " objects did not match lightmap filter.\n");
        }
        if (numShaderExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they did not use the selected shader.\n", numShaderExcluded);
            Debug.Log(numShaderExcluded + " objects were excluded because they did not use the selected shader.\n");
        }
        if (numMatExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they did not use the selected material.\n", numMatExcluded);
            Debug.Log(numMatExcluded + " objects were excluded because they did not use the selected material.\n");
        }
        if (numRegExExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they did not match the regular expression.\n", numRegExExcluded);
            Debug.Log(numRegExExcluded + " objects were excluded because they did not match the regular expression.\n");
        }
        if (numAlreadyIncludedExcluded > 0)
        {
            sb.AppendFormat("   {0} objects were excluded because they did were already included in other bakers.\n", numAlreadyIncludedExcluded);
            Debug.Log(numAlreadyIncludedExcluded + " objects were excluded because they did were already included in other bakers.\n");
        }

        helpBoxString = sb.ToString();
        return(newMomObjs);
    }