string TestEmail(Settings settings)
    {
        string email = settings.Email;
        string smtpServer = settings.SmtpServer;
        string smtpServerPort = settings.SmtpServerPort.ToString();
        string smtpUserName = settings.SmtpUserName;
        string smtpPassword = settings.SmtpPassword;
        string enableSsl = settings.EnableSsl.ToString();

        var mail = new MailMessage
        {
            From = new MailAddress(email, smtpUserName),
            Subject = string.Format("Test mail from {0}", smtpUserName),
            IsBodyHtml = true
        };
        mail.To.Add(mail.From);
        var body = new StringBuilder();
        body.Append("<div style=\"font: 11px verdana, arial\">");
        body.Append("Success");
        if (HttpContext.Current != null)
        {
            body.Append(
                "<br /><br />_______________________________________________________________________________<br /><br />");
            body.AppendFormat("<strong>IP address:</strong> {0}<br />", Utils.GetClientIP());
            body.AppendFormat("<strong>User-agent:</strong> {0}", HttpContext.Current.Request.UserAgent);
        }

        body.Append("</div>");
        mail.Body = body.ToString();

        return Utils.SendMailMessage(mail, smtpServer, smtpServerPort, smtpUserName, smtpPassword, enableSsl.ToString());
    }
示例#2
0
		public void ButtonChart_Click(object sender, System.EventArgs e)
		{
			//We first request the data from the form (Default.aspx)
			string soups, salads, sandwiches, beverages, desserts;
            soups = TextBoxSoups.Text;
			salads = TextboxSalads.Text;
			sandwiches = TextboxSandwiches.Text;
			beverages = TextboxBeverages.Text;
			desserts   = TextboxDesserts.Text;
	
			//In this example, we're directly showing this data back on chart.
			//In your apps, you can do the required processing and then show the 
			//relevant data only.
	
			//Now that we've the data in variables, we need to convert this into XML.
			//The simplest method to convert data into XML is using string concatenation.	
            StringBuilder xmlData = new StringBuilder();
			//Initialize <chart> element
			xmlData.Append("<chart caption='Sales by Product Category' subCaption='For this week' showPercentValues='1' pieSliceDepth='30' showBorder='1'>");
			//Add all data
			xmlData.AppendFormat("<set label='Soups' value='{0}' />",soups);
			xmlData.AppendFormat("<set label='Salads' value='{0}' />",salads);
			xmlData.AppendFormat("<set label='Sandwiches' value='{0}' />", sandwiches);
            xmlData.AppendFormat("<set label='Beverages' value='{0}' />", beverages);
			xmlData.AppendFormat("<set label='Desserts' value='{0}' />",desserts);
			//Close <chart> element
			xmlData.Append("</chart>");
                        
			//Create the chart - Pie 3D Chart with data from xmlData
            LiteralChart.Text = FusionCharts.RenderChart("../FusionCharts/Pie3D.swf", "", xmlData.ToString(), "Sales", "500", "300", false, false);
		}
示例#3
0
    void Update()
    {
        elapsed += Time.deltaTime;
        if (elapsed > 1f)
        {
            elapsed = 0f;
            var sb = new StringBuilder();
            elapsed = 0f;
            Vector3 v = new Vector3(2, 3, 6);
            Vector3 w = new Vector3(7, 23, 1);

            var n = v.normalized;
            object[] arr = new object[] { n.x, n.y, n.z };
            Debug.Log(sb.AppendFormat("v.normalized = ({0}, {1}, {2})", arr).ToString());

            sb.Remove(0, sb.Length);
            var cross = Vector3.Cross(v, w);
            arr = new object[] { cross.x, cross.y, cross.z };
            Debug.Log(sb.AppendFormat("Cross(v, w) = ({0}, {1}, {2})", arr).ToString());

            Debug.Log("v.magnitude = " + v.magnitude);
            Debug.Log("w.magnitude = " + w.magnitude);
            Debug.Log("Dot(v, w) = " + Vector3.Dot(v, w));
            Debug.Log("Angle(v, w) = " + Vector3.Angle(v, w));

            var proj = Vector3.Project(v, w);
            Debug.Log("Project(v,w) = " + proj.ToString());

            v.Normalize();
            w.Normalize();
            Debug.Log("normalized v = " + v.ToString());
            Debug.Log("normalized w = " + w.ToString());
        }
	}
    private void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            // Do a raycast to find our selected tile
            Camera mainCamera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
            Vector2 position = mainCamera.ScreenToWorldPoint(Input.mousePosition);

            RaycastHit2D hit = Physics2D.Raycast(position, Vector2.zero, 0);
            if (hit)
            {
                StrategyTile tile = hit.collider.gameObject.GetComponent<StrategyTile>();
                tile.NumberOfClicks++;

                StringBuilder info = new StringBuilder();
                info.AppendFormat("Tile: {0}", tile.TileType);
                info.AppendLine();
                info.Append(tile.TileNote);
                info.AppendLine();
                info.AppendFormat("Clicks: {0}", tile.NumberOfClicks);
                this.uiText.text = info.ToString();
            }
            else
            {
                this.uiText.text = "No tile selected";
            }

            // Place the cursor
            GameObject cursor = GameObject.FindGameObjectWithTag("Cursor");
            position.x -= position.x % 16;
            position.y -= position.y % 16;
            cursor.transform.position = position;

        }
    }
示例#5
0
    private void BindData()
    {
        string fields = "[_name],[fullname],[state],[city],[jianjie]";
        string where = "[hangye]='" + tag + "'";
        string sql = "select {0} from [users] where {1} order by [_name]";
        sql = String.Format(sql, fields, where);

        DataTable dt = DB.GetTable(sql);

        StringBuilder sb = new StringBuilder();

        foreach (DataRow row in dt.Rows)
        {
            sb.Append("<div style='margin-top:16px;margin-left:14px;'>");
            sb.AppendFormat("<div class='ileft'><a href='/{0}{1}' title='{0}' target=_blank><img src='/upload/photo/{0}-s.jpg' {2} /></a></div>", row["_name"], Settings.Ext, Strings.UserSmallImageError);
            sb.AppendFormat("<div class='iright'><a class='bold' href='/{0}{1}' target=_blank>{0}</a> ({2})", row["_name"], Settings.Ext, row["fullname"]);

            if (row["state"].ToString() != "")
            {
                if (row["state"].ToString().Substring(0, 2) == row["city"].ToString().Substring(0, 2))
                {
                    sb.AppendFormat(" <a href='/city/{0}{1}'>{0}</a>", row["city"], Settings.Ext);
                }
                else
                {
                    sb.AppendFormat(" <a href='/city/{0}{1}'>{0}</a>,<a href='/city/{2}{1}'>{2}</a>", row["state"], Settings.Ext, row["city"]);
                }
            }
            sb.AppendFormat("<p><span style='color:#888888;'>简介:</span>{0}</p>", Tools.HtmlEncode(Tools.CutString(row["jianjie"].ToString(), 126)));
            sb.Append("</div><div class='clear'></div></div>");
        }
        lblDataList.Text = sb.ToString();
    }
示例#6
0
    private string buildMenu(string currentPage)
    {
        StringBuilder menu = new StringBuilder();

        foreach (var parentPage in BlogEngine.Core.Page.Pages.Where(p => !p.HasParentPage))
        {
            menu.AppendFormat("<li class=\"page_item\"><a href=\"{0}\" title=\"{1}\">{1}</a>", parentPage.RelativeLink, parentPage.Title);

            if (parentPage.HasChildPages)
            {
                menu.Append("<ul class=\"sub-menu\">");
                foreach (
                    var childPage in
                        BlogEngine.Core.Page.Pages.Where(p => p.Parent == parentPage.Id))
                {
                    menu.AppendFormat(
                        "<li class=\"page_item\"><a href=\"{0}\" title=\"{1}\">{1}</a></li>",
                        childPage.RelativeLink, childPage.Title);
                }
                menu.AppendFormat("</ul>");
            }

            menu.Append("</li>");
        }

        return menu.ToString();
    }
示例#7
0
    private static HtmlString Include(string path)
    {
        if (HttpRuntime.Cache[path] == null)
        {
            var absolute = HostingEnvironment.MapPath(path) ?? "";
            var ext = Path.GetExtension(absolute);
            var fmt = ext == ".js"
                ? "<script type=\"text/javascript\" src=\"{0}\"></script>\n"
                : "<link href=\"{0}\" rel=\"stylesheet\" />\n";
            var result = new StringBuilder();
#if DEBUG
            result.AppendFormat(fmt, path);
#else
            const string min = ".min";
            var dt = File.GetLastWriteTime(absolute);
            var f = Path.GetFileNameWithoutExtension(absolute);
            var d = path.Remove(path.LastIndexOf('/'));
            var t = $"v-{dt:yyMMddhhmmss}-";
            var minfile = $"{d}/{f}{min}{ext}";
            var p = File.Exists(HostingEnvironment.MapPath(minfile))
                ? $"{d}/{t}{f}{min}{ext}"
                : $"{d}/{t}{f}{ext}";
            result.AppendFormat(fmt, p);
#endif
            HttpRuntime.Cache.Insert(path, result.ToString(), new CacheDependency(absolute));
        }
        return new HtmlString(HttpRuntime.Cache[path] as string);
    }
        private string GetCharArrayInfo(char[] chars, int startIndex, int count)
        {
            StringBuilder sb = new StringBuilder();

            if (null == chars) return string.Empty;
            if (0 == chars.Length)
            {
                sb.Append("\nThe character array is zero-length array: {}");
            }
            else
            {
                sb.Append("\nThe character array is: {");
                for (int i = 0; i < chars.Length; ++i)
                {
                    if (0 == (i & 0xf)) sb.Append("\n");
                    sb.AppendFormat("\t\\u{0:X04}, ", (int)chars[i]);
                }
                sb.Append("}");
            }
            sb.AppendFormat("\nThe length of character array: {0}", chars.Length);
            sb.AppendFormat("\nStart index for encoding: {0}\nCount of character encoded: {1}",
                            startIndex, count);

            return sb.ToString();
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string likeElementForSearchingDB = string.Empty;

        if (Request.QueryString.Count == 3)
        {
            likeElementForSearchingDB = Request.QueryString[2];

        }

        PatientInfoDAL objPat_Info = new PatientInfoDAL();

        objPat_Info = new PatientInfoDAL();

        DataTable Doc_Names = objPat_Info.get_DoctorNames(likeElementForSearchingDB);

        var sb = new StringBuilder();
        for (int i = 0; i < Doc_Names.Rows.Count; i++)
        {
            switch (i)
            {
                case 0:
                    sb.AppendFormat(keyValueFormater, Doc_Names.Rows[i][2], string.Format("{1}, {0} - {2}", Doc_Names.Rows[i][1], Doc_Names.Rows[i][0], Doc_Names.Rows[i][3]), "{", "}");
                    break;
                default:
                    sb.AppendFormat(keyValueFormaterIntermediatElement, Doc_Names.Rows[i][2], string.Format("{1}, {0} - {2}", Doc_Names.Rows[i][1], Doc_Names.Rows[i][0], Doc_Names.Rows[i][3]), "{", "}");
                    break;
            }
        }
        Response.Write(string.Format(jasonPacketFormater, sb.ToString()));
    }
示例#10
0
    private string GetUserDataText(IUserContext uc)
    {
        var sb = new StringBuilder();

        var data = uc.Data;
        sb.AppendLine("Data<size=28>");
        sb.AppendFormat("RegisterTime: {0}\n", data.RegisterTime);
        sb.AppendFormat("LastLoginTime: {0}\n", data.LastLoginTime);
        sb.AppendFormat("LoginCount: {0}\n", data.LoginCount);
        sb.AppendLine("</size>");

        var achivements = uc.Achivements;
        sb.AppendLine("Achievement<size=28>");
        foreach (AchievementKey key in Enum.GetValues(typeof(AchievementKey)))
        {
            UserAchievement ach;
            if (achivements.TryGetValue((int)key, out ach))
            {
                if (ach.AchieveTime.HasValue)
                    sb.AppendFormat("{0}: Achieved({1})\n", key, ach.AchieveTime.Value);
                else
                    sb.AppendFormat("{0}: Progress({1})\n", key, ach.Value);
            }
        }
        sb.AppendLine("</size>");

        return sb.ToString();
    }
    /// <summary>
    /// 定数を管理するクラスを自動生成する
    /// </summary>
    /// <param name="className">クラスの名前</param>
    /// <param name="classInfo">なんのクラスか説明するコメント文</param>
    /// <param name="variableDic">定数名とその値をセットで登録したDictionary</param>
    /// <typeparam name="T">定数の型、stringかintかfloat</typeparam>
    public static void Create(string className, string classInfo, string[] value)
    {
        //コメント文とクラス名を入力
        StringBuilder builder = new StringBuilder();

        builder.AppendLine("/// <summary>");
        builder.AppendFormat("/// {0}", classInfo).AppendLine();
        builder.AppendLine("/// </summary>");
        builder.AppendFormat("namespace {0}", className).AppendLine("{");
        builder.Append("\t").AppendFormat("public enum SceneName").AppendLine("{");
        for (int i = 0; i < value.Length; i++)
        {
            builder.Append("\t\t").AppendFormat("{0},", value[i]).AppendLine("");
        }

        builder.Append("\t").AppendLine("}");
        builder.AppendLine("}");

        //書き出し、ファイル名はクラス名.cs
        string exportPath = "Assets/Scripts/Scripts/Constants/AutoCreating/" + className + ".cs";

        //書き出し先のディレクトリが無ければ作成
        string directoryName = Path.GetDirectoryName(exportPath);
        if (!Directory.Exists(directoryName))
        {
            Directory.CreateDirectory(directoryName);
        }

        File.WriteAllText(exportPath, builder.ToString(), Encoding.UTF8);
        AssetDatabase.Refresh(ImportAssetOptions.ImportRecursive);

        Debug.Log(className+"の作成が完了しました");
    }
示例#12
0
    public string ConvertToMessage(AttributeData attributeData)
    {
        var stringBuilder = new StringBuilder();
        var message = attributeData.Message;
        if (message != null)
        {
            message = message.Trim();
            message = message.Trim('.');
            stringBuilder.AppendFormat("{0}. ", message);
        }

        if (attributeData.Replacement != null)
        {
            stringBuilder.AppendFormat(ReplacementFormat, attributeData.Replacement);
        }

        if (assemblyVersion < attributeData.TreatAsErrorFromVersion)
        {
            stringBuilder.AppendFormat(TreatAsErrorFormat, attributeData.TreatAsErrorFromVersion.ToSemVer());
        }
        if (attributeData.ThrowsNotImplemented)
        {
            stringBuilder.Append(ThrowsNotImplementedText);
        }
        stringBuilder.AppendFormat(RemoveInVersionFormat, attributeData.RemoveInVersion.ToSemVer());

        return stringBuilder.ToString().Trim();
    }
示例#13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var sb = new StringBuilder();
        sb.AppendFormat(@"<ul class=""tin-view-navi-menus spa-view-navi-menus"">");
        sb.AppendFormat(@"<li>
        <a href=""/"" class=""tin-view-navi-menus-item home"">
        Trang chủ
        </a>
        </li>");
        sb.Append(
            @"<li><a class=""tin-view-navi-menus-item"" href=""/Spa-khuyen-mai/"">Spa khuyến mãi</a></li>");
        sb.AppendFormat(@"</ul>");
        txtPath = sb.ToString();

        this.Page.Header.Title = string.Format(Item.Ten + " Spa khuyến mãi, Spa giảm giá, spa voucher - Tạp chí spa");

        var meta = new HtmlMeta();
        meta.Name = "description";
        meta.Content = Item.MoTa;
        this.Page.Header.Controls.Add(meta);

        meta = new HtmlMeta();
        meta.Name = "og:description";
        meta.Content = Item.MoTa;
        this.Page.Header.Controls.Add(meta);

        meta = new HtmlMeta();
        meta.Name = "og:title";
        meta.Content = string.Format(Item.Ten + " Spa khuyến mãi, Spa giảm giá, spa voucher - Tạp chí spa");
        this.Page.Header.Controls.Add(meta);
    }
示例#14
0
    protected void Application_Error(Object sender, EventArgs e)
    {

        StringBuilder message = new StringBuilder();

        // String e1 = Context.Error.ToString();

        if (Request != null)
        {
            message.AppendFormat(uriFormat, Request.Path);
        }

        if (Server != null)
        {

            Exception ex;
            for (ex = Server.GetLastError(); ex != null; ex = ex.InnerException)
            {

                message.AppendFormat(exceptionFormat,
                    ex.GetType().Name,
                    ex.Message,
                    ex.StackTrace);
            }
        }

        Session["TheException"] = message.ToString();


    }
