public byte[] CommitTransaction(SortedSet<BaseDataObjectVersion> objects) { Log.WriteLine ("Database.CommitTransaction()"); int oc = objects.Count; objects.RemoveWhere (obj => obj.ChunkID != null); Log.WriteLine ("Ommitting {0} objects in commit", oc - objects.Count); System.IO.MemoryStream MS = new System.IO.MemoryStream (); System.IO.MemoryStream MSRP = new System.IO.MemoryStream (); System.IO.BinaryWriter MSBW = new System.IO.BinaryWriter (MS); SortedSet<byte[]> dependencies = new SortedSet<byte[]> (BD2.Core.ByteSequenceComparer.Shared); ChunkHeaderv1 ch = new ChunkHeaderv1 (DateTime.UtcNow, ""); MSBW.Write (ch.Version); byte[] chbytes = ch.Serialize (); MSBW.Write (chbytes.Length); MSBW.Write (chbytes); MSBW.Write (1);//section count Log.WriteLine ("{0} sections", 1); int n = 0; //foreach (var tup in data) { MSBW.Write (1); Log.WriteLine ("Section version is {0}", 1); System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode<BaseDataObjectVersion>> ss = new System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode<BaseDataObjectVersion>> (); System.Collections.Generic.LinkedList <BaseDataObjectVersion> ll = new LinkedList<BaseDataObjectVersion> (); foreach (BaseDataObjectVersion bdo in objects) { if (!ss.ContainsKey (bdo)) ss.Add (bdo, ll.AddLast (bdo)); foreach (BaseDataObjectVersion dependency in bdo.GetDependenies ()) { byte[] dep = dependency.ChunkID; if (dep == null) { if (ss.ContainsKey (bdo)) { } else { ss.Add (dependency, ll.AddBefore (ss [bdo], dependency)); } } else { if (!dependencies.Contains (dependency.ChunkID)) dependencies.Add (dependency.ChunkID); } } } foreach (BaseDataObjectVersion bdo in ll) { n++; System.IO.MemoryStream MST = new System.IO.MemoryStream (); MST.Write (bdo.ObjectType.ToByteArray (), 0, 16); bdo.Serialize (MST, encryptedStorageManager); byte[] bytes = MST.ToArray (); Log.WriteLine ("object type+bytes: {0}", bytes.ToHexadecimal ()); //Log.WriteLine ("Object of type {0} serialized to {1} bytes.", bdo.GetType ().FullName, bytes.Length); { System.IO.MemoryStream MSC = new System.IO.MemoryStream (); System.IO.BinaryWriter BWC = new System.IO.BinaryWriter (MSC); BWC.Write (bytes.Length); MSRP.Write (MSC.ToArray (), 0, 4); } MSRP.Write (bytes, 0, bytes.Length); } byte[] encoded = MSRP.ToArray (); Log.WriteLine ("{0} objects encoded in {1} bytes", objects.Count, encoded.Length); MSBW.Write (n); MSBW.Write (encoded.Length); MSBW.Write (encoded); Log.WriteLine ("encoded:{0}", encoded.ToHexadecimal ()); //} if (n == 0) { Log.WriteLine ("No objects to save, nothing to do"); return null; } System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create (); Log.WriteLine ("{0} dependencies", dependencies.Count); byte[][] deps = new byte [dependencies.Count][]; int depid = 0; foreach (byte[] dep in dependencies) deps [depid++] = dep; Log.WriteLine ("Writing {0} bytes representing {1} objects to backend", MS.Length, n); byte[] buf = MS.ToArray (); byte[] chunkID = sha.ComputeHash (buf); foreach (var ds in dataStorage) Log.WriteLine ("We have: {0}", ds.Key.ToHexadecimal ()); byte[] cus = userStorage.GetCommonStorage (); Log.WriteLine ("Common storage id is {0}", cus.ToHexadecimal ()); if (!dataStorage.ContainsKey (cus)) { Log.WriteLine ("and we don't have it."); Log.WriteLine ("we only have:"); foreach (var t in dataStorage) Log.WriteLine (" ID: {0}", t.Key.ToHexadecimal ()); } dataStorage [cus].Push (chunkID, buf, deps, userStorage.Sign (chunkID)); foreach (var bdo in objects) { bdo.SetChunkID (chunkID); } Log.WriteLine ("Chunk saved with ID:{0}", chunkID.ToHexadecimal ()); return chunkID; }
public void ProcessRequest(System.Web.HttpContext context) { string text = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><trade_get_response>{0}</trade_get_response>"; string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; this.fomat = "json"; SiteSettings masterSettings = SettingsManager.GetMasterSettings(false); this.jsonformat = "{{\"Oid\": \"{0}\",\"SellerUid\": \"{1}\",\"BuyerNick\": \"{2}\",\"BuyerEmail\": \"{3}\",\"ReceiverName\": \"{4}\",\"ReceiverState\": \"{5}\",\"ReceiverCity\": \"{6}\",\"ReceiverDistrict\":\"{7}\",\"ReceiverAddress\":\"{8}\",\"ReceiverZip\": \"{9}\",\"ReceiverMobile\": \"{10}\",\"ReceiverPhone\":\"{11}\",\"BuyerMemo\": \"{12}\",\"OrderMark\":\"{13}\",\"SellerMemo\":\"{14}\",\"Nums\":\"{15}\",\"Price\": \"{16}\",\"Payment\":\"{17}\",\"PaymentType\": \"{18}\",\"PaymentTypeId\":\"{19}\",\"PaymentName\":\"{20}\",\"PostFee\": \"{21}\",\"DiscountFee\": \"{22}\",\"AdjustFee\": \"{23}\",\"PaymentTs\": \"{24}\",\"SentTs\":\"{25}\",\"RefundStatus\":\"{26}\",\"RefundAmount\":\"{27}\",\"RefundRemark\":\"{28}\",\"Status\": \"{29}\",\"ModeName\": \"{30}\",\"CreateTs\":\"{31}\",\"orders\": [{32}]}},"; string field = "action"; string orderitemfomat = "{{\"Tid\": \"{0}\",\"Oid\": \"{1}\",\"GoodsIid\": \"{2}\",\"Title\": \"{3}\",\"OuterId\": \"{4}\",\"SkuId\":\"{5}\",\"SKUContent\": \"{6}\",\"Nums\": \"{7}\",\"Price\": \"{8}\",\"Payment\":\"{9}\",\"ThumUrl\":\"{10}\"}},"; System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); this.ModelId = context.Request.Form["action"].ToString(); field = "sign"; this.key = context.Request.Form["sign"]; this.localcode = masterSettings.CheckCode; new System.Collections.Generic.Dictionary <string, string>(); System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); try { if (!string.IsNullOrEmpty(this.ModelId)) { string modelId; if ((modelId = this.ModelId) != null) { if (!(modelId == "tradelist")) { if (!(modelId == "tradedetails")) { if (!(modelId == "send")) { if (modelId == "mark") { string value = context.Request.Form["order_mark"].Trim(); string text2 = context.Request.Form["seller_memo"].Trim(); if (string.IsNullOrEmpty(context.Request.Form["tid"].Trim()) || string.IsNullOrEmpty(value) || string.IsNullOrEmpty(text2)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "tid or order_mark or seller_memo"); goto IL_9F1; } if (System.Convert.ToInt32(value) <= 0 || System.Convert.ToInt32(value) >= 7) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Format_Eroor, "order_mark"); goto IL_9F1; } string text3 = context.Request.Form["tid"].Trim(); this.tmpParas.Add("tid", text3); this.tmpParas.Add("order_mark", value); this.tmpParas.Add("seller_memo", text2); this.tmpParas.Add("format", this.fomat); this.tmpParas.Add("action", this.ModelId); if (!APIHelper.CheckSign(this.tmpParas, this.localcode, this.key)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "sign"); goto IL_9F1; } OrderInfo orderInfo = OrderHelper.GetOrderInfo(text3); orderInfo.ManagerMark = new OrderMark?((OrderMark)System.Enum.Parse(typeof(OrderMark), value, true)); orderInfo.ManagerRemark = Globals.HtmlEncode(text2); if (!OrderHelper.SaveRemark(orderInfo)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Paramter_Error, "save is failure "); goto IL_9F1; } if (this.fomat == "json") { text = string.Format("{{\"trade_get_response\":{{\"trade\":{0}}}}}", this.GetOrderDetails(this.jsonformat, orderitemfomat, orderInfo)); goto IL_9F1; } goto IL_9F1; } } else { string text4 = context.Request.Form["tid"].Trim(); string text5 = context.Request.Form["out_sid"].Trim(); string text6 = context.Request.Form["company_code"].Trim(); if (string.IsNullOrEmpty(text4) || string.IsNullOrEmpty(text6) || string.IsNullOrEmpty(text5)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "paramters"); goto IL_9F1; } this.tmpParas.Add("tid", text4); this.tmpParas.Add("out_sid", text5); this.tmpParas.Add("company_code", text6); this.tmpParas.Add("format", this.fomat); this.tmpParas.Add("action", this.ModelId); if (!APIHelper.CheckSign(this.tmpParas, this.localcode, this.key)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "sign"); goto IL_9F1; } ExpressCompanyInfo expressCompanyInfo = ExpressHelper.FindNodeByCode(text6); if (string.IsNullOrEmpty(expressCompanyInfo.Name)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.NoExists_Error, "company_code"); goto IL_9F1; } ShippingModeInfo shippingModeByCompany = SalesHelper.GetShippingModeByCompany(expressCompanyInfo.Name); OrderInfo orderInfo2 = OrderHelper.GetOrderInfo(text4); if (orderInfo2 == null) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.NoExists_Error, "tid"); goto IL_9F1; } ApiErrorCode apiErrorCode = this.SendOrders(orderInfo2, shippingModeByCompany, text5, expressCompanyInfo); if (apiErrorCode != ApiErrorCode.Success) { this.erromsg = MessageInfo.ShowMessageInfo(apiErrorCode, "It"); goto IL_9F1; } orderInfo2 = OrderHelper.GetOrderInfo(text4); if (this.fomat == "json") { text = string.Format("{{\"trade_get_response\":{{\"trade\":{0}}}}}", this.GetOrderDetails(this.jsonformat, orderitemfomat, orderInfo2)); goto IL_9F1; } goto IL_9F1; } } else { if (string.IsNullOrEmpty(context.Request.Form["tid"].Trim())) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "tid"); goto IL_9F1; } string text3 = context.Request.Form["tid"].Trim(); this.tmpParas = new System.Collections.Generic.SortedDictionary <string, string>(); this.tmpParas.Add("tid", context.Request.Form["tid"]); this.tmpParas.Add("format", this.fomat); this.tmpParas.Add("action", this.ModelId); if (!APIHelper.CheckSign(this.tmpParas, this.localcode, this.key)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "signature"); goto IL_9F1; } string text7 = context.Request.Form["tid"].Replace("\r\n", "\n"); if (string.IsNullOrEmpty(text7)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Format_Eroor, "tid"); goto IL_9F1; } text3 = text7; OrderInfo orderInfo3 = TradeHelper.GetOrderInfo(text3); if (this.fomat == "json") { text = string.Format("{{\"trade_get_response\":{{\"trade\":{0}}}}}", this.GetOrderDetails(this.jsonformat, orderitemfomat, orderInfo3)); goto IL_9F1; } goto IL_9F1; } } else { OrderQuery orderQuery = new OrderQuery { PageSize = 100 }; int num = 0; string text8 = context.Request.Form["status"].Trim(); string value2 = context.Request.Form["pagesize"].Trim(); string text9 = context.Request.Form["datatype"].Trim(); string text10 = context.Request.Form["buyernick"].Trim(); string value3 = context.Request.Form["pageindex"].Trim(); string value4 = context.Request.Form["starttime"].Trim(); string value5 = context.Request.Form["endtime"].Trim(); if (!string.IsNullOrEmpty(text8) && System.Convert.ToInt32(text8) >= 0 && text8 != "6") { orderQuery.Status = (OrderStatus)System.Enum.Parse(typeof(OrderStatus), text8, true); } else { if (text8 == "6") { orderQuery.Status = OrderStatus.All; orderQuery.RefundState = (RefundStatus)System.Enum.Parse(typeof(RefundStatus), text8, true); } else { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "status"); } } if (!string.IsNullOrEmpty(value3) && System.Convert.ToInt32(value3) > 0) { orderQuery.PageIndex = System.Convert.ToInt32(value3); } else { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "pageindex"); } if (!string.IsNullOrEmpty(value2) && System.Convert.ToInt32(value2) > 0) { orderQuery.PageSize = (int)System.Convert.ToInt16(value2); } if (!string.IsNullOrEmpty(text9) && System.Convert.ToInt32(text9) > 0) { orderQuery.DataType = int.Parse(text9); } if (!string.IsNullOrEmpty(this.erromsg)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "paramter"); goto IL_9F1; } this.tmpParas.Add("status", text8); this.tmpParas.Add("datatype", text9); this.tmpParas.Add("buyernick", text10); this.tmpParas.Add("pageindex", value3); this.tmpParas.Add("pagesize", value2); this.tmpParas.Add("starttime", value4); this.tmpParas.Add("endtime", value5); this.tmpParas.Add("format", this.fomat); this.tmpParas.Add("action", this.ModelId); if (!APIHelper.CheckSign(this.tmpParas, this.localcode, this.key)) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "sign"); goto IL_9F1; } if (!string.IsNullOrEmpty(text10)) { orderQuery.UserName = text10; } if (!string.IsNullOrEmpty(value4)) { orderQuery.StartDate = new System.DateTime?(System.Convert.ToDateTime(value4)); } if (!string.IsNullOrEmpty(value5)) { orderQuery.EndDate = new System.DateTime?(System.Convert.ToDateTime(value5)); } string arg = stringBuilder.Append(this.GetOrderList(orderQuery, this.jsonformat, orderitemfomat, out num).ToString()).ToString(); if (this.fomat == "json") { text = string.Format("{{\"trade_get_response\":{{\"trade\":[{0}],\"total\":{1}}}}}", arg, num); goto IL_9F1; } goto IL_9F1; } } this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Paramter_Error, "paramters"); } else { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Paramter_Error, "sign"); } IL_9F1 :; } catch (System.Exception) { this.erromsg = MessageInfo.ShowMessageInfo(ApiErrorCode.Unknown_Error, field); } if (!string.IsNullOrEmpty(this.erromsg)) { text = str + this.erromsg; if (this.fomat == "json") { text = text.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", ""); xmlDocument.Load(new System.IO.MemoryStream(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(text))); text = JsonConvert.SerializeXmlNode(xmlDocument); } } context.Response.ContentType = "text/json"; context.Response.Write(text); }
//сбор информации о селекторах (сортировка, группировка и т. д.) private TmpForLabel[] GetCaseSelectors(ISwitchNode value, Label default_label, out System.Collections.Generic.Dictionary<IConstantNode, Label> dict) { System.Collections.Generic.SortedDictionary<int, TmpForCase> sel_list = new System.Collections.Generic.SortedDictionary<int, TmpForCase>(); System.Collections.Generic.Dictionary<ICaseRangeNode, IStatementNode> sel_range = new System.Collections.Generic.Dictionary<ICaseRangeNode, IStatementNode>(); dict = new System.Collections.Generic.Dictionary<IConstantNode, Label>(); //sobiraem informaciju o konstantah v case for (int i = 0; i < value.case_variants.Length; i++) { ICaseVariantNode cvn = value.case_variants[i]; for (int j = 0; j < cvn.elements.Length; j++) { IConstantNode cnst = cvn.elements[j]; if (cnst is IIntConstantNode) { TmpForCase tfc = new TmpForCase(); tfc.cnst = cnst; tfc.stmt = cvn.statement_to_execute; sel_list[((IIntConstantNode)cnst).constant_value] = tfc; } else if (cnst is ICharConstantNode) { TmpForCase tfc = new TmpForCase(); tfc.cnst = cnst; tfc.stmt = cvn.statement_to_execute; sel_list[(int)((ICharConstantNode)cnst).constant_value] = tfc; } else if (cnst is IBoolConstantNode) { TmpForCase tfc = new TmpForCase(); tfc.cnst = cnst; tfc.stmt = cvn.statement_to_execute; sel_list[Convert.ToInt32(((IBoolConstantNode)cnst).constant_value)] = tfc; } //ICaseRangeNode crn = cvn.ranges[j]; // sel_range[crn] = cvn.statement_to_execute; } } System.Collections.Generic.List<int> lst = new System.Collections.Generic.List<int>(); foreach (int val in sel_list.Keys) { lst.Add(val); } //sortiruem spisok perehodov v case lst.Sort(); //int size = lst[lst.Count - 1] - lst[0] + 1; System.Collections.Generic.List<Label> label_list = new System.Collections.Generic.List<Label>(); int last = 0; int size = 0; TmpForLabel tfl = new TmpForLabel(); List<TmpForLabel> ltfl = new List<TmpForLabel>(); //sozdaem metki dlja perehodov if (lst.Count > 0) { last = lst[0]; size = 1; tfl.low_bound = last;//niznjaa granica Label l = il.DefineLabel(); dict[sel_list[last].cnst] = l;//konstante sopostavim metku label_list.Add(l); } for (int i = 1; i < lst.Count; i++) { int dist = lst[i] - last; if (dist < 10)//esli rasstojanie mezhdu sosednimi konstantami nebolshoe { last = lst[i]; size += dist;//pribavljaem rasstojanie if (dist > 1) { for (int j = 1; j < dist; j++) //inache nado perehodit k proverke diapazonov label_list.Add(default_label); } Label l = il.DefineLabel(); dict[sel_list[last].cnst] = l; label_list.Add(l); } else { tfl.labels = label_list.ToArray();//inache sozdaem otdelnuju tablicu perehodov ltfl.Add(tfl); tfl = new TmpForLabel(); label_list = new List<Label>(); tfl.low_bound = lst[i]; last = lst[i]; Label l = il.DefineLabel(); dict[sel_list[last].cnst] = l; label_list.Add(l); } } tfl.labels = label_list.ToArray(); ltfl.Add(tfl); return ltfl.ToArray(); }
static void Main(string[] args) { Dictionary <string, Contest> contestAndPass = new Dictionary <string, Contest>(); string command = Console.ReadLine(); while (command != "end of contests") { string name = command.Split(":")[0]; string password = command.Split(":")[1]; if (contestAndPass.ContainsKey(name) == false) { Contest contest = new Contest(name, password); contestAndPass.Add(name, contest); } command = Console.ReadLine(); } SortedDictionary <string, User> usersAndContests = new System.Collections.Generic.SortedDictionary <string, User>(); string commandTwo = Console.ReadLine(); while (commandTwo != "end of submissions") { string nameOfContest = commandTwo.Split("=>")[0]; string password = commandTwo.Split("=>")[1]; if (contestAndPass.ContainsKey(nameOfContest) && contestAndPass[nameOfContest].Password == password) { string username = commandTwo.Split("=>")[2]; int points = int.Parse(commandTwo.Split("=>")[3]); if (usersAndContests.ContainsKey(username)) { if (usersAndContests[username].Contests.ContainsKey(nameOfContest)) { if (points > usersAndContests[username].Contests[nameOfContest]) { usersAndContests[username].Contests[nameOfContest] = points; } } else { usersAndContests[username].Contests.Add(nameOfContest, points); } } else { User user = new User(username, points, nameOfContest); usersAndContests.Add(username, user); } } commandTwo = Console.ReadLine(); } string bestUser = User.BestUser(usersAndContests); Console.WriteLine($"Best candidate is {bestUser} with total {usersAndContests[bestUser].Contests.Values.Sum()} points."); Console.WriteLine("Ranking:"); foreach (var user in usersAndContests) { Console.WriteLine(user.Key); foreach (var item in user.Value.Contests.OrderByDescending(p => p.Value)) { Console.WriteLine($"# {item.Key} -> {item.Value}"); } } }
private void Load() { bool exist = File.Exists(DB_PATH); _base = new SortedDictionary <Topic, Stash>(); _db = new LiteDatabase(new ConnectionString("Filename=" + DB_PATH) { CacheSize = 500, Mode = LiteDB.FileMode.Exclusive }); if (exist && !_db.GetCollectionNames().Any(z => z == "objects")) { exist = false; } _objects = _db.GetCollection <BsonDocument>("objects"); _states = _db.GetCollection <BsonDocument>("states"); if (!exist) { _objects.EnsureIndex("p", true); } else { Topic t; Stash a; JSC.JSValue jTmp; bool saved; string sTmp; Version vRepo, vDB; List <string> oldT = new List <string>(); List <ObjectId> oldId = new List <ObjectId>(); foreach (var obj in _objects.FindAll().OrderBy(z => z["p"])) { sTmp = obj["p"].AsString; if (oldT.Any(z => sTmp.StartsWith(z))) { oldId.Add(obj["_id"]); continue; // skip load, old version } t = Topic.I.Get(Topic.root, sTmp, true, _owner, false, false); a = new Stash { id = obj["_id"], bm = obj, jm = Bs2Js(obj["v"]), bs = _states.FindById(obj["_id"]), js = null }; // check version { jTmp = t.GetField("version"); if (jTmp.ValueType == JSC.JSValueType.String && (sTmp = jTmp.Value as string) != null && sTmp.StartsWith("¤VR") && Version.TryParse(sTmp.Substring(3), out vRepo)) { jTmp = a.jm["version"]; if (jTmp.ValueType != JSC.JSValueType.String || (sTmp = jTmp.Value as string) == null || !sTmp.StartsWith("¤VR") || !Version.TryParse(sTmp.Substring(3), out vDB) || vRepo > vDB) { oldT.Add(t.path + "/"); oldId.Add(a.id); continue; // skip load, old version } } } // check attribute JSC.JSValue attr; if (a.jm == null || a.jm.ValueType != JSC.JSValueType.Object || a.jm.Value == null || !(attr = a.jm["attr"]).IsNumber) { saved = false; } else { saved = ((int)attr & (int)Topic.Attribute.Saved) == (int)Topic.Attribute.DB; } if (a.bs != null) { if (saved) { a.js = Bs2Js(a.bs["v"]); } else { _states.Delete(obj["_id"]); a.bs = null; } } _base.Add(t, a); Topic.I.Fill(t, a.js, a.jm, _owner); } oldT.Clear(); foreach (var id in oldId) { _states.Delete(id); _objects.Delete(id); } oldId.Clear(); } }
public BayesCategory(string cat, StopWordsHandler excluded) { m_Phrases = new SortedDictionary <string, BayesPhraseCount>(); m_Excluded = excluded; m_Name = cat; }
//public static void VoronoiMesh(List<g3.PolyLine3d> mesh, out List<g3.Line3d> listLines, out List<g3.PolyLine3d> listPolylines) //{ // System.Collections.Generic.SortedDictionary<int, MeshNode> faces = new System.Collections.Generic.SortedDictionary<int, MeshNode>(); // int index = 0; // foreach (var meshFaceIndex in mesh.TriangleIndices()) // { // var frame = mesh.GetTriFrame(meshFaceIndex); // g3.Index3i neighbors = mesh.GetTriNeighbourTris(meshFaceIndex); // g3.Index3i vertex_index = mesh.GetTriangle(meshFaceIndex); // faces.Add(meshFaceIndex, new MeshNode(index++, meshFaceIndex, frame, neighbors, vertex_index)); // } // foreach (var f in faces) // { // f.Value.neighbors.Clear(); // f.Value.neighbors.Capacity = 3; // for (int i = 0; i < 3; ++i) // { // int fn = f.Value.neighbors_index[i]; // if (fn >= 0) // f.Value.neighbors.Add(faces[fn]); // } // if (f.Value.neighbors.Count < 3) // { // f.Value.locked = true; // foreach (var n in f.Value.neighbors) // n.locked = true; // } // } // outputMesh = new g3.DMesh3(g3.MeshComponents.None); // listLines = new List<g3.Line3d>(); // listPolylines = new List<g3.PolyLine3d>(); // foreach (var f in faces) // { // outputMesh.AppendVertex(f.Value.frame.Origin); // } // HashSet<int> processedPoints = new HashSet<int>(); // foreach (var f in faces) // { // for (int i = 0; i < 3; i++) // { // List<int> outputLine = new List<int>(); // if (processedPoints.Contains(f.Value.vertex_index[i])) // continue; // int checkVertex = f.Value.vertex_index[i]; // MeshNode currentFaces = f.Value; // MeshNode prevFace = null; // bool fullLoop = false; // while (true) // { // for (int j = 0; j < currentFaces.neighbors.Count; j++) // { // var neighbor = currentFaces.neighbors[j]; // if (neighbor.UsesVertex(checkVertex)) // { // if (neighbor == prevFace) // continue; // if (neighbor == f.Value) // { // fullLoop = true; // break; // Found full loop // } // outputLine.Add(neighbor.index); // prevFace = currentFaces; // currentFaces = neighbor; // j = -1; // } // } // break; // } // if (fullLoop) // { // processedPoints.Add(checkVertex); // var polyline = new g3.PolyLine3d(); // if (outputLine.Count > 2) // { // g3.Vector3d centerPoint = f.Value.frame.Origin; // foreach (var p in outputLine) // centerPoint += outputMesh.GetVertex(p); // centerPoint /= (outputLine.Count + 1); // int center = outputMesh.AppendVertex(centerPoint); // var pS = outputMesh.GetVertex(f.Value.index); // var p0 = outputMesh.GetVertex(outputLine[0]); // var pE = outputMesh.GetVertex(outputLine[outputLine.Count - 1]); // var normal = mesh.GetTriNormal(f.Value.meshIndex); // polyline.AppendVertex(pS); // polyline.AppendVertex(p0); // listLines.Add(new g3.Line3d(pS, p0 - pS)); // var n = MathUtil.Normal(centerPoint, pS, p0); // bool reverseTri = n.Dot(normal) < 0; // if (!reverseTri) // outputMesh.AppendTriangle(center, f.Value.index, outputLine[0]); // else // outputMesh.AppendTriangle(center, outputLine[0], f.Value.index); // for (int j = 0; j < outputLine.Count - 1; j++) // { // var p1 = outputMesh.GetVertex(outputLine[j]); // var p2 = outputMesh.GetVertex(outputLine[j + 1]); // listLines.Add(new g3.Line3d(p1, p2 - p1)); // polyline.AppendVertex(p2); // if (!reverseTri) // outputMesh.AppendTriangle(center, outputLine[j], outputLine[j + 1]); // else // outputMesh.AppendTriangle(center, outputLine[j + 1], outputLine[j]); // } // polyline.AppendVertex(pS); // listLines.Add(new g3.Line3d(pE, pS - pE)); // listPolylines.Add(polyline); // if (!reverseTri) // outputMesh.AppendTriangle(center, outputLine[outputLine.Count - 1], f.Value.index); // else // outputMesh.AppendTriangle(center, f.Value.index, outputLine[outputLine.Count - 1]); // } // } // } // } //} public static void VoronoiMesh(g3.DMesh3 mesh, out g3.DMesh3 outputMesh, out List <g3.Line3d> listLines, out List <g3.PolyLine3d> listPolylines) { System.Collections.Generic.SortedDictionary <int, MeshNode> faces = new System.Collections.Generic.SortedDictionary <int, MeshNode>(); int index = 0; foreach (var meshFaceIndex in mesh.TriangleIndices()) { var frame = mesh.GetTriFrame(meshFaceIndex); g3.Index3i neighbors = mesh.GetTriNeighbourTris(meshFaceIndex); g3.Index3i vertex_index = mesh.GetTriangle(meshFaceIndex); faces.Add(meshFaceIndex, new MeshNode(index++, meshFaceIndex, frame, neighbors, vertex_index)); } foreach (var f in faces) { f.Value.neighbors.Clear(); f.Value.neighbors.Capacity = 3; for (int i = 0; i < 3; ++i) { int fn = f.Value.neighbors_index[i]; if (fn >= 0) { f.Value.neighbors.Add(faces[fn]); } } if (f.Value.neighbors.Count < 3) { f.Value.locked = true; foreach (var n in f.Value.neighbors) { n.locked = true; } } } outputMesh = new g3.DMesh3(g3.MeshComponents.None); listLines = new List <g3.Line3d>(); listPolylines = new List <g3.PolyLine3d>(); foreach (var f in faces) { outputMesh.AppendVertex(f.Value.frame.Origin); } HashSet <int> processedPoints = new HashSet <int>(); foreach (var f in faces) { for (int i = 0; i < 3; i++) { List <int> outputLine = new List <int>(); if (processedPoints.Contains(f.Value.vertex_index[i])) { continue; } int checkVertex = f.Value.vertex_index[i]; MeshNode currentFaces = f.Value; MeshNode prevFace = null; bool fullLoop = false; while (true) { for (int j = 0; j < currentFaces.neighbors.Count; j++) { var neighbor = currentFaces.neighbors[j]; if (neighbor.UsesVertex(checkVertex)) { if (neighbor == prevFace) { continue; } if (neighbor == f.Value) { fullLoop = true; break; // Found full loop } outputLine.Add(neighbor.index); prevFace = currentFaces; currentFaces = neighbor; j = -1; } } break; } if (fullLoop) { processedPoints.Add(checkVertex); var polyline = new g3.PolyLine3d(); if (outputLine.Count > 2) { g3.Vector3d centerPoint = f.Value.frame.Origin; foreach (var p in outputLine) { centerPoint += outputMesh.GetVertex(p); } centerPoint /= (outputLine.Count + 1); int center = outputMesh.AppendVertex(centerPoint); var pS = outputMesh.GetVertex(f.Value.index); var p0 = outputMesh.GetVertex(outputLine[0]); var pE = outputMesh.GetVertex(outputLine[outputLine.Count - 1]); var normal = mesh.GetTriNormal(f.Value.meshIndex); polyline.AppendVertex(pS); polyline.AppendVertex(p0); listLines.Add(new g3.Line3d(pS, p0 - pS)); var n = MathUtil.Normal(centerPoint, pS, p0); bool reverseTri = n.Dot(normal) < 0; if (!reverseTri) { outputMesh.AppendTriangle(center, f.Value.index, outputLine[0]); } else { outputMesh.AppendTriangle(center, outputLine[0], f.Value.index); } for (int j = 0; j < outputLine.Count - 1; j++) { var p1 = outputMesh.GetVertex(outputLine[j]); var p2 = outputMesh.GetVertex(outputLine[j + 1]); listLines.Add(new g3.Line3d(p1, p2 - p1)); polyline.AppendVertex(p2); if (!reverseTri) { outputMesh.AppendTriangle(center, outputLine[j], outputLine[j + 1]); } else { outputMesh.AppendTriangle(center, outputLine[j + 1], outputLine[j]); } } polyline.AppendVertex(pS); listLines.Add(new g3.Line3d(pE, pS - pE)); listPolylines.Add(polyline); if (!reverseTri) { outputMesh.AppendTriangle(center, outputLine[outputLine.Count - 1], f.Value.index); } else { outputMesh.AppendTriangle(center, f.Value.index, outputLine[outputLine.Count - 1]); } } } } } }
protected void Page_Load(object sender, System.EventArgs e) { int.TryParse(base.Request.QueryString["productId"], out this.productId); System.Data.DataSet taobaoProductDetails = ProductHelper.GetTaobaoProductDetails(this.productId); System.Data.DataTable dataTable = taobaoProductDetails.Tables[0]; System.Collections.Generic.SortedDictionary <string, string> sortedDictionary = new System.Collections.Generic.SortedDictionary <string, string>(); sortedDictionary.Add("SiteUrl", Hidistro.Membership.Context.HiContext.Current.SiteUrl); sortedDictionary.Add("_input_charset", "utf-8"); sortedDictionary.Add("return_url", Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("MakeTaobaoProductData_url"))); sortedDictionary.Add("ProductId", this.productId.ToString()); sortedDictionary.Add("HasSKU", dataTable.Rows[0]["HasSKU"].ToString()); sortedDictionary.Add("ProductName", (string)dataTable.Rows[0]["ProductName"]); sortedDictionary.Add("ProductCode", (string)dataTable.Rows[0]["ProductCode"]); sortedDictionary.Add("CategoryName", (dataTable.Rows[0]["CategoryName"] == System.DBNull.Value) ? "" : ((string)dataTable.Rows[0]["CategoryName"])); sortedDictionary.Add("ProductLineName", (dataTable.Rows[0]["ProductLineName"] == System.DBNull.Value) ? "" : ((string)dataTable.Rows[0]["ProductLineName"])); sortedDictionary.Add("BrandName", (dataTable.Rows[0]["BrandName"] == System.DBNull.Value) ? "" : ((string)dataTable.Rows[0]["BrandName"])); sortedDictionary.Add("SalePrice", System.Convert.ToDecimal(dataTable.Rows[0]["SalePrice"]).ToString("F2")); sortedDictionary.Add("MarketPrice", (dataTable.Rows[0]["MarketPrice"] == System.DBNull.Value) ? "0" : System.Convert.ToDecimal(dataTable.Rows[0]["MarketPrice"]).ToString("F2")); sortedDictionary.Add("CostPrice", System.Convert.ToDecimal(dataTable.Rows[0]["CostPrice"]).ToString("F2")); sortedDictionary.Add("PurchasePrice", System.Convert.ToDecimal(dataTable.Rows[0]["PurchasePrice"]).ToString("F2")); sortedDictionary.Add("Stock", dataTable.Rows[0]["Stock"].ToString()); System.Data.DataTable dataTable2 = taobaoProductDetails.Tables[1]; if (dataTable2.Rows.Count > 0) { string text = string.Empty; foreach (System.Data.DataRow dataRow in dataTable2.Rows) { object obj = text; text = string.Concat(new object[] { obj, dataRow["AttributeName"], ":", dataRow["ValueStr"], ";" }); } text = text.Remove(text.Length - 1); sortedDictionary.Add("Attributes", text); } System.Data.DataTable dataTable3 = taobaoProductDetails.Tables[2]; if (dataTable3.Rows.Count > 0) { System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); System.Text.StringBuilder stringBuilder2 = new System.Text.StringBuilder(); for (int i = dataTable3.Columns.Count - 1; i >= 0; i--) { stringBuilder2.Append(dataTable3.Columns[i].ColumnName).Append(";"); } foreach (System.Data.DataRow dataRow2 in dataTable3.Rows) { for (int j = dataTable3.Columns.Count - 1; j >= 0; j--) { stringBuilder.Append(dataRow2[dataTable3.Columns[j].ColumnName]).Append(";"); } stringBuilder.Remove(stringBuilder.Length - 1, 1).Append(","); } stringBuilder2.Remove(stringBuilder2.Length - 1, 1).Append(",").Append(stringBuilder.Remove(stringBuilder.Length - 1, 1)); sortedDictionary.Add("skus", stringBuilder2.ToString()); } System.Data.DataTable dataTable4 = taobaoProductDetails.Tables[3]; if (dataTable4.Rows.Count > 0) { sortedDictionary.Add("Cid", dataTable4.Rows[0]["Cid"].ToString()); if (dataTable4.Rows[0]["StuffStatus"] != System.DBNull.Value) { sortedDictionary.Add("StuffStatus", (string)dataTable4.Rows[0]["StuffStatus"]); } sortedDictionary.Add("ProTitle", (string)dataTable4.Rows[0]["ProTitle"]); sortedDictionary.Add("Num", dataTable4.Rows[0]["Num"].ToString()); sortedDictionary.Add("LocationState", (string)dataTable4.Rows[0]["LocationState"]); sortedDictionary.Add("LocationCity", (string)dataTable4.Rows[0]["LocationCity"]); sortedDictionary.Add("FreightPayer", (string)dataTable4.Rows[0]["FreightPayer"]); if (dataTable4.Rows[0]["PostFee"] != System.DBNull.Value) { sortedDictionary.Add("PostFee", dataTable4.Rows[0]["PostFee"].ToString()); } if (dataTable4.Rows[0]["ExpressFee"] != System.DBNull.Value) { sortedDictionary.Add("ExpressFee", dataTable4.Rows[0]["ExpressFee"].ToString()); } if (dataTable4.Rows[0]["EMSFee"] != System.DBNull.Value) { sortedDictionary.Add("EMSFee", dataTable4.Rows[0]["EMSFee"].ToString()); } sortedDictionary.Add("HasInvoice", dataTable4.Rows[0]["HasInvoice"].ToString()); sortedDictionary.Add("HasWarranty", dataTable4.Rows[0]["HasWarranty"].ToString()); sortedDictionary.Add("HasDiscount", dataTable4.Rows[0]["HasDiscount"].ToString()); if (dataTable4.Rows[0]["PropertyAlias"] != System.DBNull.Value) { sortedDictionary.Add("PropertyAlias", (string)dataTable4.Rows[0]["PropertyAlias"]); } if (dataTable4.Rows[0]["SkuProperties"] != System.DBNull.Value) { sortedDictionary.Add("SkuProperties", (string)dataTable4.Rows[0]["SkuProperties"]); } if (dataTable4.Rows[0]["SkuQuantities"] != System.DBNull.Value) { sortedDictionary.Add("SkuQuantities", (string)dataTable4.Rows[0]["SkuQuantities"]); } if (dataTable4.Rows[0]["SkuPrices"] != System.DBNull.Value) { sortedDictionary.Add("SkuPrices", (string)dataTable4.Rows[0]["SkuPrices"]); } if (dataTable4.Rows[0]["SkuOuterIds"] != System.DBNull.Value) { sortedDictionary.Add("SkuOuterIds", (string)dataTable4.Rows[0]["SkuOuterIds"]); } if (dataTable4.Rows[0]["inputpids"] != System.DBNull.Value) { sortedDictionary.Add("inputpids", (string)dataTable4.Rows[0]["inputpids"]); } if (dataTable4.Rows[0]["inputstr"] != System.DBNull.Value) { sortedDictionary.Add("inputstr", (string)dataTable4.Rows[0]["inputstr"]); } if (dataTable4.Rows[0]["FoodAttributes"] != System.DBNull.Value) { sortedDictionary.Add("FoodAttributes", System.Web.HttpUtility.UrlEncode((string)dataTable4.Rows[0]["FoodAttributes"])); } } System.Collections.Generic.Dictionary <string, string> dictionary = OpenIdFunction.FilterPara(sortedDictionary); System.Text.StringBuilder stringBuilder3 = new System.Text.StringBuilder(); foreach (System.Collections.Generic.KeyValuePair <string, string> current in dictionary) { stringBuilder3.Append(OpenIdFunction.CreateField(current.Key, current.Value)); } sortedDictionary.Clear(); dictionary.Clear(); string action = "http://order1.kuaidiangtong.com/MakeTaoBaoData.aspx"; if (dataTable4.Rows.Count > 0) { action = "http://order1.kuaidiangtong.com/UpdateTaoBaoData.aspx"; } OpenIdFunction.Submit(OpenIdFunction.CreateForm(stringBuilder3.ToString(), action)); }
protected void Page_Load(object sender, System.EventArgs e) { System.Collections.Generic.SortedDictionary <string, string> requestPost = this.GetRequestPost(); if (requestPost.Count > 0) { Notify notify = new Notify(); bool flag = notify.Verify(requestPost, base.Request.Form["notify_id"], base.Request.Form["sign"]); if (flag) { string text = base.Request.Form["success_details"]; try { if (!string.IsNullOrEmpty(text)) { string[] array = text.Split(new char[] { '|' }); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string text2 = array2[i]; string[] array3 = text2.Split(new char[] { '^' }); if (array3.Length >= 8) { BalanceDrawRequestInfo balanceDrawRequestById = DistributorsBrower.GetBalanceDrawRequestById(array3[0]); if (balanceDrawRequestById != null && balanceDrawRequestById.IsCheck != "2") { VShopHelper.UpdateBalanceDrawRequest(int.Parse(array3[0]), "支付宝付款:流水号" + array3[6] + ",支付时间:" + array3[7]); VShopHelper.UpdateBalanceDistributors(balanceDrawRequestById.UserId, decimal.Parse(array3[3])); } } } } string text3 = base.Request.Form["fail_details"]; if (!string.IsNullOrEmpty(text3)) { string[] array4 = text3.Split(new char[] { '|' }); string[] array5 = array4; for (int j = 0; j < array5.Length; j++) { string text4 = array5[j]; string[] array6 = text4.Split(new char[] { '^' }); if (array6.Length >= 8) { BalanceDrawRequestInfo balanceDrawRequestById2 = DistributorsBrower.GetBalanceDrawRequestById(array6[0]); if (balanceDrawRequestById2 != null && balanceDrawRequestById2.IsCheck != "2" && balanceDrawRequestById2.IsCheck != "-1") { DistributorsBrower.SetBalanceDrawRequestIsCheckStatus(new int[] { int.Parse(array6[0]) }, 3, System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + array6[5] + array6[6], array6[3]); } } } } } catch (System.Exception ex) { try { Globals.Debuglog(string.Concat(new string[] { System.DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]"), "验证成功,写入数据库失败->", base.Request.Form.ToString(), "||", ex.ToString() }), "_DebugLogAlipaynotify_url.txt"); } catch (System.Exception) { } } base.Response.Write("success"); return; } base.Response.Write("fail"); try { Globals.Debuglog(System.DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]") + "验证失败2,写入数据库失败->" + base.Request.Form.ToString(), "_DebugLogAlipaynotify_url.txt"); return; } catch (System.Exception) { return; } } base.Response.Write("无通知参数"); }
public StateMachine(string name) : base(name) { stateDict_ = new System.Collections.Generic.SortedDictionary <string, IState <T> >(); }
public StateMachine(T holder) { holder_ = holder; stateDict_ = new System.Collections.Generic.SortedDictionary <string, IState <T> >(); }
public bool CheckSoldProductsParameters(System.Collections.Generic.SortedDictionary <string, string> parameters, out System.DateTime?start_modified, out System.DateTime?end_modified, out string status, out int page_no, out int page_size, out string result) { start_modified = null; end_modified = null; status = string.Empty; page_no = 1; page_size = 10; if (!OpenApiHelper.CheckSystemParameters(parameters, this.site.AppKey, out result)) { return(false); } status = DataHelper.CleanSearchString(parameters["approve_status"]); if (!string.IsNullOrWhiteSpace(status) && status != "On_Sale" && status != "Un_Sale" && status != "In_Stock") { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Product_Status_is_Invalid, "approve_status"); return(false); } if (!string.IsNullOrEmpty(parameters["start_modified"]) && !OpenApiHelper.IsDate(parameters["start_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "start_modified"); return(false); } if (!string.IsNullOrEmpty(parameters["end_modified"]) && !OpenApiHelper.IsDate(parameters["end_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "end_modified"); return(false); } if (!string.IsNullOrEmpty(parameters["start_modified"])) { System.DateTime dateTime; System.DateTime.TryParse(parameters["start_modified"], out dateTime); start_modified = new System.DateTime?(dateTime); if (dateTime > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_Now, "start_modified and currenttime"); return(false); } if (!string.IsNullOrEmpty(parameters["end_modified"])) { System.DateTime dateTime2; System.DateTime.TryParse(parameters["end_modified"], out dateTime2); end_modified = new System.DateTime?(dateTime2); if (dateTime > dateTime2) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_End, "start_modified and end_created"); return(false); } if (dateTime2 > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_modified and currenttime"); return(false); } } } else if (!string.IsNullOrEmpty(parameters["end_modified"])) { System.DateTime dateTime2; System.DateTime.TryParse(parameters["end_modified"], out dateTime2); if (dateTime2 > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_modified and currenttime"); return(false); } } if (!string.IsNullOrEmpty(parameters["order_by"])) { if (parameters["order_by"].Split(new char[] { ':' }).Length != 2) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Format, "order_by"); return(false); } string[] array = parameters["order_by"].Split(new char[] { ':' }); string text = DataHelper.CleanSearchString(array[0]); string a = DataHelper.CleanSearchString(array[1]); if (string.IsNullOrEmpty(text)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Format, "order_by"); return(false); } if (text != "display_sequence" || text != "create_time" || text != "sold_quantity") { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Format, "order_by"); return(false); } if (a != "desc" || a != "asc") { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Format, "order_by"); return(false); } } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && !int.TryParse(parameters["page_size"].ToString(), out page_size)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_size"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && (page_size <= 0 || page_size > 100)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_size"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && !int.TryParse(parameters["page_no"].ToString(), out page_no)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_no"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && page_no <= 0) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_no"); return(false); } return(true); }
private bool CheckSoldTradesParameters(System.Collections.Generic.SortedDictionary <string, string> parameters, out System.DateTime?start_time, out System.DateTime?end_time, out string status, out int page_no, out int page_size, ref string result) { start_time = null; end_time = null; page_size = 10; page_no = 1; status = DataHelper.CleanSearchString(parameters["status"]); if (!OpenApiHelper.CheckSystemParameters(parameters, this.site.AppKey, out result)) { return(false); } if (!string.IsNullOrEmpty(parameters["start_created"]) && !OpenApiHelper.IsDate(parameters["start_created"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "start_created"); return(false); } if (!string.IsNullOrEmpty(parameters["end_created"]) && !OpenApiHelper.IsDate(parameters["end_created"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "end_created"); return(false); } if (!string.IsNullOrEmpty(parameters["start_created"])) { System.DateTime dateTime; System.DateTime.TryParse(parameters["start_created"], out dateTime); start_time = new System.DateTime?(dateTime); if (dateTime > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_Now, "start_created and currenttime"); return(false); } if (!string.IsNullOrEmpty(parameters["end_created"])) { System.DateTime dateTime2; System.DateTime.TryParse(parameters["end_created"], out dateTime2); end_time = new System.DateTime?(dateTime2); if (dateTime > dateTime2) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_End, "start_created and end_created"); return(false); } if (dateTime2 > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_created and currenttime"); return(false); } } } else if (!string.IsNullOrEmpty(parameters["end_created"])) { System.DateTime dateTime2; System.DateTime.TryParse(parameters["end_created"], out dateTime2); if (dateTime2 > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_created and currenttime"); return(false); } } if (!string.IsNullOrWhiteSpace(status) && status != "WAIT_BUYER_PAY" && status != "WAIT_SELLER_SEND_GOODS" && status != "WAIT_BUYER_CONFIRM_GOODS" && status != "TRADE_CLOSED" && status != "TRADE_FINISHED") { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Trade_Status_is_Invalid, "status"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && !int.TryParse(parameters["page_no"].ToString(), out page_no)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_no"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && page_no <= 0) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_no"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && !int.TryParse(parameters["page_size"].ToString(), out page_size)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_size"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && (page_size <= 0 || page_size > 100)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_size"); return(false); } return(true); }
public static bool CheckSign(System.Collections.Generic.SortedDictionary <string, string> tmpParas, string keycode, string sign) { System.Collections.Generic.Dictionary <string, string> dicArray = APIHelper.Parameterfilter(tmpParas); return(APIHelper.BuildSign(dicArray, keycode, "MD5", "utf-8") == sign); }
private bool TryLoadCached() { bool bSuccess = false; string _cachedContent = string.Empty; try { ModuleCachingProvider cache = ModuleCachingProvider.Instance(_ModuleConfiguration.GetEffectiveCacheMethod()); System.Collections.Generic.SortedDictionary<string, string> varyBy = new System.Collections.Generic.SortedDictionary<string, string>(); varyBy.Add("locale", System.Threading.Thread.CurrentThread.CurrentCulture.ToString()); string cacheKey = cache.GenerateCacheKey(_ModuleConfiguration.TabModuleID, varyBy); byte[] cachedBytes =ModuleCachingProvider.Instance(_ModuleConfiguration.GetEffectiveCacheMethod()).GetModule(_ModuleConfiguration.TabModuleID, cacheKey); if (cachedBytes != null && cachedBytes.Length > 0) { _cachedContent = System.Text.Encoding.UTF8.GetString(cachedBytes); bSuccess = true; } } catch (Exception ex) { _cachedContent = string.Empty; bSuccess = false; ex.ToString(); } if (bSuccess) { _Control = new CachedModuleControl(_cachedContent); this.Controls.Add(_Control); } return bSuccess; }
/// <summary> /// 一个构造方法。 /// </summary> public RepeatSortedDictionary() { this.Items = new SortedDictionary <TKey, Item>(); }
static LineCapExtension() { _defaultStyle = new LineCaps.FlatCap(); // first register the old deprecated Gdi styles _deprecatedGdiStyles = new System.Collections.Generic.SortedDictionary<string, LineCapExtension>(); foreach (LineCap cap in Enum.GetValues(typeof(LineCap))) { switch (cap) { case LineCap.AnchorMask: case LineCap.Flat: case LineCap.NoAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), _defaultStyle); break; case LineCap.Square: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.SquareFLineCap(0, 1)); break; case LineCap.Round: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.CircleFLineCap(0, 1)); break; case LineCap.Triangle: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.DiamondFLineCap(0, 1)); break; case LineCap.ArrowAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.ArrowF10LineCap(0, 2)); break; case LineCap.SquareAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.SquareFLineCap(0, 1.5)); break; case LineCap.RoundAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.CircleFLineCap(0, 2)); break; case LineCap.DiamondAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.DiamondFLineCap(0, 2)); break; } } // now the other linecaps _registeredStyles = new System.Collections.Generic.SortedDictionary<string, LineCapExtension>(); var types = Altaxo.Main.Services.ReflectionService.GetNonAbstractSubclassesOf(typeof(LineCapExtension)); foreach (var t in types) { var ex = (LineCapExtension)Activator.CreateInstance(t); _registeredStyles.Add(ex.Name, ex); } // now sort them by name List<string> nameList = new List<string>(_registeredStyles.Keys); nameList.Remove(_defaultStyle.Name); nameList.Sort(); nameList.Insert(0, _defaultStyle.Name); _registeredStylesSortedByName = new List<LineCapExtension>(nameList.Select(x => _registeredStyles[x])); }
/// <summary> /// 一个构造方法。 /// </summary> /// <param name="comparer">在比较键时要使用的 System.Collections.Generic.IComparer<T> 实现;或者为 null,表示为键类型使用默认的 System.Collections.Generic.Comparer<T>。</param> public RepeatSortedDictionary(IComparer <TKey> comparer) { this.Items = new SortedDictionary <TKey, Item>(comparer); }
public Category(string cat, ExcludedWords excluded) { m_Phrases = new SortedDictionary <string, PhraseCount>(); m_Excluded = excluded; m_Name = cat; }
public static System.Collections.Generic.Dictionary <string, string> FilterPara(System.Collections.Generic.SortedDictionary <string, string> dicArrayPre) { System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>(); foreach (System.Collections.Generic.KeyValuePair <string, string> current in dicArrayPre) { if (current.Key.ToLower() != "sign" && current.Key.ToLower() != "sign_type" && current.Value != "" && current.Value != null) { dictionary.Add(current.Key, current.Value); } } return(dictionary); }
public static bool RandomizeMesh(g3.DMesh3 mesh, out g3.DMesh3 outputMesh, double amount, double moveTries) { System.Collections.Generic.SortedDictionary <int, MeshNode> faces = new System.Collections.Generic.SortedDictionary <int, MeshNode>(); int index = 0; foreach (var meshFaceIndex in mesh.TriangleIndices()) { var frame = mesh.GetTriFrame(meshFaceIndex); g3.Index3i neighbors = mesh.GetTriNeighbourTris(meshFaceIndex); g3.Index3i vertex_index = mesh.GetTriangle(meshFaceIndex); faces.Add(meshFaceIndex, new MeshNode(index++, meshFaceIndex, frame, neighbors, vertex_index)); } foreach (var f in faces) { f.Value.neighbors.Clear(); f.Value.neighbors.Capacity = 3; for (int i = 0; i < 3; ++i) { int fn = f.Value.neighbors_index[i]; if (fn >= 0) { f.Value.neighbors.Add(faces[fn]); } } if (f.Value.neighbors.Count < 3) { f.Value.locked = true; foreach (var n in f.Value.neighbors) { n.locked = true; } } } DMesh3 projectMeshCopy = new DMesh3(mesh); outputMesh = new DMesh3(mesh); if (faces.Count == 0) { return(false); } DMeshAABBTree3 treeProject = new DMeshAABBTree3(projectMeshCopy); treeProject.Build(); Random r = new Random(); bool result = false; //for (int i = 0; i < moveTries; i++) //{ double faceArea = 0; foreach (var f in faces) { faceArea += f.Value.TriangleArea(outputMesh); } faceArea /= faces.Count; foreach (var f in faces) { result |= f.Value.Randomize(outputMesh, treeProject, r, amount, moveTries, faceArea); } double newFaceArea = 0; foreach (var f in faces) { newFaceArea += f.Value.TriangleArea(outputMesh); } newFaceArea /= faces.Count; return(result); }
protected void Page_Load(object sender, System.EventArgs e) { int num = 0; System.Collections.Generic.SortedDictionary <string, string> requestPost = this.GetRequestPost(); if (requestPost.Count > 0) { string openIdType = "hishop.plugins.openid.alipay.alipayservice"; OpenIdSettingsInfo openIdSettings = OpenIdHelper.GetOpenIdSettings(openIdType); if (openIdSettings == null) { base.Response.Write("登录失败,没有找到对应的插件配置信息。"); return; } System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); xmlDocument.LoadXml(HiCryptographer.Decrypt(openIdSettings.Settings)); AliPayNotify aliPayNotify = new AliPayNotify(requestPost, base.Request.Form["notify_id"], xmlDocument.FirstChild.SelectSingleNode("Partner").InnerText, xmlDocument.FirstChild.SelectSingleNode("Key").InnerText); string responseTxt = aliPayNotify.ResponseTxt; string a = base.Request.Form["sign"]; string mysign = aliPayNotify.Mysign; if (responseTxt == "true" && a == mysign) { string text = base.Request.Form["receive_address"]; if (!string.IsNullOrEmpty(text)) { System.Xml.XmlDocument xmlDocument2 = new System.Xml.XmlDocument(); xmlDocument2.LoadXml(text); ShippingAddressInfo shippingAddressInfo = new ShippingAddressInfo(); shippingAddressInfo.UserId = Hidistro.Membership.Context.HiContext.Current.User.UserId; if (xmlDocument2.SelectSingleNode("/receiveAddress/address") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/address").InnerText)) { shippingAddressInfo.Address = Globals.HtmlEncode(xmlDocument2.SelectSingleNode("/receiveAddress/address").InnerText); } if (xmlDocument2.SelectSingleNode("/receiveAddress/fullname") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/fullname").InnerText)) { shippingAddressInfo.ShipTo = Globals.HtmlEncode(xmlDocument2.SelectSingleNode("/receiveAddress/fullname").InnerText); } if (xmlDocument2.SelectSingleNode("/receiveAddress/post") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/post").InnerText)) { shippingAddressInfo.Zipcode = xmlDocument2.SelectSingleNode("/receiveAddress/post").InnerText; } if (xmlDocument2.SelectSingleNode("/receiveAddress/mobile_phone") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/mobile_phone").InnerText)) { shippingAddressInfo.CellPhone = xmlDocument2.SelectSingleNode("/receiveAddress/mobile_phone").InnerText; } if (xmlDocument2.SelectSingleNode("/receiveAddress/phone") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/phone").InnerText)) { shippingAddressInfo.TelPhone = xmlDocument2.SelectSingleNode("/receiveAddress/phone").InnerText; } string text2 = string.Empty; string text3 = string.Empty; string text4 = string.Empty; if (xmlDocument2.SelectSingleNode("/receiveAddress/area") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/area").InnerText)) { text2 = xmlDocument2.SelectSingleNode("/receiveAddress/area").InnerText; } if (xmlDocument2.SelectSingleNode("/receiveAddress/city") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/city").InnerText)) { text3 = xmlDocument2.SelectSingleNode("/receiveAddress/city").InnerText; } if (xmlDocument2.SelectSingleNode("/receiveAddress/prov") != null && !string.IsNullOrEmpty(xmlDocument2.SelectSingleNode("/receiveAddress/prov").InnerText)) { text4 = xmlDocument2.SelectSingleNode("/receiveAddress/prov").InnerText; } if (string.IsNullOrEmpty(text2) && string.IsNullOrEmpty(text3) && string.IsNullOrEmpty(text4)) { shippingAddressInfo.RegionId = 0; } else { shippingAddressInfo.RegionId = RegionHelper.GetRegionId(text2, text3, text4); } Hidistro.Membership.Context.SiteSettings arg_371_0 = Hidistro.Membership.Context.HiContext.Current.SiteSettings; if (PersonalHelper.GetShippingAddressCount(Hidistro.Membership.Context.HiContext.Current.User.UserId) < Hidistro.Membership.Context.HiContext.Current.Config.ShippingAddressQuantity) { num = PersonalHelper.AddShippingAddress(shippingAddressInfo); } } } } this.Page.Response.Redirect(Globals.ApplicationPath + "/SubmmitOrder.aspx?shippingId=" + num); }
public KeyCollection(System.Collections.Generic.SortedDictionary <TKey, TValue> dictionary) { }
public void ProcessRequest(System.Web.HttpContext context) { string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; string str2 = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; string str3 = ""; string text = ""; Hidistro.Membership.Context.SiteSettings masterSettings = Hidistro.Membership.Context.SettingsManager.GetMasterSettings(false); new System.Text.StringBuilder(); string text2 = context.Request.QueryString["action"].ToString(); string sign = context.Request.Form["sign"]; string text3 = context.Request.Form["format"]; string checkCode = masterSettings.CheckCode; System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); new System.Collections.Generic.Dictionary <string, string>(); System.Collections.Generic.SortedDictionary <string, string> sortedDictionary = new System.Collections.Generic.SortedDictionary <string, string>(); try { string a; if ((a = text2) != null && a == "distribution_list") { string text4 = context.Request.Form["parma"].Trim(); str3 = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "parma"); if (!string.IsNullOrEmpty(text4)) { str3 = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "sign"); DistributorQuery query = new DistributorQuery(); query = (DistributorQuery)JavaScriptConvert.DeserializeObject(text4, typeof(DistributorQuery)); sortedDictionary = this.GetDistriubots(query); sortedDictionary.Add("action", "distribution_list"); sortedDictionary.Add("format", text3); if (APIHelper.CheckSign(sortedDictionary, checkCode, sign)) { DbQueryResult distributors = DistributorHelper.GetDistributors(query); string format = str + "<response_distributors>{0}<totalcount>{1}</totalcount></response_distributors>"; if (distributors.Data != null) { text = string.Format(format, this.ConvertTableToXml((System.Data.DataTable)distributors.Data), distributors.TotalRecords.ToString()); } else { text = string.Format(format, "", "0"); } } } } } catch (System.Exception ex) { str3 = MessageInfo.ShowMessageInfo(ApiErrorCode.Unknown_Error, ex.Message); } if (text == "") { text = text + str2 + str3; } context.Response.ContentType = "text/xml"; if (text3 == "json") { text = text.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>", ""); xmlDocument.Load(new System.IO.MemoryStream(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(text))); text = JavaScriptConvert.SerializeXmlNode(xmlDocument); context.Response.ContentType = "text/json"; } context.Response.Write(text); }
/// <summary> /// Retrieve all Buggs matching the search criteria. /// </summary> /// <param name="FormData">The incoming form of search criteria from the client.</param> /// <returns>A view to display the filtered Buggs.</returns> private BuggsViewModel GetResults(FormHelper FormData) { // Right now we take a Result IQueryable starting with ListAll() Buggs then we widdle away the result set by tacking on // Linq queries. Essentially it's Results.ListAll().Where().Where().Where().Where().Where().Where() // Could possibly create more optimized queries when we know exactly what we're querying // The downside is that if we add more parameters each query may need to be updated.... Or we just add new case statements // The other downside is that there's less code reuse, but that may be worth it. var fromDate = FormData.DateFrom; var toDate = FormData.DateTo.AddDays(1); IQueryable <Crash> results = null; IQueryable <Bugg> buggResults = null; var skip = (FormData.Page - 1) * FormData.PageSize; var take = FormData.PageSize; var sortedResultsList = new System.Collections.Generic.List <Bugg>(); var groupCounts = new System.Collections.Generic.SortedDictionary <string, int>(); int totalCountedRecords = 0; using (var unitOfWork = new UnitOfWork(new CrashReportEntities())) { var userGroupId = unitOfWork.UserGroupRepository.First(data => data.Name == FormData.UserGroup).Id; // Get every Bugg. var resultsAll = unitOfWork.CrashRepository.ListAll(); // Look at all Buggs that are still 'open' i.e. the last Crash occurred in our date range. results = FilterByDate(resultsAll, FormData.DateFrom, FormData.DateTo); // Filter results by build version. if (!string.IsNullOrEmpty(FormData.VersionName)) { results = results.Where(data => data.BuildVersion == FormData.VersionName); } // Filter by BranchName if (!string.IsNullOrEmpty(FormData.BranchName)) { results = results.Where(da => da.Branch.Equals(FormData.BranchName)); } // Filter by PlatformName if (!string.IsNullOrEmpty(FormData.PlatformName)) { results = results.Where(da => da.PlatformName.Equals(FormData.PlatformName)); } // Run at the end if (!string.IsNullOrEmpty(FormData.SearchQuery)) { try { var queryString = HttpUtility.HtmlDecode(FormData.SearchQuery.ToString()) ?? ""; // Take out terms starting with a - var terms = queryString.Split("-, ;+".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var allFuncionCallIds = new HashSet <int>(); foreach (var term in terms) { var functionCallIds = unitOfWork.FunctionRepository.Get(functionCallInstance => functionCallInstance.Call.Contains(term)).Select(x => x.Id).ToList(); foreach (var id in functionCallIds) { allFuncionCallIds.Add(id); } } // Search for all function ids. OR operation, not very efficient, but for searching for one function should be ok. results = allFuncionCallIds.Aggregate(results, (current, id) => current.Where(x => x.Pattern.Contains(id + "+") || x.Pattern.Contains("+" + id))); } catch (Exception ex) { Debug.WriteLine("Exception in Search: " + ex.ToString()); } } // Filter by Crash Type if (FormData.CrashType != "All") { switch (FormData.CrashType) { case "Crash": results = results.Where(buggInstance => buggInstance.CrashType == 1); break; case "Assert": results = results.Where(buggInstance => buggInstance.CrashType == 2); break; case "Ensure": results = results.Where(buggInstance => buggInstance.CrashType == 3); break; case "CrashAsserts": results = results.Where(buggInstance => buggInstance.CrashType == 1 || buggInstance.CrashType == 2); break; } } // Filter by user group if present if (!string.IsNullOrEmpty(FormData.UserGroup)) { results = FilterByUserGroup(results, userGroupId); } if (!string.IsNullOrEmpty(FormData.JiraId)) { results = results.Where(data => data.Jira == FormData.JiraId); } var CrashByUserGroupCounts = unitOfWork.CrashRepository.ListAll().Where(data => data.User.UserGroupId == userGroupId && data.TimeOfCrash >= fromDate && data.TimeOfCrash <= toDate && data.BuggId != null) .GroupBy(data => data.BuggId) .Select(data => new { data.Key, Count = data.Count() }) .OrderByDescending(data => data.Count) .ToDictionary(data => data.Key, data => data.Count); var CrashInTimeFrameCounts = unitOfWork.CrashRepository.ListAll().Where(data => data.TimeOfCrash >= fromDate && data.TimeOfCrash <= toDate && data.BuggId != null) .GroupBy(data => data.BuggId) .Select(data => new { data.Key, Count = data.Count() }) .OrderByDescending(data => data.Count) .ToDictionary(data => data.Key, data => data.Count); var affectedUsers = unitOfWork.CrashRepository.ListAll().Where(data => data.User.UserGroupId == userGroupId && data.TimeOfCrash >= fromDate && data.TimeOfCrash <= toDate && data.BuggId != null) .Select(data => new { BuggId = data.BuggId, ComputerName = data.ComputerName }) .Distinct() .GroupBy(data => data.BuggId) .Select(data => new { data.Key, Count = data.Count() }) .OrderByDescending(data => data.Count) .ToDictionary(data => data.Key, data => data.Count); var ids = results.Where(data => data.BuggId != null).Select(data => data.BuggId).Distinct().ToList(); buggResults = unitOfWork.BuggRepository.ListAll().Where(data => ids.Contains(data.Id)); //buggResults = results.Where(data => data.BuggId != null).Select(data => data.Bugg).Distinct(); // Grab just the results we want to display on this page totalCountedRecords = buggResults.Count(); buggResults = GetSortedResults(buggResults, FormData.SortTerm, FormData.SortTerm == "descending", FormData.DateFrom, FormData.DateTo, FormData.UserGroup); sortedResultsList = buggResults.ToList(); // Get UserGroup ResultCounts var groups = buggResults.SelectMany(data => data.UserGroups) .GroupBy(data => data.Name) .Select(data => new { Key = data.Key, Count = data.Count() }) .ToDictionary(x => x.Key, y => y.Count); groupCounts = new SortedDictionary <string, int>(groups); foreach (var bugg in sortedResultsList) { if (CrashByUserGroupCounts.ContainsKey(bugg.Id)) { bugg.CrashesInTimeFrameGroup = CrashByUserGroupCounts[bugg.Id]; } else { bugg.CrashesInTimeFrameGroup = 0; } if (CrashInTimeFrameCounts.ContainsKey(bugg.Id)) { bugg.CrashesInTimeFrameAll = CrashInTimeFrameCounts[bugg.Id]; } else { bugg.CrashesInTimeFrameAll = 0; } if (affectedUsers.ContainsKey(bugg.Id)) { bugg.NumberOfUniqueMachines = affectedUsers[bugg.Id]; } else { bugg.NumberOfUniqueMachines = 0; } } sortedResultsList = sortedResultsList.OrderByDescending(data => data.CrashesInTimeFrameGroup).Skip(skip) .Take(totalCountedRecords >= skip + take ? take : totalCountedRecords).ToList(); foreach (var bugg in sortedResultsList) { var Crash = unitOfWork.CrashRepository.First(data => data.BuggId == bugg.Id); bugg.FunctionCalls = Crash.GetCallStack().GetFunctionCalls(); } } System.Collections.Generic.List <SelectListItem> branchNames; System.Collections.Generic.List <SelectListItem> versionNames; System.Collections.Generic.List <SelectListItem> platformNames; using (var unitOfWork = new UnitOfWork(new CrashReportEntities())) { branchNames = unitOfWork.CrashRepository.GetBranchesAsListItems(); versionNames = unitOfWork.CrashRepository.GetVersionsAsListItems(); platformNames = unitOfWork.CrashRepository.GetPlatformsAsListItems(); } return(new BuggsViewModel() { Results = sortedResultsList, PagingInfo = new PagingInfo { CurrentPage = FormData.Page, PageSize = FormData.PageSize, TotalResults = totalCountedRecords }, SortTerm = FormData.SortTerm, SortOrder = FormData.SortOrder, UserGroup = FormData.UserGroup, CrashType = FormData.CrashType, SearchQuery = FormData.SearchQuery, BranchNames = branchNames, VersionNames = versionNames, PlatformNames = platformNames, DateFrom = (long)(FormData.DateFrom - CrashesViewModel.Epoch).TotalMilliseconds, DateTo = (long)(FormData.DateTo - CrashesViewModel.Epoch).TotalMilliseconds, VersionName = FormData.VersionName, PlatformName = FormData.PlatformName, BranchName = FormData.BranchName, GroupCounts = groupCounts, Jira = FormData.JiraId, }); }
public void ProcessRequest(System.Web.HttpContext context) { string text = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; string str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"; string text2 = ""; Hidistro.Membership.Context.SiteSettings masterSettings = Hidistro.Membership.Context.SettingsManager.GetMasterSettings(false); string format = "<trade><Oid>{0}</Oid><SellerUid>{1}</SellerUid><BuyerNick>{2}</BuyerNick><BuyerEmail>{3}</BuyerEmail><ReceiverName>{4}</ReceiverName><ReceiverState>{5}</ReceiverState><ReceiverCity>{6}</ReceiverCity><ReceiverDistrict>{7}</ReceiverDistrict><ReceiverAddress>{8}</ReceiverAddress><ReceiverZip>{9}</ReceiverZip><ReceiverMobile>{10}</ReceiverMobile><ReceiverPhone>{11}</ReceiverPhone><BuyerMemo>{12}</BuyerMemo><OrderMark>{13}</OrderMark><SellerMemo>{14}</SellerMemo><Nums>{15}</Nums><Price>{16}</Price><Payment>{17}</Payment><PostFee>{18}</PostFee><Profit>{19}</Profit><PurchaseTotal>{20}</PurchaseTotal><PaymentTs>{21}</PaymentTs><SentTs>{22}</SentTs><RefundStatus>{23}</RefundStatus><RefundAmount>{24}</RefundAmount><RefundRemark>{25}</RefundRemark><Status>{26}</Status><orders list=\"{27}\">{28}</orders></trade>"; string orderitemfomat = "<order><Tid>{0}</Tid><Oid>{1}</Oid><GoodsIid>{2}</GoodsIid><Title>{3}</Title><OuterId>{4}</OuterId><SKUContent>{5}</SKUContent><Nums>{6}</Nums><Price>{7}</Price><Payment>{8}</Payment><CostPrice>{9}</CostPrice></order>"; System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); string text3 = context.Request.QueryString["action"].ToString(); string sign = context.Request.Form["sign"]; string checkCode = masterSettings.CheckCode; string text4 = context.Request.Form["format"]; System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument(); System.Collections.Generic.SortedDictionary <string, string> sortedDictionary = new System.Collections.Generic.SortedDictionary <string, string>(); string a; if ((a = text3) != null) { if (!(a == "tradelist")) { if (!(a == "tradedetails")) { if (!(a == "send")) { if (a == "mark") { string value = context.Request.Form["order_mark"].Trim(); string text5 = context.Request.Form["seller_memo"].Trim(); if (!string.IsNullOrEmpty(context.Request.Form["tid"].Trim()) && !string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(text5)) { if (System.Convert.ToInt32(value) > 0 && System.Convert.ToInt32(value) < 7) { string text6 = context.Request.Form["tid"].Trim(); sortedDictionary.Add("tid", text6); sortedDictionary.Add("order_mark", value); sortedDictionary.Add("seller_memo", text5); sortedDictionary.Add("format", text4); if (APIHelper.CheckSign(sortedDictionary, checkCode, sign)) { PurchaseOrderInfo purchaseOrder = SalesHelper.GetPurchaseOrder(text6); purchaseOrder.ManagerMark = new OrderMark?((OrderMark)System.Enum.Parse(typeof(OrderMark), value, true)); purchaseOrder.ManagerRemark = Globals.HtmlEncode(text5); if (SalesHelper.SaveAPIPurchaseOrderRemark(purchaseOrder)) { stringBuilder.Append("<trade_get_response>"); stringBuilder.Append(this.GetOrderDetails(format, orderitemfomat, purchaseOrder).ToString()); stringBuilder.Append("</trade_get_response>"); this.message = text + stringBuilder.ToString(); } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Paramter_Error, "save is failure "); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "sign"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Format_Eroor, "order_mark"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "tid or order_mark or seller_memo"); } } } else { string text7 = context.Request.Form["tid"].Trim(); string text8 = context.Request.Form["out_sid"].Trim(); string text9 = context.Request.Form["company_code"].Trim(); if (!string.IsNullOrEmpty(text7) && !string.IsNullOrEmpty(text9) && !string.IsNullOrEmpty(text8)) { sortedDictionary.Add("tid", text7); sortedDictionary.Add("out_sid", text8); sortedDictionary.Add("company_code", text9); sortedDictionary.Add("format", text4); if (APIHelper.CheckSign(sortedDictionary, checkCode, sign)) { ExpressCompanyInfo expressCompanyInfo = ExpressHelper.FindNodeByCode(text9); if (!string.IsNullOrEmpty(expressCompanyInfo.Name)) { ShippingModeInfo shippingModeByCompany = SalesHelper.GetShippingModeByCompany(expressCompanyInfo.Name); PurchaseOrderInfo purchaseOrder2 = SalesHelper.GetPurchaseOrder(text7); if (purchaseOrder2 != null) { ApiErrorCode apiErrorCode = this.SendOrders(purchaseOrder2, shippingModeByCompany, text8, expressCompanyInfo); if (apiErrorCode == ApiErrorCode.Success) { stringBuilder.Append("<trade_get_response>"); purchaseOrder2 = SalesHelper.GetPurchaseOrder(text7); stringBuilder.Append(this.GetOrderDetails(format, orderitemfomat, purchaseOrder2).ToString()); stringBuilder.Append("</trade_get_response>"); this.message = text + stringBuilder.ToString(); } else { text2 = MessageInfo.ShowMessageInfo(apiErrorCode, "It"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.NoExists_Error, "tid"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.NoExists_Error, "company_code"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "sign"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "paramters"); } } } else { if (!string.IsNullOrEmpty(context.Request.Form["tid"].Trim())) { string text6 = context.Request.Form["tid"].Trim(); if (APIHelper.CheckSign(new System.Collections.Generic.SortedDictionary <string, string> { { "tid", context.Request.Form["tid"] }, { "format", text4 } }, checkCode, sign)) { string text10 = context.Request.Form["tid"].Replace("\r\n", "\n"); if (!string.IsNullOrEmpty(text10)) { text6 = text10; PurchaseOrderInfo purchaseOrder3 = SalesHelper.GetPurchaseOrder(text6); stringBuilder.Append("<trade_get_response>"); stringBuilder.Append(this.GetOrderDetails(format, orderitemfomat, purchaseOrder3).ToString()); stringBuilder.Append("</trade_get_response>"); this.message = text + stringBuilder.ToString(); } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Format_Eroor, "tid"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "signature"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "tid"); } } } else { PurchaseOrderQuery purchaseOrderQuery = new PurchaseOrderQuery { PageSize = 100 }; int num = 0; string value2 = context.Request.Form["status"].Trim(); string text11 = context.Request.Form["buynick"].Trim(); string value3 = context.Request.Form["pageindex"].Trim(); string value4 = context.Request.Form["starttime"].Trim(); string value5 = context.Request.Form["endtime"].Trim(); if (!string.IsNullOrEmpty(value2) && System.Convert.ToInt32(value2) >= 0) { purchaseOrderQuery.PurchaseStatus = (OrderStatus)System.Enum.Parse(typeof(OrderStatus), value2, true); } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "status"); } if (!string.IsNullOrEmpty(value3) && System.Convert.ToInt32(value3) > 0) { purchaseOrderQuery.PageIndex = System.Convert.ToInt32(value3); } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "pageindex"); } if (string.IsNullOrEmpty(text2)) { sortedDictionary.Add("status", value2); sortedDictionary.Add("buynick", text11); sortedDictionary.Add("pageindex", value3); sortedDictionary.Add("starttime", value4); sortedDictionary.Add("endtime", value5); sortedDictionary.Add("format", text4); if (APIHelper.CheckSign(sortedDictionary, checkCode, sign)) { if (!string.IsNullOrEmpty(text11)) { purchaseOrderQuery.DistributorName = text11; } if (!string.IsNullOrEmpty(value4)) { purchaseOrderQuery.StartDate = new System.DateTime?(System.Convert.ToDateTime(value4)); } if (!string.IsNullOrEmpty(value5)) { purchaseOrderQuery.EndDate = new System.DateTime?(System.Convert.ToDateTime(value5)); } purchaseOrderQuery.SortOrder = SortAction.Desc; purchaseOrderQuery.SortBy = "PurchaseDate"; stringBuilder.Append("<trade_get_response>"); stringBuilder.Append(this.GetOrderList(purchaseOrderQuery, format, orderitemfomat, out num)); stringBuilder.Append("<totalrecord>" + num + "</totalrecord>"); stringBuilder.Append("</trade_get_response>"); this.message = text + stringBuilder.ToString(); } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Signature_Error, "sign"); } } else { text2 = MessageInfo.ShowMessageInfo(ApiErrorCode.Empty_Error, "paramter"); } } } if (this.message == "") { this.message = this.message + str + text2; } context.Response.ContentType = "text/xml"; if (text4 == "json") { this.message = this.message.Replace(text, ""); xmlDocument.Load(new System.IO.MemoryStream(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(this.message))); this.message = JavaScriptConvert.SerializeXmlNode(xmlDocument); context.Response.ContentType = "text/json"; } context.Response.Write(this.message); }
private void DoValidate() { ErrorLog.Write("标准支付回调开始..."); try { System.Collections.Generic.SortedDictionary <string, string> requestFormPost = this.GetRequestPostForm(); WriteRequestFormToLog(requestFormPost); System.Collections.Generic.SortedDictionary <string, string> requestQueryStringPost = this.GetRequestPostForm(); WriteRequestQueryStringToLog(requestQueryStringPost); } catch { ErrorLog.Write("标准支付回调开始:错误:"); } System.Collections.Specialized.NameValueCollection parameters = new System.Collections.Specialized.NameValueCollection { this.Page.Request.Form, this.Page.Request.QueryString }; this.Gateway = this.Page.Request.QueryString["HIGW"]; ErrorLog.Write("标准支付回调,支持回调Gateway:" + this.Gateway); this.Notify = PaymentNotify.CreateInstance(this.Gateway, parameters); if (this.isBackRequest) { ErrorLog.Write("标准支付回调,支持回调"); this.Notify.ReturnUrl = Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("PaymentReturn_url", new object[] { this.Gateway })) + "?" + this.Page.Request.Url.Query; } this.OrderId = this.Notify.GetOrderId(); this.Order = TradeHelper.GetOrderInfo(this.OrderId); if (this.Order == null) { ErrorLog.Write("标准支付回调,订单不存在:" + this.OrderId); this.ResponseStatus(true, "ordernotfound"); return; } this.Amount = this.Notify.GetOrderAmount(); if (this.Amount <= 0m) { this.Amount = this.Order.GetTotal(); } this.Order.GatewayOrderId = this.Notify.GetGatewayOrderId(); ErrorLog.Write(string.Format("标准支付回调,订单号:{0},网关:{1},流水号:{2}", this.OrderId, this.Gateway, this.Order.GatewayOrderId)); //PaymentModeInfo paymentMode = TradeHelper.GetPaymentMode(this.Order.PaymentTypeId); PaymentModeInfo paymentMode = SalesHelper.GetPaymentMode(this.Gateway); if (paymentMode == null) { ErrorLog.Write(string.Format("标准支付回调,不支持的网关,订单号:{0},网关:{1},流水号:{2}", this.OrderId, this.Gateway, this.Order.GatewayOrderId)); this.ResponseStatus(true, "gatewaynotfound"); return; } if (this.Order.Gateway.ToLower() != this.Gateway.ToLower()) { ErrorLog.Write(string.Format("标准支付回调,变更网关,订单号:{0},网关:{1},流水号:{2},新网关:{3}", this.OrderId, this.Order.Gateway, this.Order.GatewayOrderId, this.Gateway)); PaymentModeInfo paymentType = SalesHelper.GetPaymentMode(this.Gateway); if (paymentType != null) { this.Order.Gateway = this.Gateway; this.Order.PaymentTypeId = paymentType.ModeId; this.Order.PaymentType = paymentType.Name; } } this.Notify.Finished += new System.EventHandler <FinishedEventArgs>(this.Notify_Finished); this.Notify.NotifyVerifyFaild += new System.EventHandler(this.Notify_NotifyVerifyFaild); this.Notify.Payment += new System.EventHandler(this.Notify_Payment); this.Notify.VerifyNotify(30000, HiCryptographer.Decrypt(paymentMode.Settings)); }
// //createListElement // private void createListElement( ref System.Xml.XmlDocument pdoc, string pname, string pcore, System.Collections.Generic.List <pvMetadata.ListtemplateContenttype> ptypestable, System.Collections.Generic.List <pvMetadata.ListtemplateColumn> pfieldstable) { // // Insert ContentTypeRef // System.Xml.XmlNode contenttypes = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes", s_nsMgr); foreach (ListtemplateContenttype typ in ptypestable) { string ContentTypeID; switch (typ.BasedOn) { case "Element": ContentTypeID = "0x01" + "00" + typ.typeGUID; break; case "Annoncering": ContentTypeID = "0x0104" + "00" + typ.typeGUID; break; case "Hyperlink": ContentTypeID = "0x0105" + "00" + typ.typeGUID; break; case "'Kontaktperson": ContentTypeID = "0x0106" + "00" + typ.typeGUID; break; case "'Meddelelse": ContentTypeID = "0x0107" + "00" + typ.typeGUID; break; case "'Opgave": ContentTypeID = "0x0108" + "00" + typ.typeGUID; break; case "'Problem": ContentTypeID = "0x0103" + "00" + typ.typeGUID; break; default: ContentTypeID = "Error" + "00" + typ.typeGUID; break; } System.Xml.XmlElement contenttyperef = pdoc.CreateElement("", "ContentTypeRef", s_ns); System.Xml.XmlComment contenttypescomment = pdoc.CreateComment(typ.SysName); contenttyperef.SetAttribute("ID", ContentTypeID); System.Xml.XmlNode ContentTypeRef0x01 = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]", s_nsMgr); if (ContentTypeRef0x01 == null) { System.Xml.XmlNode lastContentTypeRef = contenttypes.AppendChild(contenttyperef); contenttypes.InsertBefore(contenttypescomment, lastContentTypeRef); } else { System.Xml.XmlNode Folder = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:ContentTypes/mha:ContentTypeRef[@ID=\"0x01\"]/mha:Folder", s_nsMgr); if (Folder != null) { System.Xml.XmlNode copyFolder = Folder.CloneNode(true); contenttyperef.AppendChild(copyFolder); } contenttypes.InsertBefore(contenttypescomment, ContentTypeRef0x01); contenttypes.ReplaceChild(contenttyperef, ContentTypeRef0x01); } } System.Collections.Generic.SortedDictionary <string, ListtemplateColumn> scol = new System.Collections.Generic.SortedDictionary <string, ListtemplateColumn>(); foreach (ListtemplateColumn col in pfieldstable) { scol.Add(col.Seqnr, col); } // // Insert Field in Fields // System.Xml.XmlNode fields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Fields", s_nsMgr); foreach (ListtemplateColumn col in scol.Values) { if (!col.SysCol) { System.Xml.XmlElement fieldref = pdoc.CreateElement("", "Field", s_ns); fieldref.SetAttribute("Name", col.SysName); fieldref.SetAttribute("ID", col.colGUID); fieldref.SetAttribute("DisplayName", "$Resources:" + pcore + "," + col.SysName + ";"); switch (col.KolonneType) { case "Text": fieldref.SetAttribute("Type", "Text"); break; case "Note": fieldref.SetAttribute("Type", "Note"); fieldref.SetAttribute("NumLines", "3"); fieldref.SetAttribute("RichText", "TRUE"); break; case "Choice": fieldref.SetAttribute("Type", "Choice"); break; case "Number": fieldref.SetAttribute("Type", "Number"); fieldref.SetAttribute("Decimals", "0"); break; case "Percentage": fieldref.SetAttribute("Type", "Number"); fieldref.SetAttribute("Percentage", "TRUE"); fieldref.SetAttribute("Min", "0"); fieldref.SetAttribute("Max", "1"); break; case "Currency": fieldref.SetAttribute("Type", "Currency"); fieldref.SetAttribute("Decimals", "2"); break; case "DateOnly": fieldref.SetAttribute("Type", "DateTime"); fieldref.SetAttribute("Format", "DateOnly"); break; case "DateTime": fieldref.SetAttribute("Type", "DateTime"); break; case "Boolean": fieldref.SetAttribute("Type", "Boolean"); break; case "Counter": fieldref.SetAttribute("Type", "Counter"); break; case "Picture": fieldref.SetAttribute("Type", "Picture"); break; case "Hyperlink": fieldref.SetAttribute("Type", "Hyperlink"); break; default: break; } fields.AppendChild(fieldref); } } // // Insert FieldsRef in ViewFields // System.Xml.XmlNode viewfields = pdoc.SelectSingleNode("//mha:List/mha:MetaData/mha:Views/mha:View[@BaseViewID=\"1\"]/mha:ViewFields", s_nsMgr); foreach (ListtemplateColumn col in scol.Values) { if (!col.SysCol) { System.Xml.XmlElement fieldref = pdoc.CreateElement("", "FieldRef", s_ns); fieldref.SetAttribute("ID", col.colGUID); fieldref.SetAttribute("Name", col.SysName); viewfields.AppendChild(fieldref); } } }
public Form1() { InitializeComponent(); // read student input file string[] studentLines = File.ReadAllLines("../../input_01.txt"); // read coures input file string[] courseLines = File.ReadAllLines("../../input_02.txt"); // read majors input file string[] majorLines = File.ReadAllLines("../../input_03.txt"); // add courses to coursePool for (int i = 0; i < courseLines.Length; i++) { Course course = new Course(courseLines[i]); coursePool.Add(course); } // add values to dictionary for (int i = 0; i < studentLines.Length; i++) { string[] tokens = studentLines[i].Split(','); uint zid = Convert.ToUInt32(tokens[0]); Student student = new Student(studentLines[i]); studentPool.Add(zid, student); } // Sort Dictionary by ZID and store in new Dictionary if (studentPool != null) { sortedPool = new SortedDictionary <uint, Student>(studentPool); } // Sort Courses alphabetically var sortedCourses = sortCourses(coursePool); // print courses to second listbox foreach (Course c in sortedCourses) { listBox2.Items.Add(c); } foreach (KeyValuePair <uint, Student> s in sortedPool) { listBox1.Items.Add("z" + s.Key + " ~ " + s.Value.getLastName() + ", " + s.Value.getFirstName()); } foreach (Course c in coursePool) { int index = comboBox3.FindString(c.GetDepartmentCode()); if (index == -1) { comboBox3.Items.Add(c.GetDepartmentCode()); } } //add majors to dropdown foreach (string line in majorLines) { comboBox1.Items.Add((line)); } comboBox2.Items.Add("Freshman"); comboBox2.Items.Add("Sophomore"); comboBox2.Items.Add("Junior"); comboBox2.Items.Add("Senior"); comboBox2.Items.Add("PostBacc"); }
public byte[] CommitTransaction(SortedSet <BaseDataObjectVersion> objects) { System.IO.MemoryStream MS = new System.IO.MemoryStream(); System.IO.MemoryStream MSRP = new System.IO.MemoryStream(); System.IO.BinaryWriter MSBW = new System.IO.BinaryWriter(MS); SortedSet <byte[]> dependencies = new SortedSet <byte[]> (BD2.Core.ByteSequenceComparer.Shared); ChunkHeaderv1 ch = new ChunkHeaderv1(DateTime.UtcNow, ""); MSBW.Write(ch.Version); byte[] chbytes = ch.Serialize(); MSBW.Write(chbytes.Length); MSBW.Write(chbytes); MSBW.Write(1); Console.WriteLine("{0} sections", 1); int n = 0; //foreach (var tup in data) { MSBW.Write(1); Console.WriteLine("Section version is {0}", 1); System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode <BaseDataObjectVersion> > ss = new System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode <BaseDataObjectVersion> > (); System.Collections.Generic.LinkedList <BaseDataObjectVersion> ll = new LinkedList <BaseDataObjectVersion> (); foreach (BaseDataObjectVersion bdo in objects) { if (!ss.ContainsKey(bdo)) { ss.Add(bdo, ll.AddLast(bdo)); } foreach (BaseDataObjectVersion dependency in bdo.GetDependenies()) { byte[] dep = dependency.ChunkID; if (dep == null) { if (ss.ContainsKey(bdo)) { } else { ss.Add(dependency, ll.AddBefore(ss [bdo], dependency)); } } else { if (!dependencies.Contains(dependency.ChunkID)) { dependencies.Add(dependency.ChunkID); } } } } foreach (BaseDataObjectVersion bdo in ll) { n++; System.IO.MemoryStream MST = new System.IO.MemoryStream(); MST.Write(bdo.ObjectType.ToByteArray(), 0, 16); bdo.Serialize(MST, encryptedStorageManager); byte[] bytes = MST.ToArray(); //Console.WriteLine ("Object of type {0} serialized to {1} bytes.", bdo.GetType ().FullName, bytes.Length); { System.IO.MemoryStream MSC = new System.IO.MemoryStream(); System.IO.BinaryWriter BWC = new System.IO.BinaryWriter(MSC); BWC.Write(bytes.Length); MSRP.Write(MSC.ToArray(), 0, 4); } MSRP.Write(bytes, 0, bytes.Length); } byte[] encoded = MSRP.ToArray(); Console.WriteLine("{0} objects encoded in {1} bytes", objects.Count, encoded.Length); MSBW.Write(encoded.Length); MSBW.Write(encoded); //} if (n == 0) { Console.WriteLine("No objects to save, nothing to do"); return(null); } System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create(); Console.WriteLine("{0} dependencies", dependencies.Count); byte[][] deps = new byte [dependencies.Count][]; int depid = 0; foreach (byte[] dep in dependencies) { deps [depid++] = dep; } Console.WriteLine("Writing {0} bytes representing {1} objects to backend", MS.Length, n); byte[] buf = MS.ToArray(); byte[] chunkID = sha.ComputeHash(buf); dataStorage [DefaultStorage].Push(chunkID, buf, deps, userStorage.Sign(chunkID)); foreach (var bdo in objects) { bdo.SetChunkID(chunkID); } return(chunkID); }
static LineCapExtension() { _defaultStyle = new LineCaps.FlatCap(); // first register the old deprecated Gdi styles _deprecatedGdiStyles = new System.Collections.Generic.SortedDictionary <string, LineCapExtension>(); foreach (LineCap cap in Enum.GetValues(typeof(LineCap))) { switch (cap) { case LineCap.AnchorMask: case LineCap.Flat: case LineCap.NoAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), _defaultStyle); break; case LineCap.Square: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.SquareFLineCap(0, 1)); break; case LineCap.Round: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.CircleFLineCap(0, 1)); break; case LineCap.Triangle: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.DiamondFLineCap(0, 1)); break; case LineCap.ArrowAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.ArrowF10LineCap(0, 2)); break; case LineCap.SquareAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.SquareFLineCap(0, 1.5)); break; case LineCap.RoundAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.CircleFLineCap(0, 2)); break; case LineCap.DiamondAnchor: _deprecatedGdiStyles.Add(Enum.GetName(typeof(LineCap), cap), new LineCaps.DiamondFLineCap(0, 2)); break; } } // now the other linecaps _registeredStyles = new System.Collections.Generic.SortedDictionary <string, LineCapExtension>(); var types = Altaxo.Main.Services.ReflectionService.GetNonAbstractSubclassesOf(typeof(LineCapExtension)); foreach (var t in types) { var ex = (LineCapExtension)Activator.CreateInstance(t); _registeredStyles.Add(ex.Name, ex); } // now sort them by name var nameList = new List <string>(_registeredStyles.Keys); nameList.Remove(_defaultStyle.Name); nameList.Sort(); nameList.Insert(0, _defaultStyle.Name); _registeredStylesSortedByName = new List <LineCapExtension>(nameList.Select(x => _registeredStyles[x])); }
private void DoOneTao(string out_trade_no, string trade_status, string trade_no, System.Collections.Generic.SortedDictionary <string, string> sPara) { if (trade_status == "TRADE_SUCCESS" || trade_status == "TRADE_FINISHED") { OneyuanTaoParticipantInfo addParticipant = OneyuanTaoHelp.GetAddParticipant(0, out_trade_no, ""); if (addParticipant == null) { base.Response.Write("success"); Globals.Debuglog(base.Request.Form.ToString(), "_Debuglog.txt"); return; } addParticipant.PayTime = new System.DateTime?(System.DateTime.Now); addParticipant.PayWay = "alipay"; addParticipant.PayNum = trade_no; addParticipant.Remark = "订单已支付:支付金额为¥" + sPara["total_fee"]; if (!addParticipant.IsPay && OneyuanTaoHelp.SetPayinfo(addParticipant)) { OneyuanTaoHelp.SetOneyuanTaoFinishedNum(addParticipant.ActivityId, 0); } else { Globals.Debuglog(base.Request.Form.ToString(), "_Debuglog.txt"); } } else { Globals.Debuglog(base.Request.Form.ToString(), "_Debuglog.txt"); } base.Response.Write("success"); }
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer) { if (_IsCached) { base.RenderContents(writer); } else { if (SupportsCaching() && IsViewMode() && !Common.Globals.IsAdminControl()) { string _cachedOutput = Null.NullString; StringWriter tempWriter = new StringWriter(); _Control.RenderControl(new HtmlTextWriter(tempWriter)); _cachedOutput = tempWriter.ToString(); if (!string.IsNullOrEmpty(_cachedOutput) && (!HttpContext.Current.Request.Browser.Crawler)) { byte[] moduleContent = System.Text.Encoding.UTF8.GetBytes(_cachedOutput); ModuleCachingProvider cache = ModuleCachingProvider.Instance(_ModuleConfiguration.GetEffectiveCacheMethod()); System.Collections.Generic.SortedDictionary<string, string> varyBy = new System.Collections.Generic.SortedDictionary<string, string>(); varyBy.Add("locale", System.Threading.Thread.CurrentThread.CurrentCulture.ToString()); string cacheKey = cache.GenerateCacheKey(_ModuleConfiguration.TabModuleID, varyBy); cache.SetModule(_ModuleConfiguration.TabModuleID, cacheKey, new TimeSpan(0, 0, _ModuleConfiguration.CacheTime), moduleContent); } writer.Write(_cachedOutput); } else { base.RenderContents(writer); } } }
public Form1() { InitializeComponent(); // read student input file string[] studentLines = File.ReadAllLines("../../input_01.txt"); // read coures input file string[] courseLines = File.ReadAllLines("../../input_02.txt"); // read major input file string[] majorLines = File.ReadAllLines("../../input_03.txt"); // read grades input file string[] historyLines = File.ReadAllLines("../../input_04.txt"); // add courses to coursePool list for (int i = 0; i < courseLines.Length; i++) { Course course = new Course(courseLines[i]); coursePool.Add(course); } // add attempt to historyPool list for (int i = 0; i < historyLines.Length; i++) { History attempt = new History(historyLines[i]); historyPool.Add(attempt); } // add values to studentPool dictionary for (int i = 0; i < studentLines.Length; i++) { string[] tokens = studentLines[i].Split(','); uint zid = Convert.ToUInt32(tokens[0]); Student student = new Student(studentLines[i]); studentPool.Add(zid, student); } // Sort Dictionary by ZID and store in new Dictionary if (studentPool != null) { sortedPool = new SortedDictionary <uint, Student>(studentPool); } // Sort Courses alphabetically var sortedCourses = sortCourses(coursePool); // add items to grade_ComboBox addGrades(grade1_ComboBox); // add items to grade_ComboBox addGrades(passReport_ComboBox); // populate the majors in combobox foreach (string line in majorLines) { major_ComboBox.Items.Add((line)); } /* EXTRA CREDIT * topStudents(); * hardestClasses(); */ }
/// <summary> /// Extracts all matching students from project and group them by the scores assigned to the students by the project contact in a dictionary whose key is the score and the value is the list of students who got that score. /// </summary> /// <param name="project">Detached project object which should have had its all properties eagerly loaded, otherwise an exception will be thrown.</param> /// <returns>A dictionary whose key is the score assigned to the list of students in the dictionary's value.</returns> public static IDictionary<ScoreDetail, IList<Student>> GetStudentsForProjectGroupedByScore(Project project) { if (project.Matchings == null || project.Matchings.Count == 0 || project.Matchings.Select(m => m.Student).Count() == 0) throw new ArgumentException("There are no matching students for the project. Make sure all properties of your project was eagerly loaded before it was passed as parameter.", "project"); var unsortedDict = project.Matchings.GroupBy(m => UIParamsAndMessages.ProjectScoreDetails.Where(sd => sd.Score == m.ProjectScore).FirstOrDefault()) .ToDictionary(key => key.Key, value => value.Select(m => m.Student).ToList() as IList<Student>); System.Collections.Generic.SortedDictionary<ScoreDetail,IList<Student>> dict = new System.Collections.Generic.SortedDictionary<ScoreDetail,IList<Student>>(unsortedDict); foreach (ScoreDetail sd in UIParamsAndMessages.ProjectScoreDetails) { if (!dict.Keys.Contains(sd)) dict.Add(sd, new List<Student>()); } return dict; }
private bool CheckIncrementSoldTradesParameters(System.Collections.Generic.SortedDictionary <string, string> parameters, out System.DateTime start_modified, out System.DateTime end_modified, out string status, out int page_no, out int page_size, ref string result) { start_modified = System.DateTime.Now; end_modified = System.DateTime.Now; page_size = 10; page_no = 1; status = DataHelper.CleanSearchString(parameters["status"]); if (!OpenApiHelper.CheckSystemParameters(parameters, this.site.AppKey, out result)) { return(false); } if (!string.IsNullOrWhiteSpace(status) && status != "WAIT_BUYER_PAY" && status != "WAIT_SELLER_SEND_GOODS " && status != "WAIT_BUYER_CONFIRM_GOODS" && status != "TRADE_CLOSED" && status != "TRADE_FINISHED") { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Trade_Status_is_Invalid, "status"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && !int.TryParse(parameters["page_size"].ToString(), out page_size)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_size"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_size"])) && (page_size <= 0 || page_size > 100)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_size"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && !int.TryParse(parameters["page_no"].ToString(), out page_no)) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Parameters_Format_Error, "page_no"); return(false); } if (!string.IsNullOrEmpty(DataHelper.CleanSearchString(parameters["page_no"])) && page_no <= 0) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Page_Size_Too_Long, "page_no"); return(false); } if (string.IsNullOrEmpty(parameters["start_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Missing_Required_Arguments, "start_modified"); return(false); } if (!OpenApiHelper.IsDate(parameters["start_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "start_modified"); return(false); } System.DateTime.TryParse(parameters["start_modified"], out start_modified); if (start_modified > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_Now, "start_modified and currenttime"); return(false); } if (string.IsNullOrEmpty(parameters["end_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Missing_Required_Arguments, "end_modified"); return(false); } if (!OpenApiHelper.IsDate(parameters["end_modified"])) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Invalid_Timestamp, "end_modified"); return(false); } System.DateTime.TryParse(parameters["end_modified"], out end_modified); if (start_modified > end_modified) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_Start_End, "start_modified and end_modified"); return(false); } if ((end_modified - start_modified).TotalDays > 1.0) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_StartModified_AND_EndModified, "start_modified and end_modified"); return(false); } if (end_modified > System.DateTime.Now) { result = OpenApiErrorMessage.ShowErrorMsg(OpenApiErrorCode.Time_End_Now, "end_modified and currenttime"); return(false); } return(true); }