示例#15
0
    public override string ToString()
    {
        var arguments = new StringBuilder();

        arguments.AppendFormat("\"{0}\"", workingDirectory);

        if (!string.IsNullOrWhiteSpace(exec))
        {
            arguments.AppendFormat(" /exec \"{0}\"", exec);
        }

        if (!string.IsNullOrWhiteSpace(execArgs))
        {
            arguments.AppendFormat(" /execArgs \"{0}\"", execArgs);
        }

        if (!string.IsNullOrWhiteSpace(projectFile))
        {
            arguments.AppendFormat(" /proj \"{0}\"", projectFile);
        }

        if (!string.IsNullOrWhiteSpace(projectArgs))
        {
            arguments.AppendFormat(" /projargs \"{0}\"", projectArgs);
        }

        arguments.Append(additionalArguments);

        if (!string.IsNullOrWhiteSpace(logFile))
        {
            arguments.AppendFormat(" /l \"{0}\"", logFile);
        }

        return arguments.ToString();
    }
示例#16
0
    private void BindTopic()
    {
        string fields = "[t_id],[t_title],[t_read_cnt],[t_reply_cnt],[r_uptime],[g_id],[g_name]";
        string where = "[r_t_id]=[t_id] and [g_id]=[t_g_id] and [r_user_name]='" + username + "'";

        string sqlc = "select count(*) from [restore] where [r_user_name]='" + username + "'";
        int cnt = (int)DB.GetValue(sqlc);
        if (cnt == 0) return;

        pageCount = cnt / pageSize;
        if (cnt % pageSize > 0) pageCount++;
        pageIndex = Math.Max(0, pageIndex);
        pageIndex = Math.Min(pageCount - 1, pageIndex);

        DataTable dt = Data.GetPagingData("[restore],[topic],[group]", fields, "[r_uptime]", "[t_id]", pageIndex, pageSize, where, true);

        StringBuilder sb = new StringBuilder();
        foreach (DataRow row in dt.Rows)
        {
            sb.Append("<div class='topicitem'>");
            sb.AppendFormat("<a class='bold' href='/group/topic/{0}{1}'>{2}</a>", row["t_id"], Settings.Ext, Tools.HtmlEncode(row["t_title"].ToString()));
            sb.AppendFormat(" <a class='hui' href='/group/{0}{1}'>[{2}]</a>", row["g_id"], Settings.Ext, Tools.HtmlEncode(row["g_name"].ToString()));
            sb.AppendFormat("<p class='em'>浏览({0}) 回复({1}) 回复于 {2}</p>", row["t_read_cnt"], row["t_reply_cnt"], Tools.DateString(row["r_uptime"].ToString()));
            sb.Append("</div>");
        }
        lblMsgList.Text = sb.ToString();

        if (pageCount > 1)
        {
            string url = "/groups/reply/{0}" + Settings.Ext;

            lblPageList.Text = Tools.GetPager(pageIndex, pageCount, pageNumber, url);
        }
    }
示例#17
0
 static void PolynomMultiplication(int[] firstPol, int[] secondPol)
 {
     int[] multiPol = new int[firstPol.Length + secondPol.Length];
     int startPoint = 0;
     for (int i = 0; i < firstPol.Length; i++)
     {
         startPoint = i;
         for (int j = 0; j < secondPol.Length; j++)
         {
             multiPol[startPoint] = multiPol[startPoint] + (secondPol[j] * firstPol[i]);
             startPoint++;
         }
     }
     StringBuilder strMultiPol = new StringBuilder();
     if (multiPol[0] != 0)
     {
         strMultiPol.AppendFormat("{0} ", multiPol[0]);
     }
     for (int i = 1; i < multiPol.Length; i++)
     {
         if (multiPol[i] != 0 && multiPol[i] > 0)
         {
             strMultiPol.AppendFormat("+ {0}x^{1} ", multiPol[i], i);
         }
         if (multiPol[i] < 0)
         {
             strMultiPol.AppendFormat("{0}x^{1} ", multiPol[i], i);
         }
     }
     Console.WriteLine(strMultiPol.ToString());
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            int n, nResult1, nResult2;
            string cValor;
            StringBuilder sb = new StringBuilder();

            // Testes genéricos
            cValor = "29875782123";
            nResult1 = Funcoes.Modulo11Padrao(cValor, 9);
            nResult2 = Funcoes.Modulo11Especial(cValor, 9);
            sb.AppendFormat("<b>Exemplo Unibanco Pag 55-56: {0} => {1} , {2}</b><br>", cValor, nResult1, nResult2);

            // Teste de Geração em Massa
            sb.Append("<br><hr>");
            for (n = 0; n < 1000; n++)
            {
                cValor = n.ToString();
                nResult1 = Funcoes.Modulo11Padrao(cValor, 9);
                nResult2 = Funcoes.Modulo11Especial(cValor, 9);
                if (nResult1 == nResult2)
                    sb.AppendFormat("{0} => {1} , {2}<br>", cValor, nResult1, nResult2);
                else
                    sb.AppendFormat("<b>{0} => {1} , {2} </b><br>", cValor, nResult1, nResult2);
            }
            this.lblResult.Text = sb.ToString();
        }
    }
    void LogGestures(BaseGesture[] gestures, long frameKey)
    {
        StringBuilder logLine = new StringBuilder();
        logLine.AppendFormat("Gestures frame: {0}, contains {1} gestures\n", frameKey, gestures.Length);

        int gestureCounter = 0;

        foreach (BaseGesture gesture in gestures)
        {
            string additionalGestureData = "";
            // Update messages for gesture

            switch (gesture.Type)
            {
            case BaseGesture.GestureType.HEAD_POSITION:
            {
                HeadPositionGesture headPositionGesture = gesture as HeadPositionGesture;
                additionalGestureData = " (" + headPositionGesture.RegionIndex+")";
                break;
            }
            case BaseGesture.GestureType.WINGS:
            {
                WingsGesture wingsGesture = gesture as WingsGesture;
                additionalGestureData = " (" + wingsGesture.ArmsAngle + ")";
                break;
            }
            default:
                break;
            }
            logLine.AppendFormat("{0}. Gesture id: {1} -  {2}{3}\n",gestureCounter, gesture.ID , gesture.Description, additionalGestureData);
            gestureCounter++;
        }
        Debug.Log(logLine);
    }
示例#20
0
    private void LoadBannerRight()
    {
        ltlRight.Text = string.Empty;
        StringBuilder sb = new StringBuilder();

        //搜尋條件
        Dictionary<string, string> conditions = new Dictionary<string, string>();
        conditions.Add("NodeId", "7");
        conditions.Add("Flag", "1");
        conditions.Add("PageIndex", "0");
        conditions.Add("PageSize", "9");
        conditions.Add("Order", string.Format("order by {0}", "p.SortNo, p.PostId"));

        IList<PostVO> list = m_PostService.GetPostList(conditions);
        if (list != null && list.Count > 0)
        {
            foreach (PostVO post in list)
            {
                if (string.IsNullOrEmpty(post.LinkUrl))
                {
                    sb.AppendFormat("<div style=\"background-image: url('upload/{0}')\" class=\"contant_right_ad\" ></div>", post.PicFileName);
                }
                else
                {
                    sb.AppendFormat("<div style=\"background-image: url('upload/{0}'); cursor: pointer;\" class='contant_right_ad' onclick=\"window.location='{1}';\" ></div>", post.PicFileName, post.LinkUrl);
                }
            }

            ltlRight.Text = sb.ToString();
        }
    }
示例#21
0
    public String getMessagesMAXMIN()
    {
        if (Utility.currProjeto == null) return "var min = 0;var max = 100000;";

        String NumComps = Utility.currProjeto.getTemplateSetup("NCOMP");
        StringBuilder sb = new StringBuilder();

        if (Utility.currProjeto == null)
        {
            sb.Append("var min = 0;");
            sb.Append("var max = 100000;");
            return sb.ToString();
        }

        if (NumComps != "ALL")
        {
            int min, max;
            String[] MINMAX;
            MINMAX = NumComps.Replace("[", "").Replace("]", "").Split(',');
            min = int.Parse(MINMAX[0]);
            max = int.Parse(MINMAX[1]);

            sb.AppendFormat("var MensagemSelectedMIN = \"{0}\";", String.Format(dic.getResource(296), min.ToString(), max.ToString()));
            sb.AppendFormat("var MensagemSelectedMAX = \"{0}\";", String.Format(dic.getResource(296), min.ToString(), max.ToString()));
            sb.AppendFormat("var min = \"{0}\";", min.ToString());
            sb.AppendFormat("var max = \"{0}\";", max.ToString());
            return sb.ToString();
        }
        else
        {
            sb.Append("var min = 0;");
            sb.Append("var max = 100000;");
            return sb.ToString();
        }
    }
示例#22
0
    public static string Data_ToString(SerializeData data)
    {
        StringBuilder str = new StringBuilder();
        string name = data.property["Name"];
        str.AppendFormat("<{0} ", name);
        data.property.Remove("Name");
        foreach (var item in data.property)
        {
            str.AppendFormat("{0}=\"{1}\" ", item.Key, item.Value);
        }
        if (string.IsNullOrEmpty(data.childs_self))
        {
            str.Append("/>\r\n");
        }
        else
        {
            str.AppendFormat(">\r\n{0}</{1}>\r\n", data.childs_self, name);
        }

        foreach (var item in data.childs)
        {
            for (int i = 0; i < item.Value.Count; i++)
            {
                str.Append(Data_ToString(item.Value[i]));
            }
        }
        return str.ToString();
    }
示例#23
0
    private void PostToUrl(string URL, NameValueCollection col)
    {
        try
        {

            Response.Clear();

            StringBuilder sb = new StringBuilder();
            sb.Append("<html>");
            sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>");
            sb.AppendFormat("<form name='form' action='{0}' method='post'>", URL);
            foreach (string a in col)
            {
                sb.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", a, col[a]);
            }
            sb.Append("</form>");
            sb.Append("</body>");
            sb.Append("</html>");

            Response.Write(sb.ToString());

            Response.End();

        }
        catch (Exception ex)
        {
            return;
        }
    }
 static void PolynomSum(int[] firstPol, int[] secondPol)
 {
     List<int> sumPol = new List<int>();
     if (firstPol.Length >= secondPol.Length)
     {
         for (int i = 0; i < firstPol.Length; i++)
         {
             sumPol.Add(firstPol[i] + secondPol[i]);
         }
     }
     else
     {
         for (int i = 0; i < secondPol.Length; i++)
         {
             sumPol.Add(firstPol[i] + secondPol[i]);
         }
     }
     StringBuilder strSumPol = new StringBuilder();
     if (sumPol[0] != 0)
     {
         strSumPol.AppendFormat("{0} ", sumPol[0]);
     }
     for (int i = 1; i < sumPol.Count; i++)
     {
         if (sumPol[i] != 0 && sumPol[i] > 0)
         {
             strSumPol.AppendFormat("+ {0}x^{1} ", sumPol[i], i);
         }
         if (sumPol[i] < 0)
         {
             strSumPol.AppendFormat("{0}x^{1} ", sumPol[i], i);
         }
     }
     Console.WriteLine(strSumPol.ToString());
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder strLog = new StringBuilder();
        strLog.AppendFormat("OpenBestToneAccountV2:Page_Load");
        ParseSPTokenRequest();

        if (Result == 0)
        {

            strLog.AppendFormat(String.Format("CustID:{0},SPID{1},HeadFooter:{2},ReturnUrl:{3}", CustID, SPID, HeadFooter, ReturnUrl));
            this.myCustID.Value = CustID;
            this.myReturnUrl.Value = ReturnUrl;
            this.HiddenField_SPID.Value = SPID;
            if ("yes".Equals(HeadFooter))
            {
                this.header.Visible = true;
                this.footer.Visible = true;
            }
            else
            {
                this.header.Visible = false;
                this.footer.Visible = false;
            }

            phoneNum = this.mobile.Text;
            this.hidCheckMobile.Value = this.mobile.Text;
        }
        else
        {
            Response.Redirect("ErrorInfo.aspx?ErrorInfo=" + ErrMsg);

        }

        log(strLog.ToString());
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (CustomTableItem != null)
        {
            DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(CustomTableItem.CustomTableClassName);
            if (dci != null)
            {
                // Get class form definition
                FormInfo fi = FormHelper.GetFormInfo(dci.ClassName, false);

                string fieldCaption;
                FormFieldInfo ffi;
                IDataContainer item = CustomTableItem;

                StringBuilder sb = new StringBuilder();
                sb.Append("<table class=\"table table-hover\">");
                // Table header
                sb.AppendFormat("<thead><tr class=\"unigrid-head\"><th>{0}</th><th class=\"main-column-100\">{1}</th></tr></thead><tbody>", GetString("customtable.data.nametitle"), GetString("customtable.data.namevalue"));

                // Get macro resolver
                MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + dci.ClassName);

                // Go through the columns
                foreach (string columnName in item.ColumnNames)
                {
                    // Get field caption
                    ffi = fi.GetFormField(columnName);
                    if (ffi == null)
                    {
                        fieldCaption = columnName;
                    }
                    else
                    {
                        string caption = ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, resolver);
                        if (string.IsNullOrEmpty(caption))
                        {
                            fieldCaption = columnName;
                        }
                        else
                        {
                            fieldCaption = ResHelper.LocalizeString(caption);
                        }
                    }

                    sb.AppendFormat("<tr><td><strong>{0}</strong></td><td class=\"wrap-normal\">{1}</td></tr>", fieldCaption, HTMLHelper.HTMLEncode(ValidationHelper.GetString(item.GetValue(columnName), String.Empty)));
                }
                sb.Append("</tbody></table>");

                ltlContent.Text = sb.ToString();
            }
            else
            {
                ltlContent.Text = GetString("editedobject.notexists");
            }
        }
        else
        {
            ltlContent.Text = GetString("editedobject.notexists");
        }
    }
示例#27
0
 /// <summary>
 /// Each Group item represents a named capture group defined in the pattern. 
 /// This function can be used to parse and re-assemble each url into a template used in indexing by replacing each 
 /// Within each group the actual values captured by the pattern are collected.
 /// "Url" is the complete address of an Item in a parsed collection of JSON elements.
 /// "Node" represents each object or array within the hierarchy of the URL.
 /// "NodeKey" represents UUID for each object or array providing ownership and identifiable differences within a collection of the same.
 /// "itemKey" is the key in the key/value pair of any Json element.
 /// </summary>
 /// <param name="url">JsonUrl for a parsed Json element</param>
 //[SqlFunction()]
 public static String TemplateJsonUrl(String url)
 {
     StringBuilder template = new StringBuilder();
     string[] groups = rxUrl.GetGroupNames();
     foreach (Match m in rxUrl.Matches(url))
     {
         /*step through each object extracted from the url and reassemble it, replacing the UUID's with placeholders*/
         foreach (string s in groups)
         {
             Group g = m.Groups[s];
             CaptureCollection cc = g.Captures;
             foreach (Capture cap in cc)
             {
                 /*If this is a captured Node from the Url.*/
                 if (String.Equals(s, "node", sc))
                 {
                     template.AppendFormat(".{0}[{1}]", cap.Value, "{0}");
                 }
                 /*If this is a captured itemKey from the Url.*/
                 if (String.Equals(s, "itemKey", sc))
                 {
                     template.AppendFormat(".{0}", cap.Value);
                 }
             }
         }
     }
     return template.ToString();
 }
    public static string PrintBoardContent(int[,] board, string bgcolor,
		bool printTableEnd)
    {
        StringBuilder wr = new StringBuilder ();

        if (bgcolor == null) {
            wr.Append ("<table>");
        } else {
            wr.AppendFormat ("<table bgcolor=\"{0}\">", bgcolor);
        }

        wr.Append ("        <tr><td></td>");
        for (int x = 0 ; x < board.GetLength(1) ; ++x)
            wr.AppendFormat ("<td>{0}</td>", "abcdefghijklmnopqrstuvwxyz"[x]);
        wr.Append ("</tr>\n");

        for (int y = 0 ; y < board.GetLength(0) ; ++y) {
            wr.Append ("        <tr>");

            wr.AppendFormat ("<td>{0}</td>", y);
            for (int x = 0 ; x < board.GetLength(1) ; ++x) {
                wr.AppendFormat ("<td bgcolor=\"{0}\">+</td>",
                    board[y,x] == 1 ? OneColor :
                        (board[y,x] == -1 ? MOneColor : FreeColor));
            }
            wr.Append ("\n");
            wr.Append ("        </tr>\n");
        }
        if (printTableEnd)
            wr.Append ("        </table>\n");

        return (wr.ToString ());
    }
示例#29
0
    private void BindGroups()
    {
        string sql = "select * from [group] where [g_tags] like '%" + tag + "%'";
        DataTable dt = DB.GetTable(sql);

        int cnt = dt != null ? dt.Rows.Count : 0;

        if (cnt == 0) return;

        pageCount = cnt / pageSize;
        if (cnt % pageSize > 0) pageCount++;
        pageIndex = Math.Max(0, pageIndex);
        pageIndex = Math.Min(pageCount - 1, pageIndex);

        StringBuilder sb = new StringBuilder();
        foreach (DataRow row in dt.Rows)
        {
            sb.Append("<div style='margin-top:16px;margin-left:14px;'>");
            sb.AppendFormat("<div class='ileft'><a href='/{0}{1}' title='{0}' target=_blank><img src='/upload/photo/{0}-s.jpg' {2} /></a></div>", row["g_id"], Settings.Ext, Strings.GroupSmallImageError);
            sb.AppendFormat("<div class='iright'><a class='bold' href='/group/{0}{1}' target=_blank>{2}</a>", row["g_id"], Settings.Ext, Tools.HtmlEncode(row["g_name"].ToString()));
            sb.AppendFormat("<p>{0}</p>", Tools.HtmlEncode(row["g_description"].ToString()));
            sb.AppendFormat("<span class='em'>标签:{0}</span></div>", TagTools.ToLinks(row["g_tags"].ToString(), true));
            sb.Append("<div class='clear'></div></div>");
        }
        lblGroupList.Text = sb.ToString();

        if (pageCount > 1)
        {
            string url = String.Format("/group/tag/{0}/{1}{2}", tag, "{0}", Settings.Ext);
            lblPageList.Text = Tools.GetPager(pageIndex, pageCount, pageNumber, url);
        }
    }
示例#30
0
    private void PrepareAndSendEmail()
    {
        StringBuilder template = new StringBuilder(AppUtil.ReadEmailTemplate(AppConstants.EmailTemplate.GENERAL_EMAIL_TEMPLATE));
        if (template.Length > 0)
        {
            String senderName = SessionCache.CurrentUser == null ?
                        String.Format("{0}", AppUtil.Encode(txtName.Text.Trim()))
                        : String.Format("{0} {1} ({2})", AppUtil.Encode(SessionCache.CurrentUser.FirstName), AppUtil.Encode(SessionCache.CurrentUser.LastName), AppUtil.Encode(SessionCache.CurrentUser.Username));

            String toEmail = SessionCache.CurrentUser == null ?
                        String.Format("{0} <{1}>", senderName, txtEmail.Text.Trim())
                        : String.Format("{0} <{1}>", senderName, SessionCache.CurrentUser.Author_email);
            String fromEmail = ConfigReader.SupportEmail;
            String subject = AppUtil.Encode(txtSubject.Text.Trim());
            StringBuilder body = new StringBuilder(AppUtil.FormatText(txtComment.Text.Trim()));
            body.Append("<br /><br />");
            body.AppendFormat("<b>Sent By:</b> {0} <br />", senderName);
            body.AppendFormat("<b>From IP:</b> {0} <br />", AppUtil.GetRemoteIPAddress());

            template.Replace(AppConstants.ETConstants.MESSAGE, body.ToString());

            try
            {
                MailManager.SendMail(toEmail, String.Empty, String.Empty, fromEmail, subject, template.ToString());
            }
            catch { }
        }
    }
示例#31
0
        public void ReportDebugStreamBuffer(string readOrWrite, byte[] buffer, int offset, int bytesReadOrWritten)
        {
#if COMSTREAMLOGGING
            _debugWriter?.AppendFormat(".... {0}: {1} byte", readOrWrite, bytesReadOrWritten);
            _debugWriter.AppendFormat(" (");
            if (bytesReadOrWritten <= 4)
            {
                for (int i = 0; i < bytesReadOrWritten; ++i)
                {
                    _debugWriter.AppendFormat(" {0:X}", buffer[offset + i]);
                }
            }
            else
            {
                for (int i = 0; i < 2; ++i)
                {
                    _debugWriter.AppendFormat(" {0:X}", buffer[offset + i]);
                }
                _debugWriter.AppendFormat("...");
                for (int i = bytesReadOrWritten - 2; i < bytesReadOrWritten; ++i)
                {
                    _debugWriter.AppendFormat(" {0:X}", buffer[offset + i]);
                }
            }
            _debugWriter.AppendFormat(")\r\n");
#endif
        }
示例#32
0
        private static Packet ReadPacket(Stream ms, StringBuilder log)
        {
            var len = ReadLine(ms).ToInt(-1);

            log?.Append(len);
            if (len <= 0)
            {
                return(null);
            }
            //if (len <= 0) throw new InvalidDataException();

            var buf = new Byte[len + 2];
            var p   = 0;

            while (p < buf.Length)
            {
                // 等待,直到读完需要的数据,避免大包丢数据
                var count = ms.Read(buf, p, buf.Length - p);
                if (count <= 0)
                {
                    break;
                }

                p += count;
            }

            var pk = new Packet(buf, 0, p - 2);

            log?.AppendFormat(" {0}", pk.ToStr(null, 0, 1024)?.TrimEnd());

            return(pk);
        }
        public static StringBuilder AppendLineFormat([CanBeNull] this StringBuilder builder, [NotNull] string format, [NotNull][ItemCanBeNull] params object[] arguments)
        {
            Contract.Requires(format != null);
            Contract.Requires(arguments != null);

            builder?.AppendFormat(format, arguments);
            builder?.AppendLine();
            return(builder);
        }
示例#34
0
        internal bool ExitBreakCore(int delayMs, bool step = false, StringBuilder output = null)
        {
            Action continueAction = () =>
            {
                this.Protocol.SendEvent(new ContinuedEvent(threadId: this.stopThreadId));
                this.Continue(step);
            };

            if (delayMs != 0)
            {
                if (this.exitBreakTimer != null)
                {
                    output?.AppendLine("Another delayed ExitBreak operation is already pending!");
                    return(false);
                }

                // Wait the specified amount of time before leaving break mode.  Do this on a background thread to
                //  avoid blocking VS if the directive is issued from the Immediate window, so we can still switch
                //  processes, etc.
                this.exitBreakTimer = new Timer(
                    (state) =>
                {
                    continueAction();
                    if (this.exitBreakTimer != null)
                    {
                        this.exitBreakTimer.Dispose();
                        this.exitBreakTimer = null;
                    }
                },
                    null,
                    delayMs,
                    Timeout.Infinite);

                output?.AppendFormat(CultureInfo.InvariantCulture, "Will exit break state in {0}ms.", delayMs);
                return(true);
            }

            continueAction();
            output?.AppendLine("Forced process to exit break mode");
            return(true);
        }
示例#35
0
        protected void btnpay_Click(object sender, EventArgs e)
        {
            da = new SqlDataAdapter("select Acc_id,Stud_name from Account_detail where PRN_noForm_no='" + lbl_pnr.Text + "'", con);
            ds = new DataSet();
            da.Fill(ds, "tbres");
            // Label3.Text = ds.Tables[0].Rows[0][0].ToString();
            Session["Accid"] = ds.Tables[0].Rows[0][0].ToString();
            Session["name"]  = ds.Tables[0].Rows[0][1].ToString();


            da = new SqlDataAdapter("select Fee_id from Head_detail where Course='" + lbl_crs.Text + "' and sem='" + Session["sem"] + "'", con);
            ds = new DataSet();
            da.Fill(ds, "tbres");
            Label4.Text = ds.Tables[0].Rows[0][0].ToString();

            da = new SqlDataAdapter("select count(Receipt_id)+1 from Fees_detail", con);

            ds = new DataSet();
            da.Fill(ds, "tbres");
            string num = ds.Tables[0].Rows[0][0].ToString();

            cmd = new SqlCommand("Insert into Fees_detail (Acc_id,Receipt_id,Fee_id,Course,sem,Fee_type,time_span,Amount)values('" + Session["Accid"] + "','" + num + "'," + Label4.Text + ",'" + lbl_crs.Text + "','" + Session["sem"] + "','" + Session["type"] + " ',GETDATE(),'" + txt_fee.Text + "')", con);

            cmd.ExecuteNonQuery();
            Label5.Text = "inserted";

            da = new SqlDataAdapter("select Receipt_id,time_span,Course from Fees_detail where Acc_id='" + Session["Accid"] + "' ", con);
            ds = new DataSet();
            da.Fill(ds, "tbres");
            Session["rec"]  = ds.Tables[0].Rows[0][0].ToString();
            Session["time"] = ds.Tables[0].Rows[0][1].ToString();
            Session["Crse"] = ds.Tables[0].Rows[0][2].ToString();
            //Session["sem"] = ds.Tables[0].Rows[0][3].ToString();

            if (DropDownList1.Text == "Semester Fee")
            {
                da = new SqlDataAdapter("select Tution_fee,Library_fee,Sport_culture_fee,Other_fee,Exam_fee,Exam_form_fee,Amount from Head_detail where Course='" + Session["Crse"] + "' and sem=" + Session["sem"] + "", con);
                ds = new DataSet();
                da.Fill(ds, "tbres");
                Session["tut"]     = ds.Tables[0].Rows[0][0].ToString();
                Session["lib"]     = ds.Tables[0].Rows[0][1].ToString();
                Session["sprt"]    = ds.Tables[0].Rows[0][2].ToString();
                Session["othr"]    = ds.Tables[0].Rows[0][3].ToString();
                Session["exm"]     = ds.Tables[0].Rows[0][4].ToString();
                Session["exmfrm"]  = ds.Tables[0].Rows[0][5].ToString();
                Session["amt"]     = ds.Tables[0].Rows[0][6].ToString();
                Session["exmtype"] = "Semester Fee";
            }
            if (DropDownList1.Text == "Exam Fee")
            {
                da = new SqlDataAdapter("select Exam_fee from Head_detail where sem='" + Session["sem"] + "' and Course='" + lbl_crs.Text + "'", con);

                ds = new DataSet();
                da.Fill(ds, "tbres");
                Session["exm"]     = ds.Tables[0].Rows[0][0].ToString();
                Session["exmtype"] = "Exam Fee";
            }


            //Response.Redirect("Bill.aspx");

            string url = "https://www.paypal.com/us/cgi-bin/webscr";


            var builder = new StringBuilder();

            builder.Append(url);
            builder.AppendFormat("?cmd=_xclick&business={0}", HttpUtility.UrlEncode("*****@*****.**"));
            builder.Append("&lc=US&no_note=0&currency_code=USD");
            builder.AppendFormat("&amount={0}", string.Format("{0:F2}", decimal.Parse(txt_fee.Text)));

            Response.Redirect(builder.ToString());
            //Response.Redirect("Histroy.aspx");
        }
        private async Task CheckingPluginImagesRequiredComponents(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);
            var repositoryImage = new SdkMessageProcessingStepImageRepository(service);

            var listImages = await repositoryImage.GetAllImagesAsync();

            var queryImages = listImages
                            .OrderBy(image => image.Contains("sdkmessageprocessingstep.eventhandler") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.eventhandler").Value as EntityReference).Name : "Null")
                            .ThenBy(image => image.PrimaryObjectTypeCodeName)
                            .ThenBy(image => image.SecondaryObjectTypeCodeName)
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.sdkmessageid") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.sdkmessageid").Value as EntityReference).Name : "Null", new MessageComparer())
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.stage") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.stage").Value as OptionSetValue).Value : 0)
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.mode") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.mode").Value as OptionSetValue).Value : 0)
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.rank") ? (int)image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.rank").Value : 0)
                            .ThenBy(image => image.FormattedValues.ContainsKey("sdkmessageprocessingstep.statuscode") ? image.FormattedValues["sdkmessageprocessingstep.statuscode"] : "")
                            .ThenBy(image => image.FormattedValues.ContainsKey(SdkMessageProcessingStepImage.Schema.Attributes.imagetype) ? image.FormattedValues[SdkMessageProcessingStepImage.Schema.Attributes.imagetype] : "")
                            .ThenBy(image => image.Name)
                            .ThenBy(image => image.EntityAlias)
                            .ThenBy(image => image.Attributes1StringsSorted)
                            ;

            EntityMetadataRepository repositoryMetadata = new EntityMetadataRepository(service);
            var dependencyRepository = new DependencyRepository(service);

            var listMetaData = await repositoryMetadata.GetEntitiesWithAttributesAsync();

            var dictEntity = new Dictionary<Guid, EntityMetadata>();
            var dictAttribute = new Dictionary<Guid, AttributeMetadata>();

            foreach (var metaEntity in listMetaData)
            {
                dictEntity.Add(metaEntity.MetadataId.Value, metaEntity);

                foreach (var metaAttribute in metaEntity.Attributes)
                {
                    dictAttribute.Add(metaAttribute.MetadataId.Value, metaAttribute);
                }
            }

            bool hasInfo = false;

            foreach (var image in queryImages)
            {
                var listRequired = await dependencyRepository.GetRequiredComponentsAsync((int)ComponentType.SdkMessageProcessingStepImage, image.Id);

                var stepEntities = GetSetEntites(image);
                var stepAttributes = GetSetImageAttributes(image);

                var componentsEntities = GetSetComponentsEntites(listRequired, dictEntity);
                var componentsAttributes = GetSetComponentsAttributes(listRequired, dictAttribute);

                bool entitiesIsSame = stepEntities.SequenceEqual(componentsEntities);
                bool attributesIsSame = stepAttributes.SequenceEqual(componentsAttributes);

                string pluginType = image.Contains("sdkmessageprocessingstep.eventhandler") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.eventhandler").Value as EntityReference).Name : "Null";

                string sdkMessage = image.Contains("sdkmessageprocessingstep.sdkmessageid") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.sdkmessageid").Value as EntityReference).Name : "Null";
                int stage = image.Contains("sdkmessageprocessingstep.stage") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.stage").Value as OptionSetValue).Value : 0;
                int mode = image.Contains("sdkmessageprocessingstep.mode") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.mode").Value as OptionSetValue).Value : 0;
                int rank = image.Contains("sdkmessageprocessingstep.rank") ? (int)image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.rank").Value : 0;
                string status = image.FormattedValues.ContainsKey("sdkmessageprocessingstep.statuscode") ? image.FormattedValues["sdkmessageprocessingstep.statuscode"] : "";

                if (!entitiesIsSame || !attributesIsSame)
                {
                    hasInfo = true;

                    if (content.Length > 0)
                    {
                        content.AppendLine().AppendLine().AppendLine();
                    }

                    //handler.SetHeader("PluginType", "Primary Entity", "Secondary Entity", "Message", "Stage", "Rank", "Status", "ImageType", "Name", "EntityAlias", "Attributes");

                    content.AppendFormat("{0}   Primary {1}   Secondary {2}   Message {3}   Stage {4}   Rank {5}   Status {6}   ImageType {7}   Name {8}   EntityAlias {9}   Attributes {10}"
                        , pluginType
                        , image.PrimaryObjectTypeCodeName
                        , image.SecondaryObjectTypeCodeName
                        , sdkMessage
                        , SdkMessageProcessingStepRepository.GetStageName(stage, mode)
                        , rank.ToString()
                        , status
                        , image.FormattedValues[SdkMessageProcessingStepImage.Schema.Attributes.imagetype]
                        , image.Name
                        , image.EntityAlias
                        , image.Attributes1StringsSorted
                    ).AppendLine();

                    if (!entitiesIsSame)
                    {
                        content.AppendLine("Conflict in entites.");

                        content.Append("Entities in plugin step description");

                        if (stepEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }


                        content.Append("Entities in required components");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }

                    if (!attributesIsSame)
                    {
                        content.AppendLine("Conflict in attributes.");

                        content.Append("Attributes in plugin step description");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }

                        content.Append("Attributes in required components");

                        if (componentsAttributes.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }
                }
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No conflicts were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Images Required Components at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false));

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Images Required Components: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
示例#37
0
        private static void PerformBuild(string[] buildConfigs, BuildOptions options = BuildOptions.None)
        {
            int successCount = 0;
            int failCount    = 0;

            // Save current script defines, build constants, etc. so we can restore them after build.
            string buildConstantsPath        = BuildConstantsGenerator.FindFile();
            string currentBuildConstantsFile = null;

            if (!string.IsNullOrEmpty(buildConstantsPath))
            {
                currentBuildConstantsFile = FileUtil.GetUniqueTempPathInProject();
                File.Copy(buildConstantsPath, currentBuildConstantsFile);
            }

            DateTime buildTime;

            PerformPreBuild(out buildTime);

            for (int i = 0; i < buildConfigs.Length; i++)
            {
                BuildReleaseType  releaseType;
                BuildPlatform     platform;
                BuildArchitecture arch;
                BuildDistribution dist;
                string            configKey = buildConfigs[i];

                // Parse build config and perform build.
                string notification = string.Format("Building ({0}/{1}): ", i + 1, buildConfigs.Length);
                BuildSettings.projectConfigurations.ParseKeychain(configKey, out releaseType, out platform, out arch, out dist);
                bool success = BuildPlayer(notification, releaseType, platform, arch, dist, buildTime, options, configKey);

                if (success)
                {
                    ++successCount;
                }
                else
                {
                    ++failCount;
                }
            }

            PerformPostBuild();

            // Restore editor status.
            if (!string.IsNullOrEmpty(buildConstantsPath))
            {
                File.Copy(currentBuildConstantsFile, buildConstantsPath, true);
                File.Delete(currentBuildConstantsFile);
            }

            // Report success/failure.
            StringBuilder sb = new StringBuilder();

            if (failCount == 0)
            {
                sb.AppendFormat("{0} successful build{1}. No failures. ✔️",
                                successCount, successCount > 1 ? "s" : "");
            }
            else if (successCount == 0)
            {
                sb.AppendFormat("No successful builds. {0} failure{1}. ✖️",
                                failCount, failCount > 1 ? "s" : "");
            }
            else
            {
                sb.AppendFormat("{0} successful build{1}. {2} failure{3}.",
                                successCount, successCount > 1 ? "s" : "",
                                failCount, failCount > 1 ? "s" : "");
            }
            BuildNotificationList.instance.AddNotification(new BuildNotification(
                                                               BuildNotification.Category.Notification,
                                                               "Build Complete.", sb.ToString(),
                                                               true, null));

            // Open output folder if option is enabled.
            if (BuildSettings.basicSettings.openFolderPostBuild)
            {
                System.Diagnostics.Process.Start(BuildSettings.basicSettings.baseBuildFolder);
            }
        }
示例#38
0
        public ActionResult PaymentWall()
        {
            var sb       = new StringBuilder();
            var store    = Services.StoreContext.CurrentStore;
            var customer = Services.WorkContext.CurrentCustomer;
            var language = Services.WorkContext.WorkingLanguage;
            var settings = Services.Settings.LoadSetting <PayPalPlusPaymentSettings>(store.Id);
            var cart     = customer.GetCartItems(ShoppingCartType.ShoppingCart, store.Id);

            var pppMethod   = _paymentService.GetPaymentMethodBySystemName(PayPalPlusProvider.SystemName);
            var pppProvider = _paymentService.LoadPaymentMethodBySystemName(PayPalPlusProvider.SystemName, false, store.Id);

            var methods           = _paymentService.LoadActivePaymentMethods(customer, cart, store.Id, null, false);
            var session           = _httpContext.GetPayPalState(PayPalPlusProvider.SystemName);
            var redirectToConfirm = false;

            var model = new PayPalPlusCheckoutModel();

            model.ThirdPartyPaymentMethods = new List <PayPalPlusCheckoutModel.ThirdPartyPaymentMethod>();
            model.UseSandbox                  = settings.UseSandbox;
            model.LanguageCulture             = (language.LanguageCulture ?? "de_DE").Replace("-", "_");
            model.PayPalPlusPseudoMessageFlag = TempData["PayPalPlusPseudoMessageFlag"] as string;
            model.PayPalFee  = GetPaymentFee(pppProvider, cart);
            model.HasAnyFees = model.PayPalFee.HasValue();

            if (pppMethod != null)
            {
                model.FullDescription = pppMethod.GetLocalized(x => x.FullDescription, language);
            }

            if (customer.BillingAddress != null && customer.BillingAddress.Country != null)
            {
                model.BillingAddressCountryCode = customer.BillingAddress.Country.TwoLetterIsoCode;
            }

            foreach (var systemName in settings.ThirdPartyPaymentMethods)
            {
                var provider = methods.FirstOrDefault(x => x.Metadata.SystemName == systemName);
                if (provider != null)
                {
                    var methodModel = GetThirdPartyPaymentMethodModel(provider, settings, store);
                    model.ThirdPartyPaymentMethods.Add(methodModel);

                    var fee = GetPaymentFee(provider, cart);
                    if (fee.HasValue())
                    {
                        model.HasAnyFees = true;
                    }
                    if (sb.Length > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.AppendFormat("['{0}','{1}']", methodModel.MethodName.Replace("'", ""), fee);
                }
            }

            model.ThirdPartyFees = sb.ToString();

            // We must create a new paypal payment each time the payment wall is rendered because otherwise patch payment can fail
            // with "Item amount must add up to specified amount subtotal (or total if amount details not specified)".
            session.PaymentId   = null;
            session.ApprovalUrl = null;

            var result = PayPalService.EnsureAccessToken(session, settings);

            if (result.Success)
            {
                var protocol  = store.SslEnabled ? "https" : "http";
                var returnUrl = Url.Action("CheckoutReturn", "PayPalPlus", new { area = Plugin.SystemName }, protocol);
                var cancelUrl = Url.Action("CheckoutCancel", "PayPalPlus", new { area = Plugin.SystemName }, protocol);

                var paymentData = PayPalService.CreatePaymentData(settings, session, cart, returnUrl, cancelUrl);

                result = PayPalService.CreatePayment(settings, session, paymentData);
                if (result == null)
                {
                    // No payment required.
                    redirectToConfirm = true;
                }
                else if (result.Success && result.Json != null)
                {
                    foreach (var link in result.Json.links)
                    {
                        if (((string)link.rel).IsCaseInsensitiveEqual("approval_url"))
                        {
                            session.PaymentId   = result.Id;
                            session.ApprovalUrl = link.href;
                            break;
                        }
                    }
                }
                else
                {
                    model.ErrorMessage = result.ErrorMessage;
                }
            }
            else
            {
                model.ErrorMessage = result.ErrorMessage;
            }

            model.ApprovalUrl = session.ApprovalUrl;

            // There have been cases where the token was lost for unexplained reasons, so it is additionally stored in the database.
            var sessionData = session.AccessToken.HasValue() && session.PaymentId.HasValue()
                ? JsonConvert.SerializeObject(session)
                : null;

            _genericAttributeService.SaveAttribute(customer, PayPalPlusProvider.SystemName + ".SessionData", sessionData, store.Id);

            if (redirectToConfirm)
            {
                return(RedirectToAction("Confirm", "Checkout", new { area = "" }));
            }

            if (session.SessionExpired)
            {
                // Customer has been redirected because the session expired.
                session.SessionExpired = false;
                NotifyInfo(T("Plugins.SmartStore.PayPal.SessionExpired"));
            }

            return(View(model));
        }
        private async Task CheckingPluginImages(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);

            var search = await repository.FindAllAsync(null, string.Empty, string.Empty, string.Empty);

            var querySteps = search.SdkMessageProcessingStep
                            .OrderBy(ent => ent.EventHandler?.Name ?? "Unknown")
                            .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                            .ThenBy(ent => ent.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                            .ThenBy(ent => ent.Stage.Value)
                            .ThenBy(ent => ent.Mode.Value)
                            .ThenBy(ent => ent.Rank)
                            .ThenBy(ent => ent.Name)
                            ;

            int stepNumber = 1;

            bool hasInfo = false;

            foreach (var step in querySteps)
            {
                var queryImage = from image in search.SdkMessageProcessingStepImage
                                 where image.SdkMessageProcessingStepId != null
                                 where image.SdkMessageProcessingStepId.Id == step.Id
                                 orderby image.ImageType.Value, image.CreatedOn, image.Name
                                 select image;

                var preImages = queryImage.Where(im => im.ImageType.Value == 0 || im.ImageType.Value == 2);
                var postImages = queryImage.Where(im => im.ImageType.Value == 1 || im.ImageType.Value == 2);

                var preImagesByEntityAlias = preImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);
                var preImagesByName = preImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);

                var postImagesByEntityAlias = postImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);
                var postImagesByName = postImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);

                var hasDuplicatesPreImagesByEntityAlias = preImagesByEntityAlias.Count() > 0;
                var hasDuplicatesPreImagesByName = preImagesByName.Count() > 0;

                var hasDuplicatesPostImagesByEntityAlias = postImagesByEntityAlias.Count() > 0;
                var hasDuplicatesPostImagesByName = postImagesByName.Count() > 0;

                if (hasDuplicatesPreImagesByEntityAlias
                    || hasDuplicatesPreImagesByName
                    || hasDuplicatesPostImagesByEntityAlias
                    || hasDuplicatesPostImagesByName
                    )
                {
                    if (content.Length > 0)
                    {
                        content.AppendLine().AppendLine();
                    }

                    hasInfo = true;

                    content.AppendFormat("{0}. {1}", stepNumber, step.EventHandler?.Name ?? "Unknown").AppendLine();

                    content.AppendFormat("Entity '{0}',   Message '{1}',   Stage '{2}',   Rank {3},   Statuscode {4}"
                        , step.PrimaryObjectTypeCodeName
                        , step.SdkMessageId?.Name ?? "Unknown"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        ).AppendLine();

                    DescribeImages(content, stepNumber, hasDuplicatesPreImagesByEntityAlias, preImagesByEntityAlias, "Pre images duplicates by EntityAlias:");

                    DescribeImages(content, stepNumber, hasDuplicatesPreImagesByName, preImagesByName, "Pre images duplicates by Name:");

                    DescribeImages(content, stepNumber, hasDuplicatesPostImagesByEntityAlias, postImagesByEntityAlias, "Post images duplicates by EntityAlias:");

                    DescribeImages(content, stepNumber, hasDuplicatesPostImagesByName, postImagesByName, "Post images duplicates by Name:");

                    stepNumber++;
                }
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No duplicates were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Images Duplicates at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false));

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Images Duplicates: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
示例#40
0
        // /////// //
        // Methods //
        // /////// //

        /// <summary>
        /// Scan the navmesh for paths between randomized navigation points and
        /// print the percentage of valid paths between them.
        /// </summary>
        /// <param name="mapPieces">
        /// The map pieces, sorted by placing order.
        /// </param>
        public void ScanMesh(IReadOnlyList <MapPiece> mapPieces)
        {
            // Number of successful paths and attempts to find them
            int success = 0;
            int tries   = 0;

            // Where to store the calculated paths
            NavMeshPath storedPath = new NavMeshPath();

            // Obtain list of map piece bounds with running sum box volume
            // This will be required to evenly distribute nav points through
            // the map
            IReadOnlyList <(float sumVol, Bounds bounds)> pieceBounds =
                CalculateLocations(mapPieces);

            // Dictionary of nav points and their clusters
            IDictionary <NavPoint, ISet <NavPoint> > navPointClusters =
                new Dictionary <NavPoint, ISet <NavPoint> >();

            // Initialize navigation logger
            StringBuilder log = new StringBuilder("---- Nav Validation Log ");

            // Reinitialize RNG if requested by user
            if (_reinitializeRNG != ReInitRNG.No)
            {
                int seed = _reinitializeRNG == ReInitRNG.Randomly
                    ? System.Guid.NewGuid().GetHashCode()
                    : _seed;
                Random.InitState(seed);
                log.AppendFormat("(seed = {0})", seed);
            }
            else
            {
                log.Append("(no RNG reseed)");
            }
            log.Append(" ----\n");

            // Failures in finding navigation points
            int navPointFindFailures = 0;

            // Measure how long the navigation scanning takes
            Stopwatch stopwatch = Stopwatch.StartNew();

            // Initialize list of navigation points
            _navPoints = new List <NavPoint>(_navPointCount);

            // Initialize list for debugging origin and nav points
            _navOriginsDebug = new List <Origin2Nav>(_navPointCount);

            // Find random points in the navmesh and add them to the list
            for (int i = 0; i < _navPointCount; i++)
            {
                // Find nearest point in navmesh from the position of the
                // map piece
                Vector3?point = FindPointInNavMesh(pieceBounds);

                // Add found navigation point to list
                if (point.HasValue)
                {
                    _navPoints.Add(new NavPoint(point.Value));
                }
                else
                {
                    navPointFindFailures++;
                }
            }

            // Log any failures in finding nav points
            if (navPointFindFailures > 0)
            {
                log.AppendFormat("Unable to place {0} nav points out of {1}\n",
                                 navPointFindFailures, _navPointCount);
            }

            // Compare each navigation point to all others and check for a
            // valid connection
            for (int i = 0; i < _navPoints.Count; i++)
            {
                for (int j = i + 1; j < _navPoints.Count; j++)
                {
                    // Put nav points in locals vars, easier to work with
                    NavPoint p1 = _navPoints[i];
                    NavPoint p2 = _navPoints[j];

                    // Try and calculate a path between the two current points
                    bool path = NavMesh.CalculatePath(
                        p1.Point, p2.Point, NavMesh.AllAreas, storedPath);

                    // Increment number of tries
                    tries++;

                    // Has a complete path been found?
                    if (path && storedPath.status == NavMeshPathStatus.PathComplete)
                    {
                        // Cluster generation
                        if (p1.Isolated && p2.Isolated)
                        {
                            // If both points are isolated, create a new cluster
                            // for containing them
                            ISet <NavPoint> newCluster =
                                new HashSet <NavPoint>()
                            {
                                p1, p2
                            };

                            // Connect cluster to each point
                            navPointClusters.Add(p1, newCluster);
                            navPointClusters.Add(p2, newCluster);
                        }
                        else if (!p1.Isolated && p2.Isolated)
                        {
                            // If first point has cluster and the second does
                            // not, add second point to the first's cluster
                            navPointClusters[p1].Add(p2);
                            navPointClusters.Add(p2, navPointClusters[p1]);
                        }
                        else if (p1.Isolated && !p2.Isolated)
                        {
                            // If second point has cluster and the first does
                            // not, add first point to the seconds's cluster
                            navPointClusters[p2].Add(p1);
                            navPointClusters.Add(p1, navPointClusters[p2]);
                        }
                        else if (navPointClusters[p1] != navPointClusters[p2])
                        {
                            // If points are in different clusters, merge
                            // clusters
                            navPointClusters[p1].UnionWith(navPointClusters[p2]);
                            navPointClusters[p2] = navPointClusters[p1];
                        }

                        // Update points
                        p1.IncConnections();
                        p2.IncConnections();
                        success++;
                    }
                }
            }

            // If there are still isolated points, they should be placed in
            // their own cluster
            for (int i = 0; i < _navPoints.Count; i++)
            {
                NavPoint p = _navPoints[i];
                if (p.Isolated)
                {
                    ISet <NavPoint> newCluster = new HashSet <NavPoint>()
                    {
                        p
                    };
                    navPointClusters.Add(p, newCluster);
                }
            }

            // Stop stopwatch
            stopwatch.Stop();

            // Log good paths found vs total paths
            log.AppendFormat(
                "\tEvaluated {0} paths from {1} points, found {2} good paths ({3:p2} average), took {4} ms\n",
                tries, _navPoints.Count, success, (float)success / tries, stopwatch.ElapsedMilliseconds);

            // Get distinct clusters (sets), convert them to lists, sort them
            // by size (descending) and convert the resulting enumerable to a
            // list
            _clusters = navPointClusters.Values
                        .Distinct()
                        .Select(set => new Cluster(set))
                        .OrderByDescending(clust => clust.Points.Count)
                        .ToList();

            // Verify that the total number of points in clusters is the same
            // number of actually deployed points
            Assert.AreEqual(
                _navPoints.Count,
                _clusters.Select(clust => clust.Points.Count).Sum());

            // Log nav point clusters found
            log.AppendFormat(
                "\tA total of {0} navigation clusters were found:\n",
                _clusters.Count);
            for (int i = 0; i < _clusters.Count; i++)
            {
                log.AppendFormat("\t\tCluster {0:d2} has {1} points ({2:p2} of total)\n",
                                 i,
                                 _clusters[i].Points.Count,
                                 _clusters[i].Points.Count / (float)_navPoints.Count);
            }

            // Show log
            Debug.Log(log.ToString());

            // Sort nav point list by number of connections before returning
            _navPoints.Sort();

            // Update properties with this scan
            MeanValidConnections  = (float)success / tries;
            RelAreaLargestCluster = _clusters[0].Points.Count / (float)_navPoints.Count;
            ValidationTimeMillis  = (int)stopwatch.ElapsedMilliseconds;

            // Notify listeners that navigation information is ready
            OnNavInfoReady.Invoke(this);
        }
示例#41
0
        /// <summary>
        /// 生成商品的促销信息
        /// </summary>
        /// <param name="singlePromotionInfo">单品促销活动</param>
        /// <param name="buySendPromotionList">买送促销活动列表</param>
        /// <param name="fullSendPromotionInfo">满赠促销活动</param>
        /// <param name="fullCutPromotionInfo">满减促销活动</param>
        /// <returns></returns>
        public static string GeneratePromotionMsg(SinglePromotionInfo singlePromotionInfo, List <BuySendPromotionInfo> buySendPromotionList, FullSendPromotionInfo fullSendPromotionInfo, FullCutPromotionInfo fullCutPromotionInfo)
        {
            StringBuilder promotionMsg = new StringBuilder();

            //单品促销
            if (singlePromotionInfo != null)
            {
                //折扣类别
                switch (singlePromotionInfo.DiscountType)
                {
                case 0:    //折扣
                    promotionMsg.AppendFormat("折扣:{0}折<br/>", singlePromotionInfo.DiscountValue);
                    break;

                case 1:    //直降
                    promotionMsg.AppendFormat("直降:{0}元<br/>", singlePromotionInfo.DiscountValue);
                    break;

                case 2:    //折后价
                    promotionMsg.AppendFormat("折后价:{0}元<br/>", singlePromotionInfo.DiscountValue);
                    break;
                }

                //积分
                if (singlePromotionInfo.PayCredits > 0)
                {
                    promotionMsg.AppendFormat("赠送{0}:{1}<br/>", Credits.PayCreditName, singlePromotionInfo.PayCredits);
                }

                //优惠劵
                if (singlePromotionInfo.CouponTypeId > 0)
                {
                    CouponTypeInfo couponTypeInfo = Coupons.GetCouponTypeById(singlePromotionInfo.CouponTypeId);
                    if (couponTypeInfo != null)
                    {
                        promotionMsg.AppendFormat("赠送优惠劵:{0}<br/>", couponTypeInfo.Name);
                    }
                }
            }
            //买送促销
            if (buySendPromotionList != null && buySendPromotionList.Count > 0)
            {
                promotionMsg.Append("买送促销:");
                foreach (BuySendPromotionInfo buySendPromotionInfo in buySendPromotionList)
                {
                    promotionMsg.AppendFormat("买{0}送{1},", buySendPromotionInfo.BuyCount, buySendPromotionInfo.SendCount);
                }
                promotionMsg.Remove(promotionMsg.Length - 1, 1);
                promotionMsg.Append("<br/>");
            }
            //满赠促销
            if (fullSendPromotionInfo != null)
            {
                promotionMsg.Append("满赠促销:");
                promotionMsg.AppendFormat("满{0}元加{1}元<br/>", fullSendPromotionInfo.LimitMoney, fullSendPromotionInfo.AddMoney);
            }
            //满减促销
            if (fullCutPromotionInfo != null)
            {
                promotionMsg.Append("满减促销:");
                promotionMsg.AppendFormat("满{0}元减{1}元,", fullCutPromotionInfo.LimitMoney1, fullCutPromotionInfo.CutMoney1);
                if (fullCutPromotionInfo.LimitMoney2 > 0 && fullCutPromotionInfo.CutMoney2 > 0)
                {
                    promotionMsg.AppendFormat("满{0}元减{1}元,", fullCutPromotionInfo.LimitMoney2, fullCutPromotionInfo.CutMoney2);
                }
                if (fullCutPromotionInfo.LimitMoney3 > 0 && fullCutPromotionInfo.CutMoney3 > 0)
                {
                    promotionMsg.AppendFormat("满{0}元减{1}元,", fullCutPromotionInfo.LimitMoney3, fullCutPromotionInfo.CutMoney3);
                }
                promotionMsg.Remove(promotionMsg.Length - 1, 1);
                promotionMsg.Append("<br/>");
            }

            return(promotionMsg.Length > 0 ? promotionMsg.Remove(promotionMsg.Length - 5, 5).ToString() : "");
        }
示例#42
0
        private Output ConvertToVideoType(VideoFile input)
        {
            StringBuilder builder = new StringBuilder();
            Output        output  = new Output();

            if (!input.Found)
            {
                output.Message = input.Message;
            }
            else if (this._allowedext.IndexOf(Path.GetExtension(input.Path).ToLower()) < 0)
            {
                if (".xml.log.db".IndexOf(Path.GetExtension(input.Path)) < 0)
                {
                    output.Message = "\"" + input.Path + "\" " + Path.GetExtension(input.Path) + " files are not allowed to convert.";
                }
            }
            else
            {
                if (!input.infoGathered)
                {
                }
                string fileName       = string.Empty;
                string path           = string.Empty;
                string parameters     = string.Empty;
                string str4           = string.Empty;
                string outputSettings = this.GetOutputSettings();
                fileName = Path.GetFileName(input.Path);
                path     = Path.Combine(this._OutputPath, fileName);
                if (this._Settings.OutputAudioOnly)
                {
                    path = Path.ChangeExtension(path, this._Settings.OutputAudioType);
                }
                else
                {
                    path = Path.ChangeExtension(path, this._Settings.OutputVideoType);
                }
                parameters             = string.Format("-i \"{0}\" {1} -pass 1 -passlogfile \"{2}\" NULL.3gp", input.Path, outputSettings, input.Path + "_pass2");
                output.ConversionStart = DateTime.Now;
                str4       = this.RunProcess(parameters);
                parameters = string.Format("-i \"{0}\" {1} -pass 2 -passlogfile \"{2}\" \"{3}\"", new object[] { input.Path, outputSettings, input.Path + "_pass2", path });
                str4       = this.RunProcess(parameters);
                try
                {
                    if (File.Exists("NULL.3gp"))
                    {
                        File.Delete("NULL.3gp");
                    }
                    if (File.Exists(input.Path + "_pass2-0.log"))
                    {
                        File.Delete(input.Path + "_pass2-0.log");
                    }
                }
                catch (Exception ex)
                {
                    sb.AppendLine("Message - " + ex.Message + " Exception - " + ex.InnerException + " Source - " + ex.Source);
                }
                output.ConversionEnd = DateTime.Now;
                output.RawOutput     = str4;
                output.Success       = false;
                output.Message       = "Failed";
                if (str4.Contains("Output #"))
                {
                    Regex regex = new Regex("");
                    Match match = regex.Match("");
                    int   num   = 0;
                    int   num2  = 0;
                    if (this._Settings.OutputAudioOnly)
                    {
                        regex = new Regex(" audio:(?<AudioSize>[0-9]+)[k|K|m|M|g|G]B ", RegexOptions.IgnoreCase);
                        match = regex.Match(str4);
                        try
                        {
                            num = Convert.ToInt32(match.Groups["AudioSize"].Value);
                        }
                        catch (Exception ex)
                        {
                            sb.AppendLine("Message - " + ex.Message + " Exception - " + ex.InnerException + " Source - " + ex.Source);
                        }
                        if (num > 0)
                        {
                            output.Success = true;
                            output.Message = "File has successfully been converted";
                        }
                    }
                    else
                    {
                        match = new Regex("video:(?<VideoSize>[0-9]+)[k|K|m|M|g|G]B audio:(?<AudioSize>[0-9]+)[k|K|m|M|g|G]B ", RegexOptions.IgnoreCase).Match(str4);
                        try
                        {
                            num  = Convert.ToInt32(match.Groups["AudioSize"].Value);
                            num2 = Convert.ToInt32(match.Groups["VideoSize"].Value);
                        }
                        catch (Exception ex)
                        {
                            sb.AppendLine("Message - " + ex.Message + " Exception - " + ex.InnerException + " Source - " + ex.Source);
                        }
                        if ((num2 > 0) && (num > 0))
                        {
                            output.Success = true;
                            output.Message = "File has successfully been converted";
                        }
                        else if ((num2 > 0) && (num <= 0))
                        {
                            output.Message = output.Message + " (audio not converted)";
                        }
                        else if (num2 <= 0)
                        {
                            output.Message = output.Message + " (video not converted)";
                        }
                    }
                }
                else
                {
                    string[] strArray = str4.Split(new char[] { '\r' });
                    if (strArray.Length > 0)
                    {
                        string str6 = "";
                        if (strArray[strArray.Length - 1] == "\n")
                        {
                            str6 = strArray[strArray.Length - 2].Replace('\n', ' ').Trim();
                        }
                        else
                        {
                            str6 = strArray[strArray.Length - 1].Replace('\n', ' ').Trim();
                        }
                        if (string.IsNullOrEmpty(str6))
                        {
                            str6 = "Ffmpeg didn't return any output";
                        }
                        output.Message = str6;
                    }
                }
                if (output.Success && File.Exists(path))
                {
                    string str7 = Path.ChangeExtension(fileName, this._Settings.OutputVideoType);
                    output.FileName    = str7;
                    output.VideoStream = LoadMemoryStreamFromFile(path);
                    int num3 = this.ConvertedFileLimitInKB * 0x400;
                    if (output.VideoStream.Length > num3)
                    {
                        output.VideoStream = null;
                        output.Success     = false;
                        output.Message     = "Output file stream is larger than " + Utility.BytesToWords((long)num3);
                    }
                }
                try
                {
                    File.Delete(path);
                }
                catch (Exception ex)
                {
                    sb.AppendLine("Message - " + ex.Message + " Exception - " + ex.InnerException + " Source - " + ex.Source);
                }
                builder.AppendLine("[Input]= " + input.Path);
                builder.AppendLine("[Output]= " + path);
                builder.AppendLine();
                builder.AppendLine("[Ffmpeg History] ");
                builder.Append(str4);
                if (string.IsNullOrEmpty(str4))
                {
                    builder.Append("Ffmpeg didn't return any output");
                    builder.AppendLine();
                }
                builder.AppendLine();
                builder.AppendLine();
                builder.AppendLine("[Conversion Status]= " + output.Message);
                builder.AppendLine();
                builder.AppendFormat("[Conversion Start Time]= {0}", output.ConversionStart.ToLongTimeString());
                builder.AppendLine();
                builder.AppendFormat("[Conversion End Time]= {0}", output.ConversionEnd.ToLongTimeString());
                builder.AppendLine();
                builder.AppendFormat("[Total Time]= {0}", output.GetConversionTime());
            }
            if (this._LogOutput)
            {
                if (string.IsNullOrEmpty(builder.ToString()))
                {
                    return(output);
                }
                EncoderLog log = new EncoderLog();
                if (string.IsNullOrEmpty(this._LogPath))
                {
                    log.FilePath = Path.GetDirectoryName(input.Path);
                }
                else
                {
                    log.FilePath = this._LogPath;
                }
                log.WriteLog(builder.ToString());
            }
            return(output);
        }
        public void ProcessOrder(Cart cart, ShippingDetails shippingInfo)
        {
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.EnableSsl             = emailSettings.UseSsl;
                smtpClient.Host                  = emailSettings.ServerName;
                smtpClient.Port                  = emailSettings.ServerPort;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials
                    = new NetworkCredential(emailSettings.Username,
                                            emailSettings.Password);

                if (emailSettings.WriteAsFile)
                {
                    smtpClient.DeliveryMethod
                        = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    smtpClient.PickupDirectoryLocation = emailSettings.FileLocation;
                    smtpClient.EnableSsl = false;
                }

                StringBuilder body = new StringBuilder()
                                     .AppendLine("A new order has been submitted")
                                     .AppendLine("---")
                                     .AppendLine("Items");

                foreach (var line in cart.Lines)
                {
                    var subtotal = line.Product.Price * line.Quantity;
                    body.AppendFormat("{0} x {1} (subtotal: {2:c}", line.Quantity,
                                      line.Product.Name,
                                      subtotal);
                }

                body.AppendFormat("Total order value: {0:c}", cart.ComputeTotalValue())
                .AppendLine("---")
                .AppendLine("Ship to:")
                .AppendLine(shippingInfo.Name)
                .AppendLine(shippingInfo.Line1)
                .AppendLine(shippingInfo.Line2 ?? "")
                .AppendLine(shippingInfo.Line3 ?? "")
                .AppendLine(shippingInfo.City)
                .AppendLine(shippingInfo.State ?? "")
                .AppendLine(shippingInfo.Country)
                .AppendLine(shippingInfo.Zip)
                .AppendLine("---")
                .AppendFormat("Gift wrap: {0}",
                              shippingInfo.GiftWrap ? "Yes" : "No");

                MailMessage mailMessage = new MailMessage(
                    emailSettings.MailFromAdress,
                    emailSettings.MailToAdress,
                    "New order submitted!",
                    body.ToString());

                if (emailSettings.WriteAsFile)
                {
                    mailMessage.BodyEncoding = Encoding.ASCII;
                }

                smtpClient.Send(mailMessage);
            }
        }
        /// <summary>
        /// Processes the payments.
        /// </summary>
        /// <param name="gateway">The gateway.</param>
        /// <param name="batchNamePrefix">The batch name prefix.</param>
        /// <param name="payments">The payments.</param>
        /// <param name="batchUrlFormat">The batch URL format.</param>
        /// <param name="receiptEmail">The receipt email.</param>
        /// <returns></returns>
        public static string ProcessPayments( FinancialGateway gateway, string batchNamePrefix, List<Payment> payments, string batchUrlFormat = "", Guid? receiptEmail = null )
        {
            int totalPayments = 0;
            int totalAlreadyDownloaded = 0;
            int totalNoScheduledTransaction = 0;
            int totalAdded = 0;
            int totalReversals = 0;
            int totalStatusChanges = 0;

            var batches = new List<FinancialBatch>();
            var batchSummary = new Dictionary<Guid, List<Decimal>>();
            var initialControlAmounts = new Dictionary<Guid, decimal>();

            var txnPersonNames = new Dictionary<Guid, string>();

            var gatewayComponent = gateway.GetGatewayComponent();

            var newTransactions = new List<FinancialTransaction>();

            using ( var rockContext = new RockContext() )
            {
                var accountService = new FinancialAccountService( rockContext );
                var txnService = new FinancialTransactionService( rockContext );
                var batchService = new FinancialBatchService( rockContext );
                var scheduledTxnService = new FinancialScheduledTransactionService( rockContext );

                var contributionTxnType = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid() );

                var defaultAccount = accountService.Queryable()
                    .Where( a =>
                        a.IsActive &&
                        !a.ParentAccountId.HasValue &&
                        ( !a.StartDate.HasValue || a.StartDate.Value <= RockDateTime.Now ) &&
                        ( !a.EndDate.HasValue || a.EndDate.Value >= RockDateTime.Now )
                        )
                    .OrderBy( a => a.Order )
                    .FirstOrDefault();

                var batchTxnChanges = new Dictionary<Guid, List<string>>();
                var batchBatchChanges = new Dictionary<Guid, List<string>>();
                var scheduledTransactionIds = new List<int>();

                foreach ( var payment in payments.Where( p => p.Amount > 0.0M ) )
                {
                    totalPayments++;

                    var scheduledTransaction = scheduledTxnService.GetByScheduleId( payment.GatewayScheduleId, gateway.Id );
                    if ( scheduledTransaction != null )
                    {
                        // Find existing payments with same transaction code
                        var txns = txnService
                            .Queryable( "TransactionDetails" )
                            .Where( t => t.TransactionCode == payment.TransactionCode )
                            .ToList();

                        // Calculate whether a transaction needs to be added
                        var txnAmount = CalculateTransactionAmount( payment, txns );
                        if ( txnAmount != 0.0M )
                        {
                            scheduledTransactionIds.Add( scheduledTransaction.Id );
                            if ( payment.ScheduleActive.HasValue )
                            {
                                scheduledTransaction.IsActive = payment.ScheduleActive.Value;
                            }

                            var transaction = new FinancialTransaction();
                            transaction.FinancialPaymentDetail = new FinancialPaymentDetail();

                            transaction.Guid = Guid.NewGuid();
                            transaction.TransactionCode = payment.TransactionCode;
                            transaction.TransactionDateTime = payment.TransactionDateTime;
                            transaction.Status = payment.Status;
                            transaction.StatusMessage = payment.StatusMessage;
                            transaction.ScheduledTransactionId = scheduledTransaction.Id;
                            transaction.AuthorizedPersonAliasId = scheduledTransaction.AuthorizedPersonAliasId;
                            transaction.SourceTypeValueId = scheduledTransaction.SourceTypeValueId;
                            txnPersonNames.Add( transaction.Guid, scheduledTransaction.AuthorizedPersonAlias.Person.FullName );
                            transaction.FinancialGatewayId = gateway.Id;
                            transaction.TransactionTypeValueId = contributionTxnType.Id;

                            if ( txnAmount < 0.0M )
                            {
                                transaction.Summary = "Reversal for previous transaction that failed during processing." + Environment.NewLine;
                            }

                            var currencyTypeValue = payment.CurrencyTypeValue;
                            var creditCardTypevalue = payment.CreditCardTypeValue;

                            if ( scheduledTransaction.FinancialPaymentDetail != null )
                            {
                                if ( currencyTypeValue == null && scheduledTransaction.FinancialPaymentDetail.CurrencyTypeValueId.HasValue )
                                {
                                    currencyTypeValue = DefinedValueCache.Read( scheduledTransaction.FinancialPaymentDetail.CurrencyTypeValueId.Value );
                                }

                                if ( creditCardTypevalue == null && scheduledTransaction.FinancialPaymentDetail.CreditCardTypeValueId.HasValue )
                                {
                                    creditCardTypevalue = DefinedValueCache.Read( scheduledTransaction.FinancialPaymentDetail.CreditCardTypeValueId.Value );
                                }

                                transaction.FinancialPaymentDetail.AccountNumberMasked = scheduledTransaction.FinancialPaymentDetail.AccountNumberMasked;
                                transaction.FinancialPaymentDetail.NameOnCardEncrypted = scheduledTransaction.FinancialPaymentDetail.NameOnCardEncrypted;
                                transaction.FinancialPaymentDetail.ExpirationMonthEncrypted = scheduledTransaction.FinancialPaymentDetail.ExpirationMonthEncrypted;
                                transaction.FinancialPaymentDetail.ExpirationYearEncrypted = scheduledTransaction.FinancialPaymentDetail.ExpirationYearEncrypted;
                                transaction.FinancialPaymentDetail.BillingLocationId = scheduledTransaction.FinancialPaymentDetail.BillingLocationId;
                            }

                            if ( currencyTypeValue != null )
                            {
                                transaction.FinancialPaymentDetail.CurrencyTypeValueId = currencyTypeValue.Id;
                            }
                            if ( creditCardTypevalue != null )
                            {
                                transaction.FinancialPaymentDetail.CreditCardTypeValueId = creditCardTypevalue.Id;
                            }

                            // Try to allocate the amount of the transaction based on the current scheduled transaction accounts
                            decimal remainingAmount = Math.Abs( txnAmount );
                            foreach ( var detail in scheduledTransaction.ScheduledTransactionDetails.Where( d => d.Amount != 0.0M ) )
                            {
                                var transactionDetail = new FinancialTransactionDetail();
                                transactionDetail.AccountId = detail.AccountId;

                                if ( detail.Amount <= remainingAmount )
                                {
                                    // If the configured amount for this account is less than or equal to the remaining
                                    // amount, allocate the configured amount
                                    transactionDetail.Amount = detail.Amount;
                                    remainingAmount -= detail.Amount;
                                }
                                else
                                {
                                    // If the configured amount is greater than the remaining amount, only allocate
                                    // the remaining amount
                                    transaction.Summary += "Note: Downloaded transaction amount was less than the configured allocation amounts for the Scheduled Transaction.";
                                    transactionDetail.Amount = remainingAmount;
                                    transactionDetail.Summary = "Note: The downloaded amount was not enough to apply the configured amount to this account.";
                                    remainingAmount = 0.0M;
                                }

                                transaction.TransactionDetails.Add( transactionDetail );

                                if ( remainingAmount <= 0.0M )
                                {
                                    // If there's no amount left, break out of details
                                    break;
                                }
                            }

                            // If there's still amount left after allocating based on current config, add the remainder
                            // to the account that was configured for the most amount
                            if ( remainingAmount > 0.0M )
                            {
                                transaction.Summary += "Note: Downloaded transaction amount was greater than the configured allocation amounts for the Scheduled Transaction.";
                                var transactionDetail = transaction.TransactionDetails
                                    .OrderByDescending( d => d.Amount )
                                    .FirstOrDefault();
                                if ( transactionDetail == null && defaultAccount != null )
                                {
                                    transactionDetail = new FinancialTransactionDetail();
                                    transactionDetail.AccountId = defaultAccount.Id;
                                    transaction.TransactionDetails.Add( transactionDetail );
                                }
                                if ( transactionDetail != null )
                                {
                                    transactionDetail.Amount += remainingAmount;
                                    transactionDetail.Summary = "Note: Extra amount was applied to this account.";
                                }
                            }

                            // If the amount to apply was negative, update all details to be negative (absolute value was used when allocating to accounts)
                            if ( txnAmount < 0.0M )
                            {
                                foreach ( var txnDetail in transaction.TransactionDetails )
                                {
                                    txnDetail.Amount = 0 - txnDetail.Amount;
                                }
                            }

                            // Get the batch
                            var batch = batchService.Get(
                                batchNamePrefix,
                                currencyTypeValue,
                                creditCardTypevalue,
                                transaction.TransactionDateTime.Value,
                                gateway.GetBatchTimeOffset(),
                                batches );

                            var batchChanges = new List<string>();
                            if ( batch.Id != 0 )
                            {
                                initialControlAmounts.AddOrIgnore( batch.Guid, batch.ControlAmount );
                            }
                            batch.ControlAmount += transaction.TotalAmount;

                            batch.Transactions.Add( transaction );

                            if ( txnAmount > 0.0M && receiptEmail.HasValue )
                            {
                                newTransactions.Add( transaction );
                            }

                            // Add summary
                            if ( !batchSummary.ContainsKey( batch.Guid ) )
                            {
                                batchSummary.Add( batch.Guid, new List<Decimal>() );
                            }
                            batchSummary[batch.Guid].Add( txnAmount );

                            if ( txnAmount > 0.0M )
                            {
                                totalAdded++;
                            }
                            else
                            {
                                totalReversals++;
                            }
                        }
                        else
                        {
                            totalAlreadyDownloaded++;

                            foreach ( var txn in txns.Where( t => t.Status != payment.Status || t.StatusMessage != payment.StatusMessage ) )
                            {
                                txn.Status = payment.Status;
                                txn.StatusMessage = payment.StatusMessage;
                                totalStatusChanges++;
                            }
                        }
                    }
                    else
                    {
                        totalNoScheduledTransaction++;
                    }
                }

                rockContext.SaveChanges();

                // Queue a transaction to update the status of all affected scheduled transactions
                var updatePaymentStatusTxn = new Rock.Transactions.UpdatePaymentStatusTransaction( gateway.Id, scheduledTransactionIds );
                Rock.Transactions.RockQueue.TransactionQueue.Enqueue( updatePaymentStatusTxn );

                if ( receiptEmail.HasValue )
                {
                    // Queue a transaction to send receipts
                    var newTransactionIds = newTransactions.Select( t => t.Id ).ToList();
                    var sendPaymentReceiptsTxn = new Rock.Transactions.SendPaymentReceipts( receiptEmail.Value, newTransactionIds );
                    Rock.Transactions.RockQueue.TransactionQueue.Enqueue( sendPaymentReceiptsTxn );
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat( "<li>{0} {1} downloaded.</li>", totalPayments.ToString( "N0" ),
                ( totalPayments == 1 ? "payment" : "payments" ) );

            if ( totalAlreadyDownloaded > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} previously downloaded and {2} already been added.</li>", totalAlreadyDownloaded.ToString( "N0" ),
                    ( totalAlreadyDownloaded == 1 ? "payment was" : "payments were" ),
                    ( totalAlreadyDownloaded == 1 ? "has" : "have" ) );
            }

            if ( totalStatusChanges > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} previously downloaded but had a change of status.</li>", totalStatusChanges.ToString( "N0" ),
                ( totalStatusChanges == 1 ? "payment was" : "payments were" ) );
            }

            if ( totalNoScheduledTransaction > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} could not be matched to an existing scheduled payment profile.</li>", totalNoScheduledTransaction.ToString( "N0" ),
                    ( totalNoScheduledTransaction == 1 ? "payment" : "payments" ) );
            }

            sb.AppendFormat( "<li>{0} {1} successfully added.</li>", totalAdded.ToString( "N0" ),
                ( totalAdded == 1 ? "payment was" : "payments were" ) );

            if ( totalReversals > 0 )
            {
                sb.AppendFormat( "<li>{0} {1} added as a reversal to a previous transaction.</li>", totalReversals.ToString( "N0" ),
                    ( totalReversals == 1 ? "payment was" : "payments were" ) );
            }

            foreach ( var batchItem in batchSummary )
            {
                int items = batchItem.Value.Count;
                if ( items > 0 )
                {
                    var batch = batches
                        .Where( b => b.Guid.Equals( batchItem.Key ) )
                        .FirstOrDefault();

                    string batchName = string.Format( "'{0} ({1})'", batch.Name, batch.BatchStartDateTime.Value.ToString( "d" ) );
                    if ( !string.IsNullOrWhiteSpace( batchUrlFormat ) )
                    {
                        batchName = string.Format( "<a href='{0}'>{1}</a>", string.Format( batchUrlFormat, batch.Id ), batchName );
                    }

                    decimal sum = batchItem.Value.Sum();

                    string summaryformat = items == 1 ?
                        "<li>{0} transaction of {1} was added to the {2} batch.</li>" :
                        "<li>{0} transactions totaling {1} were added to the {2} batch</li>";

                    sb.AppendFormat( summaryformat, items.ToString( "N0" ), sum.FormatAsCurrency(), batchName );
                }
            }

            return sb.ToString();
        }
示例#45
0
        /// <summary>
        /// Returns the raw REST URI which can be executed in a browser or using curl.
        /// </summary>
        /// <returns></returns>
        public Uri RawUri()
        {
            var sb = new StringBuilder();

            sb.Append(_baseUri);

            if (!_baseUri.EndsWith(ForwardSlash))
            {
                sb.Append(ForwardSlash);
            }

            if (!string.IsNullOrWhiteSpace(_bucketName) && !_baseUri.Contains(_bucketName))
            {
                sb.Append(_bucketName);
                sb.Append(ForwardSlash);
            }
            sb.Append(Design);
            sb.Append(ForwardSlash);

            if (_development.HasValue && _development.Value)
            {
                sb.Append(DevelopmentViewPrefix);
            }

            sb.Append(_designDoc);
            sb.Append(ForwardSlash);
            sb.Append(ViewMethod);
            sb.Append(ForwardSlash);
            sb.Append(_viewName);
            sb.Append(QueryOperator);

            if (_staleState != StaleState.None)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Stale, _staleState.ToLowerString());
            }
            if (_descending.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Descending, _descending.ToLowerString());
            }
            if (_continueOnError.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.OnError, _continueOnError.Value ? "continue" : "stop");
            }
            if (_endDocId != null)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.EndKeyDocId, _endDocId);
            }
            if (_endKey != null)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.EndKey, _endKey);
            }
            if (_fullSet.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.FullSet, _fullSet.ToLowerString());
            }
            if (_group.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Group, _group.ToLowerString());
            }
            if (_groupLevel.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.GroupLevel, _groupLevel);
            }
            if (_inclusiveEnd.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.InclusiveEnd, _inclusiveEnd.ToLowerString());
            }
            if (_key != null)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Key, _key);
            }
            if (_keys != null)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Keys, _keys);
            }
            if (_limit.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Limit, _limit);
            }
            if (_reduce.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Reduce, _reduce.ToLowerString());
            }
            if (_startKey != null)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.StartKey, _startKey);
            }
            if (_startKeyDocId != null)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.StartKeyDocId, _startKeyDocId);
            }
            if (_skipCount.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.Skip, _skipCount);
            }
            if (_connectionTimeout.HasValue)
            {
                sb.AppendFormat(QueryArgPattern, QueryArguments.ConnectionTimeout, _connectionTimeout);
            }

            var requestUri = sb.ToString().TrimEnd('&');

            Log.Debug(m => m(requestUri));
            return(new Uri(requestUri));
        }
 private static string GetParamsPrototype(List<VariableInfo> variableList)
 {
     var sb = new StringBuilder();
     variableList.ForEach((v) => sb.AppendFormat("{0}{1} {2}, ", v.IsReturnDataType ? "ref " : "", v.DataType, v.Name));
     return sb.ToString().TrimEnd(',', ' ');
 }
 private static string GetRawParamsList(List<VariableInfo> variableList)
 {
     var sb = new StringBuilder();
     variableList.ForEach((v) => sb.AppendFormat("{0}, ", v.Name));
     return sb.ToString().TrimEnd(',', ' ');
 }
        private ShippingOption RequestShippingOption(string zipPostalCodeFrom,
                                                     string zipPostalCodeTo, string countryCode, string serviceType,
                                                     int weight, int length, int width, int height, int quantity)
        {
            var shippingOption = new ShippingOption();
            var sb             = new StringBuilder();

            sb.AppendFormat(GetGatewayUrl());
            sb.AppendFormat("?Pickup_Postcode={0}&", zipPostalCodeFrom);
            sb.AppendFormat("Destination_Postcode={0}&", zipPostalCodeTo);
            sb.AppendFormat("Country={0}&", countryCode);
            sb.AppendFormat("Service_Type={0}&", serviceType);
            sb.AppendFormat("Weight={0}&", weight);
            sb.AppendFormat("Length={0}&", length);
            sb.AppendFormat("Width={0}&", width);
            sb.AppendFormat("Height={0}&", height);
            sb.AppendFormat("Quantity={0}", quantity);

            HttpWebRequest request = WebRequest.Create(sb.ToString()) as HttpWebRequest;

            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded";
            //byte[] reqContent = Encoding.ASCII.GetBytes(sb.ToString());
            //request.ContentLength = reqContent.Length;
            //using (Stream newStream = request.GetRequestStream())
            //{
            //    newStream.Write(reqContent, 0, reqContent.Length);
            //}

            WebResponse response = request.GetResponse();
            string      rspContent;

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                rspContent = reader.ReadToEnd();
            }

            string[] tmp = rspContent.Split(new char[] { '\n' }, 3);
            if (tmp.Length != 3)
            {
                throw new NopException("Response is not valid.");
            }

            var rspParams = new NameValueCollection();

            foreach (string s in tmp)
            {
                string[] tmp2 = s.Split(new char[] { '=' });
                if (tmp2.Length != 2)
                {
                    throw new NopException("Response is not valid.");
                }
                rspParams.Add(tmp2[0].Trim(), tmp2[1].Trim());
            }


            string err_msg = rspParams["err_msg"];

            if (!err_msg.ToUpperInvariant().StartsWith("OK"))
            {
                throw new NopException(err_msg);
            }

            shippingOption.Name        = serviceType;
            shippingOption.Description = String.Format("{0} Days", rspParams["days"]);
            shippingOption.Rate        = Decimal.Parse(rspParams["charge"]);

            return(shippingOption);
        }
        public void LoadPostProcess()
        {
            // Remove invalid blueprint classes
            for (int i = 0; i < BlueprintClasses.Count;)
            {
                if (!BlueprintClassCanBeUsed(BlueprintClasses[i]))
                {
                    BlueprintClasses.RemoveAt(i);
                }
                else
                {
                    ++i;
                }
            }

            // Set the constraint icons only if all the blueprint classes agree upon them
            string firstInputIcon  = null;
            string firstOutputIcon = null;

            if (BlueprintClasses.Count != 0)
            {
                firstInputIcon  = BlueprintClasses[0].InputConstraintIcon;
                firstOutputIcon = BlueprintClasses[0].OutputConstraintIcon;

                for (int i = 1; i < BlueprintClasses.Count; ++i)
                {
                    if (BlueprintClasses[i].InputConstraintIcon != firstInputIcon)
                    {
                        firstInputIcon = null;
                    }
                    if (BlueprintClasses[i].OutputConstraintIcon != firstOutputIcon)
                    {
                        firstOutputIcon = null;
                    }
                }
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat(MySpaceTexts.ToolTipItemFilter_GenericProductionBlockInput, DisplayNameText);
            InputInventoryConstraint = new MyInventoryConstraint(sb.ToString(), firstInputIcon);

            sb = new StringBuilder();
            sb.AppendFormat(MySpaceTexts.ToolTipItemFilter_GenericProductionBlockOutput, DisplayNameText);
            OutputInventoryConstraint = new MyInventoryConstraint(sb.ToString(), firstOutputIcon);

            for (int i = 0; i < BlueprintClasses.Count; ++i)
            {
                foreach (var blueprint in BlueprintClasses[i])
                {
                    foreach (var input in blueprint.Prerequisites)
                    {
                        InputInventoryConstraint.Add(input.Id);
                    }
                    foreach (var output in blueprint.Results)
                    {
                        OutputInventoryConstraint.Add(output.Id);
                    }
                }
            }
        }
        /// <summary>
        /// Computes an AWS4 signature for a request, ready for inclusion as an
        /// 'Authorization' header.
        /// </summary>
        /// <param name="headers">
        /// The request headers; 'Host' and 'X-Amz-Date' will be added to this set.
        /// </param>
        /// <param name="queryParameters">
        /// Any query parameters that will be added to the endpoint. The parameters
        /// should be specified in canonical format.
        /// </param>
        /// <param name="bodyHash">
        /// Precomputed SHA256 hash of the request body content; this value should also
        /// be set as the header 'X-Amz-Content-SHA256' for non-streaming uploads.
        /// </param>
        /// <param name="awsAccessKey">
        /// The user's AWS Access Key.
        /// </param>
        /// <param name="awsSecretKey">
        /// The user's AWS Secret Key.
        /// </param>
        /// <returns>
        /// The computed authorization string for the request. This value needs to be set as the
        /// header 'Authorization' on the subsequent HTTP request.
        /// </returns>
        public string ComputeSignature(IDictionary <string, string> headers,
                                       string queryParameters,
                                       string bodyHash,
                                       string awsAccessKey,
                                       string awsSecretKey)
        {
            // first get the date and time for the subsequent request, and convert to ISO 8601 format
            // for use in signature generation
            var requestDateTime = DateTime.UtcNow;
            var dateTimeStamp   = requestDateTime.ToString(ISO8601BasicFormat, CultureInfo.InvariantCulture);

            // update the headers with required 'x-amz-date' and 'host' values
            headers.Add(X_Amz_Date, dateTimeStamp);

            var hostHeader = EndpointUri.Host;

            if (!EndpointUri.IsDefaultPort)
            {
                hostHeader += ":" + EndpointUri.Port;
            }
            headers.Add("Host", hostHeader);

            // canonicalize the headers; we need the set of header names as well as the
            // names and values to go into the signature process
            var canonicalizedHeaderNames = CanonicalizeHeaderNames(headers);
            var canonicalizedHeaders     = CanonicalizeHeaders(headers);

            // if any query string parameters have been supplied, canonicalize them
            // (note this sample assumes any required url encoding has been done already)
            var canonicalizedQueryParameters = string.Empty;

            if (!string.IsNullOrEmpty(queryParameters))
            {
                var paramDictionary = queryParameters.Split('&').Select(p => p.Split('='))
                                      .ToDictionary(nameval => nameval[0],
                                                    nameval => nameval.Length > 1
                                                                        ? nameval[1] : "");

                var sb        = new StringBuilder();
                var paramKeys = new List <string>(paramDictionary.Keys);
                paramKeys.Sort(StringComparer.Ordinal);
                foreach (var p in paramKeys)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append("&");
                    }
                    sb.AppendFormat("{0}={1}", p, paramDictionary[p]);
                }

                canonicalizedQueryParameters = sb.ToString();
            }

            // canonicalize the various components of the request
            var canonicalRequest = CanonicalizeRequest(EndpointUri,
                                                       HttpMethod,
                                                       canonicalizedQueryParameters,
                                                       canonicalizedHeaderNames,
                                                       canonicalizedHeaders,
                                                       bodyHash);

            Logger.LogDebug($"\nCanonicalRequest:\n{canonicalRequest}");

            // generate a hash of the canonical request, to go into signature computation
            var canonicalRequestHashBytes
                = CanonicalRequestHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(canonicalRequest));

            // construct the string to be signed
            var stringToSign = new StringBuilder();

            var dateStamp = requestDateTime.ToString(DateStringFormat, CultureInfo.InvariantCulture);
            var scope     = string.Format("{0}/{1}/{2}/{3}",
                                          dateStamp,
                                          Region,
                                          Service,
                                          TERMINATOR);

            stringToSign.AppendFormat("{0}-{1}\n{2}\n{3}\n", SCHEME, ALGORITHM, dateTimeStamp, scope);
            stringToSign.Append(ToHexString(canonicalRequestHashBytes, true));

            Logger.LogDebug($"\nStringToSign:\n{stringToSign}");

            // compute the signing key
            var kha = KeyedHashAlgorithm.Create(HMACSHA256);

            kha.Key = DeriveSigningKey(HMACSHA256, awsSecretKey, Region, dateStamp, Service);

            // compute the AWS4 signature and return it
            var signature       = kha.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString()));
            var signatureString = ToHexString(signature, true);

            Logger.LogDebug($"\nSignature:\n{signatureString}");

            var authString = new StringBuilder();

            authString.AppendFormat("{0}-{1} ", SCHEME, ALGORITHM);
            authString.AppendFormat("Credential={0}/{1}, ", awsAccessKey, scope);
            authString.AppendFormat("SignedHeaders={0}, ", canonicalizedHeaderNames);
            authString.AppendFormat("Signature={0}", signatureString);

            var authorization = authString.ToString();

            Logger.LogDebug($"\nAuthorization:\n{authorization}");

            return(authorization);
        }
示例#51
0
        /// <summary>
        /// 指定的打印机设置以mm为单位的自定义纸张(Form)
        /// </summary>
        /// <param name="PrinterName">打印机名称</param>
        /// <param name="PaperName">Form名称</param>
        /// <param name="WidthInMm">以mm为单位的宽度</param>
        /// <param name="HeightInMm">以mm为单位的高度</param>
        public static void AddCustomPaperSize(string PrinterName, string PaperName, float WidthInMm, float HeightInMm)
        {
            if (PlatformID.Win32NT == Environment.OSVersion.Platform)
            {
                const int PRINTER_ACCESS_USE        = 0x00000008;
                const int PRINTER_ACCESS_ADMINISTER = 0x00000004;
                //const int FORM_PRINTER = 0x00000002;

                structPrinterDefaults defaults = new structPrinterDefaults();
                defaults.pDatatype     = null;
                defaults.pDevMode      = IntPtr.Zero;
                defaults.DesiredAccess = PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE;

                IntPtr hPrinter = IntPtr.Zero;

                //打开打印机
                if (OpenPrinter(PrinterName, out hPrinter, ref defaults))
                {
                    try
                    {
                        //如果Form存在删除之
                        DeleteForm(hPrinter, PaperName);
                        //创建并初始化FORM_INFO_1
                        FormInfo1 formInfo = new FormInfo1();
                        formInfo.Flags                = 0;
                        formInfo.pName                = PaperName;
                        formInfo.Size.width           = (int)(WidthInMm * 1000.0);
                        formInfo.Size.height          = (int)(HeightInMm * 1000.0);
                        formInfo.ImageableArea.left   = 0;
                        formInfo.ImageableArea.right  = formInfo.Size.width;
                        formInfo.ImageableArea.top    = 0;
                        formInfo.ImageableArea.bottom = formInfo.Size.height;
                        if (!AddForm(hPrinter, 1, ref formInfo))
                        {
                            StringBuilder strBuilder = new StringBuilder();
                            strBuilder.AppendFormat("向打印机 {1} 添加自定义纸张 {0} 失败!错误代号:{2}",
                                                    PaperName, PrinterName, GetLastError());
                            throw new ApplicationException(strBuilder.ToString());
                        }

                        //初始化
                        const int      DM_OUT_BUFFER = 2;
                        const int      DM_IN_BUFFER = 8;
                        structDevMode  devMode = new structDevMode();
                        IntPtr         hPrinterInfo, hDummy;
                        PRINTER_INFO_9 printerInfo;
                        printerInfo.pDevMode = IntPtr.Zero;
                        int iPrinterInfoSize, iDummyInt;


                        int iDevModeSize = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, IntPtr.Zero, 0);

                        if (iDevModeSize < 0)
                        {
                            throw new ApplicationException("无法取得DEVMODE结构的大小!");
                        }

                        //分配缓冲
                        IntPtr hDevMode = Marshal.AllocCoTaskMem(iDevModeSize + 100);

                        //获取DEV_MODE指针
                        int iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, hDevMode, IntPtr.Zero, DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("无法获得DEVMODE结构!");
                        }

                        //填充DEV_MODE
                        devMode = (structDevMode)Marshal.PtrToStructure(hDevMode, devMode.GetType());


                        devMode.dmFields = 0x10000;

                        //FORM名称
                        devMode.dmFormName = PaperName;

                        Marshal.StructureToPtr(devMode, hDevMode, true);

                        iRet = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName,
                                                  printerInfo.pDevMode, printerInfo.pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);

                        if (iRet < 0)
                        {
                            throw new ApplicationException("无法为打印机设定打印方向!");
                        }

                        GetPrinter(hPrinter, 9, IntPtr.Zero, 0, out iPrinterInfoSize);
                        if (iPrinterInfoSize == 0)
                        {
                            throw new ApplicationException("调用GetPrinter方法失败!");
                        }

                        hPrinterInfo = Marshal.AllocCoTaskMem(iPrinterInfoSize + 100);

                        bool bSuccess = GetPrinter(hPrinter, 9, hPrinterInfo, iPrinterInfoSize, out iDummyInt);

                        if (!bSuccess)
                        {
                            throw new ApplicationException("调用GetPrinter方法失败!");
                        }

                        printerInfo          = (PRINTER_INFO_9)Marshal.PtrToStructure(hPrinterInfo, printerInfo.GetType());
                        printerInfo.pDevMode = hDevMode;

                        Marshal.StructureToPtr(printerInfo, hPrinterInfo, true);

                        bSuccess = SetPrinter(hPrinter, 9, hPrinterInfo, 0);

                        if (!bSuccess)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error(), "调用SetPrinter方法失败,无法进行打印机设置!");
                        }

                        SendMessageTimeout(
                            new IntPtr(HWND_BROADCAST),
                            WM_SETTINGCHANGE,
                            IntPtr.Zero,
                            IntPtr.Zero,
                            Printer.SendMessageTimeoutFlags.SMTO_NORMAL,
                            1000,
                            out hDummy);
                    }
                    finally
                    {
                        ClosePrinter(hPrinter);
                    }
                }
                else
                {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendFormat("无法打开打印机{0}, 错误代号: {1}",
                                            PrinterName, GetLastError());
                    throw new ApplicationException(strBuilder.ToString());
                }
            }
            else
            {
                structDevMode pDevMode = new structDevMode();
                IntPtr        hDC      = CreateDC(null, PrinterName, null, ref pDevMode);
                if (hDC != IntPtr.Zero)
                {
                    const long DM_PAPERSIZE   = 0x00000002L;
                    const long DM_PAPERLENGTH = 0x00000004L;
                    const long DM_PAPERWIDTH  = 0x00000008L;
                    pDevMode.dmFields      = (int)(DM_PAPERSIZE | DM_PAPERWIDTH | DM_PAPERLENGTH);
                    pDevMode.dmPaperSize   = 256;
                    pDevMode.dmPaperWidth  = (short)(WidthInMm * 1000.0);
                    pDevMode.dmPaperLength = (short)(HeightInMm * 1000.0);
                    ResetDC(hDC, ref pDevMode);
                    DeleteDC(hDC);
                }
            }
        }
        IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false)               //Convert the JSONObject into a string
        //Profiler.BeginSample("JSONprint");
        {
            if (depth++ > MAX_DEPTH)
            {
                Debug.Log("reached max depth!");
                yield break;
            }
            if (printWatch.Elapsed.TotalSeconds > maxFrameTime)
            {
                printWatch.Reset();
                yield return(0);

                printWatch.Start();
            }
            switch (type)
            {
            case Type.BAKED:
                builder.Append(str);
                break;

            case Type.STRING:
                builder.AppendFormat("\"{0}\"", str);
                break;

            case Type.NUMBER:
        #if USEFLOAT
                if (float.IsInfinity(n))
                {
                    builder.Append(INFINITY);
                }
                else if (float.IsNegativeInfinity(n))
                {
                    builder.Append(NEGINFINITY);
                }
                else if (float.IsNaN(n))
                {
                    builder.Append(NaN);
                }
        #else
                if (double.IsInfinity(n))
                {
                    builder.Append(INFINITY);
                }
                else if (double.IsNegativeInfinity(n))
                {
                    builder.Append(NEGINFINITY);
                }
                else if (double.IsNaN(n))
                {
                    builder.Append(NaN);
                }
        #endif
                else
                {
                    builder.Append(n.ToString());
                }
                break;

            case Type.OBJECT:
                builder.Append("{");
                if (list.Count > 0)
                {
        #if (PRETTY)     //for a bit more readability, comment the define above to disable system-wide
                    if (pretty)
                    {
                        builder.Append("\n");
                    }
        #endif
                    for (int i = 0; i < list.Count; i++)
                    {
                        string     key = keys[i];
                        JSONObject obj = list[i];
                        if (obj)
                        {
        #if (PRETTY)
                            if (pretty)
                            {
                                for (int j = 0; j < depth; j++)
                                {
                                    builder.Append("\t");                                             //for a bit more readability
                                }
                            }
        #endif
                            builder.AppendFormat("\"{0}\":", key);
                            foreach (IEnumerable e in obj.StringifyAsync(depth, builder, pretty))
                            {
                                yield return(e);
                            }
                            builder.Append(",");
        #if (PRETTY)
                            if (pretty)
                            {
                                builder.Append("\n");
                            }
        #endif
                        }
                    }
        #if (PRETTY)
                    if (pretty)
                    {
                        builder.Length -= 2;
                    }
                    else
        #endif
                    builder.Length--;
                }
        #if (PRETTY)
                if (pretty && list.Count > 0)
                {
                    builder.Append("\n");
                    for (int j = 0; j < depth - 1; j++)
                    {
                        builder.Append("\t");                                 //for a bit more readability
                    }
                }
        #endif
                builder.Append("}");
                break;

            case Type.ARRAY:
                builder.Append("[");
                if (list.Count > 0)
                {
        #if (PRETTY)
                    if (pretty)
                    {
                        builder.Append("\n");                                 //for a bit more readability
                    }
        #endif
                    for (int i = 0; i < list.Count; i++)
                    {
                        if (list[i])
                        {
        #if (PRETTY)
                            if (pretty)
                            {
                                for (int j = 0; j < depth; j++)
                                {
                                    builder.Append("\t");                                             //for a bit more readability
                                }
                            }
        #endif
                            foreach (IEnumerable e in list[i].StringifyAsync(depth, builder, pretty))
                            {
                                yield return(e);
                            }
                            builder.Append(",");
        #if (PRETTY)
                            if (pretty)
                            {
                                builder.Append("\n");                                         //for a bit more readability
                            }
        #endif
                        }
                    }
        #if (PRETTY)
                    if (pretty)
                    {
                        builder.Length -= 2;
                    }
                    else
        #endif
                    builder.Length--;
                }
        #if (PRETTY)
                if (pretty && list.Count > 0)
                {
                    builder.Append("\n");
                    for (int j = 0; j < depth - 1; j++)
                    {
                        builder.Append("\t");                                 //for a bit more readability
                    }
                }
        #endif
                builder.Append("]");
                break;

            case Type.BOOL:
                if (b)
                {
                    builder.Append("true");
                }
                else
                {
                    builder.Append("false");
                }
                break;

            case Type.NULL:
                builder.Append("null");
                break;
            }
            //Profiler.EndSample();
        }
示例#53
0
文件: jcData.cs 项目: hjk1122/start1
        public sendData DataInit(string data)
        {
            StringBuilder data1 = new StringBuilder();
            StringBuilder data2 = new StringBuilder();
            StringBuilder str1 = new StringBuilder();
            sendData sendData = new sendData();
            sendData.dataList = new List<string>();
            //str = "";
            try
            {
                if (data.Length != 8)
                {
                    Exception e1 = new Exception("数据长度不是8位");
                    throw e1;
                }

                czData czData = new czData();

                subStr subStr=new subStr();
                
                string idstring = tools.Tool.HexToDec(data.Substring(4, 2));
                int Id = Int32.Parse(idstring);
                czData.Id = this.GetStringDouByte(idstring);
                //判断前进或后退
                czData.flag = data.Substring(6, 1);
                switch (czData.flag)
                {
                    //前进(最小速度)
                    case "f":
                    case "F":
                    {
                        subStr = this.GetjcData("jcSendFMin");
                        data1.AppendFormat("{0}{1}{2}{3}", subStr.strBegin,
                            czData.Id,"8", subStr.strEnd);
                        str1.AppendFormat("机车[{0}] 状态[前进]", Id);
                        sendData.dataList.Add(data1.ToString());
                        sendData.msg = str1.ToString();
                        sendData.error = false;
                        break;
                    }
                    //后退
                    case "b":
                    case "B":
                    {
                        subStr = this.GetjcData("jcSendBMin");
                        data1.AppendFormat("{0}{1}{2}{3}", subStr.strBegin,
                            czData.Id, "0", subStr.strEnd);
                        str1.AppendFormat("机车[{0}] 状态[后退]", Id);
                        sendData.dataList.Add(data1.ToString());
                        sendData.msg = str1.ToString();
                        sendData.error = false;
                        break;
                    }
                    //停止
                    case "0":
                    {
                        subStr = this.GetjcData("jcStop");
                        data1.AppendFormat("{0}{1}{2}", subStr.strBegin,
                            czData.Id, subStr.strEnd);
                        subStr = this.GetjcData("jcStop");
                        data2.AppendFormat("{0}{1}{2}", subStr.strBegin,
                            czData.Id, subStr.strEnd);
                        str1.AppendFormat("机车[{0}] 状态[停车]", Id);
                        sendData.dataList.Add(data1.ToString());
                        sendData.dataList.Add(data2.ToString());
                        sendData.msg = str1.ToString();
                        sendData.error = false;
                        break;
                    }
                }
            }
            catch (Exception e1)
            {
                sendData.dataList = null;
                sendData.msg = e1.Message;
                sendData.error = true;
                MessageBox.Show(e1.Message, "错误");
            }

            //str = str1.ToString();
            return sendData;
        }
示例#54
0
        public static string CreateProgressBar(
            float progress,
            Orientation orientation,
            Unit width,
            Unit height,
            Unit borderWidth,
            string borderCssClass,
            string borderStyle,
            string processedCssClass,
            string processedStyle,
            string unprocessedCssClass,
            string unprocessedStyle,
            string completeCssClass,
            string completeStyle
            )
        {
            if (progress >= 0 && progress <= 1)
            {
                StringBuilder html       = new StringBuilder();
                int           percentage = (int)(progress * 100);

                string borderCssClassStr = string.Empty;
                if (borderCssClass != null && borderCssClass.Length > 0)
                {
                    borderCssClassStr = String.Format(" class='{0}'", borderCssClass);
                }

                string borderStyleStr = string.Empty;
                if (borderStyle != null && borderStyle.Length > 0)
                {
                    borderStyleStr = String.Format(" style='{0}'", borderStyle);
                }

                string processedCssClassStr = string.Empty;
                if (processedCssClass != null && processedCssClass.Length > 0)
                {
                    processedCssClassStr = String.Format(" class='{0}'", processedCssClass);
                }

                string unprocessedCssClassStr = string.Empty;
                if (unprocessedCssClass != null && unprocessedCssClass.Length > 0)
                {
                    unprocessedCssClassStr = String.Format(" class='{0}'", unprocessedCssClass);
                }

                string completeCssClassStr = string.Empty;
                if (completeCssClass != null && completeCssClass.Length > 0)
                {
                    completeCssClassStr = String.Format(" class='{0}'", completeCssClass);
                }

                string processedStyleStr = string.Empty;
                if (processedStyle != null && processedStyle.Length > 0)
                {
                    processedStyleStr = String.Format(" style='{0}'", processedStyle);
                }

                string unprocessedStyleStr = string.Empty;
                if (unprocessedStyle != null && unprocessedStyle.Length > 0)
                {
                    unprocessedStyleStr = String.Format(" style='{0}'", unprocessedStyle);
                }

                string completeStyleStr = string.Empty;
                if (completeStyle != null && completeStyle.Length > 0)
                {
                    completeStyleStr = String.Format(" style='{0}'", completeStyle);
                }

                html.AppendFormat("<table width='{0}' height='{1}' cellPadding='0' cellSpacing='0'{2}{3}>", width, height, borderCssClassStr, borderStyleStr);

                if (orientation == Orientation.Horizontal)
                {
                    html.Append("<tr>");
                    if (percentage <= 0)
                    {
                        html.Append("<td></td>");
                    }
                    else if (percentage < 100)
                    {
                        html.Append("<td bgcolor='");
                        html.Append("#FF0000");
                        html.Append("' width='");
                        html.Append(percentage);
                        html.Append("%'></td><td></td>");
                    }
                    else
                    {
                        html.Append("<td bgcolor='");
                        html.Append("#00FF00");
                        html.Append("'></td>");
                    }
                    html.Append("</tr>");

                    //if (percentage <= 0)
                    //{
                    //    html.AppendFormat("<tr><td></td></tr>");
                    //}
                    //else if (percentage < 100)
                    //{
                    //    html.AppendFormat("<tr><td align='left'><table cellPadding='0' cellSpacing='0' width='{0}' height='100%'{1}{2}><tr><td></td></tr></table></td></tr>", new Unit(width.Value * progress, width.Type), processedStyleStr, processedCssClassStr);
                    //}
                    //else
                    //{
                    //    html.AppendFormat("<tr><td align='left'><table cellPadding='0' cellSpacing='0' width='{0}' height='100%'{1}{2}><tr><td></td></tr></table></td></tr>", new Unit(width.Value * progress, width.Type), completeStyleStr, completeCssClassStr);
                    //}
                }
                else if (orientation == Orientation.Vertical)
                {
                    if (percentage <= 0)
                    {
                        html.Append("<tr><td></td></tr>");
                    }
                    else if (percentage < 100)
                    {
                        html.AppendFormat("<tr><td valign='bottom'><table cellPadding='0' cellSpacing='0' width='100%' height='{0}'{1}{2}><tr><td></td></tr></table></td></tr>", new Unit(height.Value * progress, UnitType.Pixel), processedStyleStr, processedCssClassStr);
                    }
                    else
                    {
                        html.AppendFormat("<tr><td><table cellPadding='0' cellSpacing='0' width='100%' height='{0}'{1}{2}><tr><td></td></tr></table></td></tr>", new Unit(height.Value * progress, UnitType.Pixel), completeStyleStr, completeCssClassStr);
                    }
                }

                html.Append("</table>");

                return(html.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
示例#55
0
        public override string ToString()
        {
            var builder = new StringBuilder();

            builder.AppendFormat("Material Number : {0}\n", MaterialNumber);
            builder.AppendFormat("Description : {0}\n", MaterialDescription);
            builder.AppendFormat("Final Width [cm] : {0}\n", FinalWidthCm);
            builder.AppendFormat("End Count : {0}\n", EndsPerInch);
            builder.AppendFormat("Dtex : {0}\n", Dtex);
            builder.AppendFormat("Warping Speed [m/min] : {0}\n", WarpingSpeed);
            builder.AppendFormat("Beaming Speed [m/min] : {0}\n", BeamingSpeed);
            builder.AppendFormat("Cross Winding : {0}\n", CrossWinding);
            builder.AppendFormat("Dents / cm : {0}\n", DentsPerCm);
            builder.AppendFormat("Ends / Dent : {0}\n", EndsPerDent);
            builder.AppendFormat("S Wrap : {0}\n", IsSWrapped ? "ON" : "OFF");
            builder.AppendFormat("Total Number Of Ends : {0}\n", NumberOfEnds);
            builder.AppendFormat("Beam Width [cm] : {0}\n", BeamWidth);
            builder.AppendFormat("Beaming Tension [N/cm] : {0}\n", BeamingTension);
            builder.AppendFormat("Warping Tension [N/cm]: {0}\n", WarpingTension);
            builder.AppendFormat("Style No. : {0}\n", Style);

            return(builder.ToString());
        }
示例#56
0
 public void AppendLine(string formatString, params object[] args)
 {
     AppendIndentation();
     m_StringBuilder.AppendFormat(formatString, args);
     AppendNewLine();
 }
        private async Task CheckingPluginSteps(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);

            var search = await repository.FindAllAsync(null, string.Empty, string.Empty, string.Empty);

            var querySteps = search.SdkMessageProcessingStep
                            .OrderBy(ent => ent.EventHandler?.Name ?? "Unknown")
                            .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                            .ThenBy(ent => ent.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                            .ThenBy(ent => ent.Stage.Value)
                            .ThenBy(ent => ent.Mode.Value)
                            .ThenBy(ent => ent.Rank)
                            .ThenBy(ent => ent.Name)
                            ;

            var pluginTypesWithConflicts = querySteps.GroupBy(step => new
            {
                EventHandlerId = step.EventHandler.Id,
                Stage = step.Stage.Value,

                EntityName = step.PrimaryObjectTypeCodeName,
                Message = step.SdkMessageId?.Name ?? "Unknown",

                EventHandlerName = step.EventHandler?.Name ?? "Unknown",
                step.Configuration,
            }).Where(gr => gr.Count() > 1);

            int pluginTypeNumber = 1;

            bool hasInfo = false;

            foreach (var gr in pluginTypesWithConflicts)
            {
                hasInfo = true;

                if (content.Length > 0)
                {
                    content.AppendLine().AppendLine();
                }

                content.AppendFormat("{0}. {1}", pluginTypeNumber, gr.Key.EventHandlerName).AppendLine();

                content.AppendFormat("Entity '{0}',   Message '{1}',   Stage '{2}'"
                    , gr.Key.EntityName
                    , gr.Key.Message
                    , SdkMessageProcessingStepRepository.GetStageName(gr.Key.Stage, null)
                    ).AppendLine();

                if (!string.IsNullOrEmpty(gr.Key.Configuration))
                {
                    content.AppendFormat("Configuration: {0}", gr.Key.Configuration).AppendLine();
                }

                foreach (var step in gr)
                {
                    content.AppendFormat("Stage '{0}',   Rank {1},   Statuscode {2}"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        ).AppendLine();

                    var queryImage = from image in search.SdkMessageProcessingStepImage
                                     where image.SdkMessageProcessingStepId != null
                                     where image.SdkMessageProcessingStepId.Id == step.Id
                                     orderby image.ImageType.Value, image.CreatedOn, image.Name
                                     select image;

                    int numberImage = 1;

                    foreach (var image in queryImage)
                    {
                        string imageDescription = GetImageDescription(numberImage.ToString(), image);

                        var coll = imageDescription.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (var item in coll)
                        {
                            content.AppendLine(tabSpacer + tabSpacer + item);
                        }

                        numberImage++;
                    }
                }

                pluginTypeNumber++;
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No duplicates were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Steps Duplicates at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false));

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Steps Duplicates: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
示例#58
0
        public override string ToString()
        {
            var builder = new StringBuilder();

            builder.AppendLine();
            builder.AppendLine("Microsoft Visual Studio Solution File, Format Version 11.00");
            builder.AppendLine("# Visual Studio 2010");

            foreach (var project in projects)
            {
                builder.AppendFormat("Project(\"{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}\") = \"{0}\", \"{1}\", \"{{{2}}}\"\n", project.Name, project.Path, project.GUID.ToString().ToUpper());
                builder.AppendLine("EndProject");
            }

            var typeToGuidMap = new Dictionary <string, Tuple <Guid, IEnumerable <Project> > >();

            var pluginProjects = projects.OfType <PluginProject>().AsEnumerable <Project>();

            if (pluginProjects.Any())
            {
                typeToGuidMap.Add("Plugins", Tuple.Create(Guid.NewGuid(), pluginProjects));
            }

            var testsProjects = projects.OfType <TestsProject>().AsEnumerable <Project>();

            if (testsProjects.Any())
            {
                typeToGuidMap.Add("Tests", Tuple.Create(Guid.NewGuid(), testsProjects));
            }

            var coresProjects = projects.OfType <CpuCoreProject>();

            if (coresProjects.Any())
            {
                typeToGuidMap.Add("Cores", Tuple.Create(Guid.NewGuid(), coresProjects.Cast <Project>()));
            }

            var extensionProjects = projects.OfType <ExtensionProject>().AsEnumerable <Project>();

            if (extensionProjects.Any())
            {
                typeToGuidMap.Add("Extensions", Tuple.Create(Guid.NewGuid(), extensionProjects));
            }

            var librariesProjects = projects.Where(x => x.Path.Contains("/External/"));

            if (librariesProjects.Any())
            {
                typeToGuidMap.Add("Libraries", Tuple.Create(Guid.NewGuid(), librariesProjects));
            }

            foreach (var type in typeToGuidMap)
            {
                builder.AppendFormat("Project(\"{{2150E333-8FDC-42A3-9474-1A3956D46DE8}}\") = \"{0}\", \"{0}\", \"{{{1}}}\"\n", type.Key, type.Value.Item1.ToString().ToUpper());
                builder.AppendLine("EndProject");
            }

            builder.AppendLine("Global");
            builder.AppendLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
            builder.AppendLine("\t\tDebug|x86 = Debug|x86");
            builder.AppendLine("\t\tRelease|x86 = Release|x86");
            builder.AppendLine("\tEndGlobalSection");
            builder.AppendLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");

            foreach (var project in projects)
            {
                var guid = project.GUID.ToString().ToUpper();
                builder.AppendFormat("\t\t\t{{{0}}}.Debug|x86.ActiveCfg = Debug|{1}\n", guid, project.Target);
                builder.AppendFormat("\t\t\t{{{0}}}.Debug|x86.Build.0 = Debug|{1}\n", guid, project.Target);
                builder.AppendFormat("\t\t\t{{{0}}}.Release|x86.ActiveCfg = Release|{1}\n", guid, project.Target);
                builder.AppendFormat("\t\t\t{{{0}}}.Release|x86.Build.0 = Release|{1}\n", guid, project.Target);
            }

            builder.AppendLine("\tEndGlobalSection");

            builder.AppendLine("\tGlobalSection(NestedProjects) = preSolution");

            foreach (var type in typeToGuidMap)
            {
                foreach (var project in type.Value.Item2)
                {
                    builder.AppendFormat("\t\t\t{{{0}}} = {{{1}}}\n", project.GUID.ToString().ToUpper(), type.Value.Item1);
                }
            }

            builder.AppendLine("\tEndGlobalSection");

            builder.AppendLine("EndGlobal");

            return(builder.ToString());
        }
示例#59
0
        /// <summary>
        /// 执行分页查询
        /// </summary>
        /// <param name="pWhereConditions">筛选条件</param>
        /// <param name="pOrderBys">排序</param>
        /// <param name="pPageSize">每页的记录数</param>
        /// <param name="pCurrentPageIndex">以0开始的当前页码</param>
        /// <returns></returns>
        public PagedQueryResult <VipCardBatchEntity> PagedQuery(IWhereCondition[] pWhereConditions, OrderBy[] pOrderBys, int pPageSize, int pCurrentPageIndex)
        {
            //组织SQL
            StringBuilder pagedSql      = new StringBuilder();
            StringBuilder totalCountSql = new StringBuilder();

            //分页SQL
            pagedSql.AppendFormat("select * from (select row_number()over( order by ");
            if (pOrderBys != null && pOrderBys.Length > 0)
            {
                foreach (var item in pOrderBys)
                {
                    if (item != null)
                    {
                        pagedSql.AppendFormat(" {0} {1},", StringUtils.WrapperSQLServerObject(item.FieldName), item.Direction == OrderByDirections.Asc ? "asc" : "desc");
                    }
                }
                pagedSql.Remove(pagedSql.Length - 1, 1);
            }
            else
            {
                pagedSql.AppendFormat(" [BatchID] desc"); //默认为主键值倒序
            }
            pagedSql.AppendFormat(") as ___rn,* from [VipCardBatch] where 1=1  and isdelete=0 ");
            //总记录数SQL
            totalCountSql.AppendFormat("select count(1) from [VipCardBatch] where 1=1  and isdelete=0 ");
            //过滤条件
            if (pWhereConditions != null)
            {
                foreach (var item in pWhereConditions)
                {
                    if (item != null)
                    {
                        pagedSql.AppendFormat(" and {0}", item.GetExpression());
                        totalCountSql.AppendFormat(" and {0}", item.GetExpression());
                    }
                }
            }
            pagedSql.AppendFormat(") as A ");
            //取指定页的数据
            pagedSql.AppendFormat(" where ___rn >{0} and ___rn <={1}", pPageSize * (pCurrentPageIndex - 1), pPageSize * (pCurrentPageIndex));
            //执行语句并返回结果
            PagedQueryResult <VipCardBatchEntity> result = new PagedQueryResult <VipCardBatchEntity>();
            List <VipCardBatchEntity>             list   = new List <VipCardBatchEntity>();

            using (SqlDataReader rdr = this.SQLHelper.ExecuteReader(pagedSql.ToString()))
            {
                while (rdr.Read())
                {
                    VipCardBatchEntity m;
                    this.Load(rdr, out m);
                    list.Add(m);
                }
            }
            result.Entities = list.ToArray();
            int totalCount = Convert.ToInt32(this.SQLHelper.ExecuteScalar(totalCountSql.ToString()));    //计算总行数

            result.RowCount = totalCount;
            int remainder = 0;

            result.PageCount = Math.DivRem(totalCount, pPageSize, out remainder);
            if (remainder > 0)
            {
                result.PageCount++;
            }
            return(result);
        }
        private async Task CheckingPluginStepsRequiredComponents(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);

            var search = await repository.FindAllAsync(new List<PluginStage>(), string.Empty, string.Empty, string.Empty);

            var querySteps = search.SdkMessageProcessingStep
                            .OrderBy(ent => ent.EventHandler.Name)
                            .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                            .ThenBy(ent => ent.SdkMessageId.Name, new MessageComparer())
                            .ThenBy(ent => ent.Stage.Value)
                            .ThenBy(ent => ent.Mode.Value)
                            .ThenBy(ent => ent.Rank)
                            .ThenBy(ent => ent.Name)
                            ;

            EntityMetadataRepository repositoryMetadata = new EntityMetadataRepository(service);

            DependencyRepository dependencyRepository = new DependencyRepository(service);

            var listMetaData = await repositoryMetadata.GetEntitiesWithAttributesAsync();

            var dictEntity = new Dictionary<Guid, EntityMetadata>();
            var dictAttribute = new Dictionary<Guid, AttributeMetadata>();

            bool hasInfo = false;

            foreach (var metaEntity in listMetaData)
            {
                dictEntity.Add(metaEntity.MetadataId.Value, metaEntity);

                foreach (var metaAttribute in metaEntity.Attributes)
                {
                    dictAttribute.Add(metaAttribute.MetadataId.Value, metaAttribute);
                }
            }

            foreach (var step in querySteps)
            {
                var listRequired = await dependencyRepository.GetRequiredComponentsAsync((int)ComponentType.SdkMessageProcessingStep, step.Id);

                var stepEntities = GetSetEntites(step);
                var stepAttributes = GetSetStepAttributes(step);

                var componentsEntities = GetSetComponentsEntites(listRequired, dictEntity);
                var componentsAttributes = GetSetComponentsAttributes(listRequired, dictAttribute);

                bool entitiesIsSame = stepEntities.SequenceEqual(componentsEntities);
                bool attributesIsSame = stepAttributes.SequenceEqual(componentsAttributes);

                if (!entitiesIsSame || !attributesIsSame)
                {
                    if (content.Length > 0)
                    {
                        content.AppendLine().AppendLine().AppendLine();
                    }

                    content.AppendFormat("{0}   Primary {1}   Secondary {2}   Message {3}   Stage {4}   Rank {5}   Status {6}   FilteringAttributes {7}",
                        step.EventHandler?.Name ?? "Unknown"
                        , step.PrimaryObjectTypeCodeName
                        , step.SecondaryObjectTypeCodeName
                        , step.SdkMessageId?.Name ?? "Unknown"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        , step.FilteringAttributesStringsSorted
                    ).AppendLine();

                    if (!entitiesIsSame)
                    {
                        hasInfo = true;

                        content.AppendLine("Conflict in entites.");

                        content.Append("Entities in plugin step description");

                        if (stepEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }


                        content.Append("Entities in required components");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }

                    if (!attributesIsSame)
                    {
                        hasInfo = true;

                        content.AppendLine("Conflict in attributes.");

                        content.Append("Attributes in plugin step description");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }

                        content.Append("Attributes in required components");

                        if (componentsAttributes.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }
                }
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No conflicts were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Steps Required Components at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false));

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Steps Required Components: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }